I'm doing a holistic code review of the desloppify codebase. This is Batch 1: Architecture & Coupling, evaluating dimensions: cross_module_architecture, initialization_coupling.
Module-level IO detected in several files (mostly false positives from string matches)
94 files total, 20384 LOC
Please investigate:
Read desloppify/utils.py — why does it have 57 importers? Is it a god module or a legitimate shared utility?
Read desloppify/state.py — what does it export, is it too large?
Read desloppify/cli.py — it has 13 importers, which is unusual for a CLI entry point. Why?
Read desloppify/narrative/init.py and desloppify/narrative/_constants.py — are these re-export facades or real coupling?
Look for module-level side effects: any file that does I/O at import time (not in functions)?
Look for initialization coupling: does import order matter anywhere?
For each file, note:
What it exports / what role it plays
Whether its importer count is justified
Any import-time side effects or initialization coupling
Be thorough — read all 5 files mentioned above plus check desloppify/scoring.py and desloppify/zones.py briefly.
Assistant
I'll conduct a thorough holistic code review of the desloppify codebase, focusing on architecture and coupling. Let me start by reading the key files you mentioned.
Assistant
Now let me check for more information about the state.py file, check for importers, and verify narrative/_constants.py:
User
I'm doing a holistic code review of the desloppify codebase. This is Batch 2: Conventions & Errors, evaluating dimensions: convention_outlier, error_consistency.
commands/_move_py.py and _move_ts.py missing the c (color) utility — is this intentional?
Please investigate:
Read a few commands files (scan.py, show.py, fix_cmd.py, review_cmd.py) to understand the command pattern — do they follow a consistent structure?
Read detectors/ — check 3-4 detector files to see if they follow a consistent pattern. Look at base.py plus a few others.
Look at error handling patterns: do commands use try/except consistently? Do detectors handle errors the same way?
Check the _move_py.py and _move_ts.py files — why don't they import c (color utility)?
Check desloppify/init.py and desloppify/main.py — are these following the package conventions?
For each observation, note the specific files and whether the inconsistency is intentional or accidental.
Assistant
Now let me search for importers of these modules to understand the coupling better:
Assistant
I'll conduct a systematic investigation of the conventions and error handling patterns in the desloppify codebase. Let me start by exploring the structure and then examining specific files.
Assistant
Now let me read the key files to understand patterns:
Assistant
Now let me check for module-level side effects more systematically:
User
I'm doing a holistic code review of the desloppify codebase. This is Batch 3: Abstractions & Dependencies, evaluating dimensions: abstraction_fitness, dependency_health.
Read desloppify/utils.py — is it a coherent utility module or a dumping ground? What categories of functions does it contain? Should any be split out?
Read desloppify/lang/typescript/fixers/common.py — what does it provide? Is it well-scoped?
Check if there are any abstraction issues: wrappers that add no value, premature generalizations, etc.
Look at the dependency structure — does desloppify/lang/base.py have a clear role, or does it mix concerns?
Check desloppify/registry.py — is the detector registry well-scoped?
For each file, note its LOC, what it does, and whether its abstraction level is appropriate.
Assistant
Now let me check the review_cmd.py and investigate the _move files:
Assistant
I'll conduct a systematic investigation of the abstraction and dependency health of the desloppify codebase. Let me start by examining the key utility and shared files you've mentioned.
Assistant
Now let me examine the detector files to understand patterns:
Assistant
Now let me examine the zone classification and check for any additional dependency or abstraction concerns:
Assistant
Now let me check the cli.py more fully and review the imports to understand why it has 13 importers:
User
I'm doing a holistic code review of the desloppify codebase. This is Batch 4: Testing & API, evaluating dimensions: test_strategy, api_surface_coherence.
Read desloppify/narrative/_constants.py — what does it contain and why is it untested?
Check the tests/ directory — what test files exist? Read tests/test_narrative.py briefly to see coverage patterns.
Check API surface coherence: read desloppify/lang/base.py to see the LangConfig interface — is the API consistent across language plugins?
Compare desloppify/lang/python/init.py and desloppify/lang/typescript/init.py — do they implement the same interface consistently?
Look at the command interface: do all commands follow the same pattern for args, state, output?
For each observation, note specific files and line numbers.
Assistant
Now let me check the state.py and scoring.py to understand how dependencies flow and if there are any abstraction issues:
Assistant
Let me continue reading detectors and check more patterns:
Assistant
I'll conduct a thorough investigation of the testing and API dimensions for this holistic code review. Let me start by examining the files you've identified.
Assistant
Let me examine the issue with utils.py more carefully and check what's being imported:
Assistant
Let me check the main.py and use Grep to analyze error patterns:
Assistant
Now let me check a few more key files to understand the dependencies and identify any abstraction issues:
Assistant
Let me get more detailed information about utils imports:
Assistant
Now let me check the test files and review command interface patterns:
Assistant
Now let me look at specific module-level code that might have side effects:
Assistant
Now let me search for error handling and return patterns in more depth:
Assistant
Let me check a couple more key files to understand the dependency structure better:
Assistant
Now let me examine the command interface patterns and check for consistency:
Assistant
Now let me examine which modules actually import utils to understand the scope of coupling:
Assistant
Now let me check imports in the move files specifically:
Assistant
Now let me check if there are any wrapper functions that add no value by examining a couple of detector files:
Assistant
Let me get the full list:
Assistant
Now let me check how narrative is imported and used, and see what test coverage exists:
Assistant
Perfect. Now let me check if there's a broader pattern with c imports across commands:
Assistant
Now let me analyze what specific exports are being used from utils:
Assistant
Let me check some abstract functions in lang/base.py to see if there are any premature generalizations or wrappers that add no value:
Assistant
Now let me check the command interface consistency more deeply and look at the cli.py:
Assistant
Perfect. Now let me check for initialization coupling by examining import order dependencies:
Assistant
Excellent! Now let me verify where c is actually used in the move files:
Assistant
Let me check a few more things about API consistency and test coverage:
Assistant
Perfect. Now let me gather final information about the narrative module and check for any cross-cutting concerns:
Assistant
Perfect! Now let me check the main.py file to understand the package entry point:
Assistant
Excellent. Now let me create a comprehensive analysis document by examining a few more cross-cutting concerns:
Assistant
Now let me check the _EXCLUDED_ZONES duplication mentioned in the memory:
Assistant
Perfect. Now let me check how importers are distributed across the constants file:
Assistant
Now let me create a comprehensive summary by reading a few more detector error patterns:
Assistant
Excellent. Now let me create a comprehensive summary by examining key function exports from the critical modules:
Assistant
Let me check error handling in detectors more carefully:
Assistant
Excellent! Now let me create a comprehensive summary. Let me check a few more details on command patterns:
Assistant
Now I have enough information to write a comprehensive report. Let me compile the findings:
Assistant
Perfect! Now let me do one final check on import cycles and initialization ordering:
Assistant
Excellent! Now let me verify the narrative package structure:
Assistant
Perfect! Now let me create a comprehensive holistic code review document with all findings:
Assistant
Perfect. Now I have all the information I need. Let me compile a comprehensive holistic review report.
Based on systematic investigation of command files, detectors, and error handling patterns, here are my findings:
1. COMMAND STRUCTURE & CONVENTIONS - Consistent Pattern Found
Status: CONSISTENT ✓
All command files (scan.py, show.py, fix_cmd.py, review_cmd.py, etc.) follow a consistent architectural pattern:
Main entry point: cmd_<name>(args) function
Helper functions prefixed with _ for internal use
Imports from ..utils, ..cli, ..state at the top
Use color utility c() from utils for colored terminal output
Call _write_query() at the end to persist structured JSON for LLM consumption
Examples:
/Users/user_c042661f/Documents/desloppify/desloppify/commands/scan.py (line 5): from ..utils import c
/Users/user_c042661f/Documents/desloppify/desloppify/commands/show.py (line 6): from ..utils import c
/Users/user_c042661f/Documents/desloppify/desloppify/commands/fix_cmd.py (line 7): from ..utils import c
/Users/user_c042661f/Documents/desloppify/desloppify/commands/review_cmd.py (line 7): from ..utils import c
2. MISSING IMPORT IN HELPER MODULES - Minor Inconsistency
Status: INTENTIONAL DESIGN ✓
Finding: The files _move_py.py and _move_ts.py do NOT import the color utility c().
Evidence:
_move_py.py imports: os, re, Path, PROJECT_ROOT, _dedup only
_move_ts.py imports: os, Path, SRC_PATH, _dedup only
Grep analysis shows 0 usages of c() in both files
Explanation: These are helper modules that compute import replacements—they are pure functions with no user-facing output. They never print to terminal. The parent module (line 9) imports and handles all terminal output.
Assistant
Perfect! Now I have enough information to provide a comprehensive holistic review. Let me compile my findings:
The desloppify codebase demonstrates generally sound abstraction design with clear separation of concerns. However, there are several areas where abstractions could be tightened, and a few concerns about mutable global state and dependency overloading. Overall health is good with minor structural issues.
✓ SAFE: All I/O is in functions, not at module level
NO_COLOR = os.environ.get("NO_COLOR") is not None — environment variable evaluation at import (intentional, read-only)
PROJECT_ROOT — computed at import time from environment/cwd (necessary for path root)
_extra_exclusions — mutable module-level tuple initialized empty (set via set_exclusions())
Is it a god module?
YES, but JUSTIFIED. Here's why:
Legitimate cohesion: Everything in utils.py is genuinely utility-level (paths, I/O, colors, text). No business logic.
No artificial grouping: Can't be split without creating artificial modules (e.g., "PathUtils", "ColorUtils") that would only be imported by one caller each.
User
I need to understand the full end-to-end workflow after holistic review findings are imported in the desloppify codebase. Specifically:
Read desloppify/commands/plan_cmd.py — what does the plan command output? Does it include review/holistic findings?
Read desloppify/commands/next.py — what does next recommend? Does it surface holistic review findings?
Read desloppify/commands/status.py — what does status show? How does scoring work for holistic findings?
Read desloppify/commands/resolve.py — how do findings get resolved? Can holistic findings auto-resolve?
Read desloppify/commands/scan.py — what happens when you re-scan after fixing a holistic finding? Does the score update?
Check desloppify/scoring.py — how are holistic review findings (file=".") scored differently from per-file findings?
For each command, note:
Does it handle holistic (file=".") findings?
Does it include narrative context?
What's the output format (terminal, file, query.json)?
What does the user do AFTER running this command?
The goal is to understand: after review --import, what's the user journey to improve their score?
Assistant
I'll systematically explore the command files and scoring logic to understand the end-to-end workflow. Let me start with parallel reads of the key command files.
Assistant
Now let me read the scan command and scoring logic:
Assistant
Let me continue reading the scoring.py file:
Assistant
Now let me check the plan.py file to understand how findings flow to the next/plan commands:
Assistant
Now let me check the show command to understand how it displays findings:
Assistant
Now let me check how holistic findings are currently handled in the review import logic:
Assistant
Now let me check the review.py file to see how holistic findings are created and imported:
Assistant
Let me search for the import_holistic_findings function specifically:
Assistant
Perfect! Now let me check the state.py file to understand how findings flow through merge_scan and scoring:
Assistant
Now let me look at how scoring is computed from findings, particularly with dimension_scores:
Assistant
Excellent! Now let me create a comprehensive report. Let me check one more thing - the narrative's handling of holistic findings:
Assistant
Perfect! Now I have enough information to create a comprehensive workflow analysis. Let me prepare the report.
End-to-End Workflow After Holistic Review Import
I've analyzed the complete workflow for holistic review findings in desloppify. Here's the comprehensive flow:
1. HOLISTIC FINDINGS STRUCTURE & IMPORT
How they're created (review.py:import_holistic_findings):
Holistic findings are stored as file="." (codebase-wide, not per-file)
They contain detail.holistic=True flag
They include detail.related_files=[] list of affected files
They are all tier=3 (judgment call complexity)
They flow through the standard merge_scan() path
Scoring credit (scoring.py:59-60, 115-119):
Holistic findings have a 10x weight multiplier (HOLISTIC_MULTIPLIER = 10.0)
They bypass per-file caps (only regular file-based findings are capped at 1.0 per file)
They add HOLISTIC_POTENTIAL = 10 to the review detector's potential pool (one-time, tracked in review_cache.holistic)
2. HOW SCORING CHANGES AFTER IMPORT
State recomputation (triggered by save_state() → _recompute_stats() → _update_objective_health()):
Metric
Impact
dimension_scores["Design quality"]
Recalculated because it contains "review" detector
objective_score
Recalculated as tier-weighted average of all dimensions
objective_strict
Recalculated (includes "wontfix" in failures)
score / strict_score
Legacy progress-based scores (recomputed from status counts)
Key formula (scoring.py:_detector_pass_rate lines 115-139):
python
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
Initial Request: User asked to implement a plan for "Make Holistic Review Self-Evident for Agent Users" with specific changes to review.py, review_cmd.py, and tests.
Plan Details: The plan had 3 main problems to solve:
Missing narrative in review_cmd.py (only command not calling compute_narrative)
Not self-contained query.json (no file content, no workflow instructions)
Added _extract_imported_names() for sibling behavior
Added sibling behavior analysis in _build_holistic_context_inner()
Added excerpts to god_modules and util_files
Added _build_investigation_batches()
Added _HOLISTIC_WORKFLOW list
Updated prepare_holistic_review() with workflow and batches
Updated convention_outlier prompt
Implementation Phase 2 - review_cmd.py changes:
Added compute_narrative() to _do_prepare() and _do_import()
Added investigation batch printing in holistic mode
Added narrative to per-file prepare _write_query()
Bug Fix: Test test_detects_outlier failed because files with no imports weren't tracked in dir_imports, so they couldn't be flagged as outliers. Fixed by removing the if names: guard.
Tests passed: 56 holistic tests pass, full suite 1809 pass (excluding pre-existing scorecard/ts_patterns failures).
User asked to "run it for this repo, imagine you're an agent": I went through the full holistic review workflow:
Read query.json
Ran 4 investigation batches in parallel using Task agents
Synthesized findings
Wrote holistic_findings.json with 4 findings
Imported via review --import
Resolved 3 stale findings from prior attempt
User asked about the path to fixing findings: "what would they do next?" - I traced the full workflow and identified gaps.
User
Investigate the scorecard color test failures. The tests in tests/test_scorecard.py expect specific RGB tuples from _score_color() but the actual implementation returns different values. Read both files:
tests/test_scorecard.py - to see what values tests expect
desloppify/scorecard.py - to see the actual _score_color() implementation
Tell me: what colors does the implementation actually produce, and what do tests expect? The goal is to update the tests to match the implementation (the implementation was intentionally changed).
Assistant
I'll investigate the scorecard color test failures by reading both files to compare the expected vs actual values.
Assistant
Now I can clearly see the discrepancy. Let me compare the expected vs actual color values:
Summary of Color Test Failures
The tests expect specific RGB tuples from _score_color(), but the implementation produces completely different values. Here's the detailed breakdown:
Implementation's Actual Colors (from scorecard.py, lines 20-33):
High scores (≥90): Implementation uses (68, 120, 68) but tests expect (88, 129, 87) — a lighter/brighter sage green
Mid scores (70-89): Implementation uses (120, 140, 72) (olive) but tests expect (178, 148, 72) (mustard/golden) — much more yellow/orange
Low scores (<70): Implementation uses (145, 155, 80) (yellow-green) but tests expect (168, 90, 90) (dusty rose/coral) — completely different hue and saturation
The tests are checking for the OLD color scheme (sage green → mustard → dusty rose), while the implementation was intentionally changed to use a NEW color scheme (sage green → olive green → yellow-green) with different muted variants (peachy/apricot tones instead of the strict column colors).
User
Investigate the ts_patterns test failure. The test test_fragmentation_detected_with_enough_areas in tests/test_ts_patterns.py expects total_areas >= 5 but gets total_areas == 1.
Read:
tests/test_ts_patterns.py - the failing test
desloppify/lang/typescript/detectors/patterns.py - the detect_pattern_anomalies implementation
The test creates 6 directories like area1/sub/, area2/sub/ etc with .ts files but only 1 area is detected. Figure out why - is it a file discovery issue (not finding the temp files) or an area counting issue?
Assistant
I'll investigate the test failure by reading both the test file and the implementation.
Assistant
Now let me check the get_area() function to understand how it classifies paths into areas:
Assistant
Now let me check the find_ts_files() function to see how it discovers files:
Assistant
Now let me look at the rel() function to understand how it converts absolute paths to relative paths:
Assistant
Now let me trace through the test more carefully. Let me run the actual test to see what's happening:
Assistant
The test is reporting total_areas == 1, which means the census is only finding 1 area when it should find 6. This is a file discovery issue. Let me create a quick debugging script to understand what's happening:
Assistant
Perfect! I found the issue. The problem is in the rel() function in patterns.py. Let me trace through what's happening:
find_ts_files() discovers 6 files correctly
Files are being returned as absolute paths starting with ../../../../var/folders/...
rel() is called on these paths but it's trying to compute relative_to(PROJECT_ROOT) where PROJECT_ROOT is the temp directory
Since the file paths are outside the temp directory (they're in the system's /private/var/folders/...), the relative_to() call fails
The fallback with os.path.relpath() returns ../.. for all of them
The issue is in patterns.py line 98 - it calls rel(filepath) on the output of find_ts_files():
python
rpath = rel(filepath)
area = get_area(rpath)
Let me check what find_ts_files() actually returns and trace the issue more carefully:
Assistant
Good! So when PROJECT_ROOT is set correctly to the tmp directory during the test, _find_source_files_cached returns proper relative paths like editor/sub/main.ts. Let me check what the test fixture actually does with PROJECT_ROOT:
Assistant
The test fixture sets PROJECT_ROOT in both utils_mod and det_mod. But look at line 17 - it clears the cache, which is good. However, let me look at the actual problem in patterns.py more carefully:
Assistant
Aha! I see the problem now. Look at line 98:
python
rpath = rel(filepath)
The filepath returned from find_ts_files(path) is already a relative path (like editor/sub/main.ts). But rel() expects to work with either absolute paths or paths relative to PROJECT_ROOT. Since filepath is a relative path and rel() tries to call Path(path).resolve(), it will be resolved relative to the current working directory, not PROJECT_ROOT.
Let me verify this is the issue:
Assistant
Perfect! I've found the root cause. Let me now provide a clear summary of the investigation:
Investigation Summary
I've identified the root cause of the test failure. The problem is an area counting issue in patterns.py.
The Problem
In patterns.py at line 98, the code calls rel(filepath) on paths returned from find_ts_files():
python
files = find_ts_files(path) # Returns relative paths like 'editor/sub/main.ts'
for filepath in files:
rpath = rel(filepath) # BUG: rel() doesn't handle relative paths correctly
area = get_area(rpath)
Why This Breaks
find_ts_files() returns relative paths — e.g., editor/sub/main.ts (relative to PROJECT_ROOT)
rel() assumes absolute paths or paths resolvable from cwd — When given a relative path, Path(filepath).resolve() resolves it relative to the current working directory (/Users/user_c042661f/Documents/desloppify), NOT relative to PROJECT_ROOT
Result: All paths become unrelated "../../" — Since the resolved path doesn't exist under PROJECT_ROOT, the fallback os.path.relpath() computes the relative path from temp directory to the actual CWD, resulting in all 6 files mapping to the same area ../..
Census only sees 1 unique area — get_area("../..") → "../.." for all files, so the census dict ends up with only 1 key instead of 6
The Fix
The fix should be in patterns.py line 98. Since filepath is already a relative path from find_ts_files(), it should be used directly without calling rel():
Current (buggy):
python
rpath = rel(filepath)
area = get_area(rpath)
Should be:
python
area = get_area(filepath) # filepath is already relative to PROJECT_ROOT
The rel() call is unnecessary and harmful here because:
filepath is already in the correct relative form
get_area() expects a relative path (it splits on /)
The fallback path reading on line 100 already handles both absolute and relative paths correctly
File Paths
Test file:/Users/user_c042661f/Documents/desloppify/tests/test_ts_patterns.py
I need to understand how the narrative system guides agents to the next step. Specifically:
Read desloppify/narrative/actions.py — how are actions computed? What determines the "suggested next" command? How does the subjective_review detector get surfaced as an action?
Read desloppify/narrative/strategy.py — how does strategy/hint generation work?
Read desloppify/narrative/headline.py — how is the headline computed?
Read desloppify/narrative/core.py — how does compute_narrative() orchestrate everything?
For each, summarize the key functions and how they connect. I want to understand: if I wanted to add a new narrative action like "N issues need attention — work through .desloppify/issues/" or change the "86 files need design review" action to point to a different command, where would I change that?
Assistant
I'll read the narrative system files to understand how actions and guidance are computed.
User
I need to understand how review findings get imported and how they flow through the system. Read these files and trace the data flow:
desloppify/review.py — specifically import_review_findings() and import_holistic_findings(). How do they create findings? What does the diff look like? Also look at generate_remediation_plan() — this is what we'll replace with per-issue docs.
desloppify/state.py — specifically merge_scan() and _upsert_findings(). How do findings get merged? How does auto-resolution work? What's make_finding()?
desloppify/commands/fix_cmd.py — specifically _cmd_fix_review(). This is the current "fix review" path. How does it prepare review data?
Check what's in desloppify/scoring.py — what's HOLISTIC_MULTIPLIER, HOLISTIC_POTENTIAL, CONFIDENCE_WEIGHTS? These are used for score impact estimation.
desloppify/commands/scan.py — look at _print_llm_summary() and how the scan output guides agents.
I want to understand: when review findings are imported, what happens? How would I change the import path to write individual issue docs instead of (or in addition to) updating state? And how does the score impact get calculated?
Assistant
I'll trace the review findings flow through the system. Let me read these files in parallel.
User
I need to understand the resolve flow and .desloppify directory structure:
Find and read the resolve command implementation. Search for cmd_resolve or similar in desloppify/commands/. How does resolving a finding work? What statuses are available? Could we hook into resolve to clean up issue docs?
Check what files currently live in .desloppify/ — what's the existing directory structure? Is there already an issues/ directory?
Read desloppify/utils.py — look for safe_write_text, PROJECT_ROOT, and any file I/O helpers we could reuse.
Look at desloppify/commands/next.py — how does the "next" command work? It suggests the next thing to fix. Could this be adapted to point agents to issue docs?
Search for any existing pattern where desloppify writes markdown files or manages a directory of documents.
I want to understand: what's the cleanest way to manage .desloppify/issues/ docs, hook cleanup into the resolve command, and make the "next" command aware of issue docs?
Assistant
I'll systematically explore the resolve flow, directory structure, and related utilities. Let me start with parallel searches.
Assistant
Good! Now let me read the resolve command and related files.
Assistant
Now let me check the state.py for the resolve_findings function and understand the available statuses:
Assistant
Now let me read the full resolve_findings function:
Assistant
Good! Now let me check if there's any pattern of markdown file generation in the codebase:
Assistant
Let me check plan_cmd.py and review.py for examples of markdown generation:
Assistant
Now let me check the plan.py to see how markdown generation works:
Assistant
Perfect! I now have a complete understanding of the narrative system. Let me synthesize this for you.
Summary: Narrative System Architecture
High-Level Flow
compute_narrative() in core.py is the single entry point that orchestrates all narrative computation:
This is where you would change action descriptions and commands. It processes four action types in order:
Auto-fix actions (lines 31–67): For detectors with action_type="auto_fix" in DETECTOR_TOOLS
For TypeScript: creates "desloppify fix {fixer} --dry-run"
For Python: converts to manual fix instead: "desloppify show {det} --status open"
Reorganize actions (lines 69–89): For detectors with action_type="reorganize"
Uses tool_info.get("guidance") from DETECTOR_TOOLS
Points to: "desloppify show {det} --status open"
Refactor actions (lines 91–119): For detectors with action_type="refactor" or "manual_fix"
Special case for subjective_review (lines 103–105):
python
if det == "subjective_review":
command = "desloppify fix review"
description = f"{count} files need design review — run design review with dimension templates"
The resolve command handles finding status changes:
python
def cmd_resolve(args):
"""Resolve finding(s) matching one or more patterns."""
from ..state import load_state, save_state, resolve_findings
if args.status == "wontfix" and not args.note:
print(c("Wontfix items become technical debt. Add --note to record your reasoning for future review.", "yellow"))
sys.exit(1)
sp = _state_path(args)
state = load_state(sp)
prev_score = state.get("score", 0)
all_resolved = []
for pattern in args.patterns:
resolved = resolve_findings(state, pattern, args.status, args.note)
all_resolved.extend(resolved)
if not all_resolved:
print(c(f"No open findings matching: {' '.join(args.patterns)}", "yellow"))
return
save_state(state, sp)
# ... compute narrative, write query.json
_write_query({"command": "resolve", "patterns": args.patterns, "status": args.status,
"resolved": all_resolved, "count": len(all_resolved), ...})
Available Statuses (from /Users/user_c042661f/Documents/desloppify/desloppify/state.py and /Users/user_c042661f/Documents/desloppify/desloppify/cli.py):
fixed — User manually fixed the finding
wontfix — Intentional technical debt (requires --note for reasoning)
false_positive — Not actually an issue
User
I need to design an implementation plan for replacing the monolithic remediation plan with per-issue documents in a Python CLI tool called desloppify.
desloppify fix review or desloppify review --prepare — prepares context for agent evaluation
Agent evaluates, writes findings.json
desloppify review --import findings.json [--holistic] — ingests findings into state, currently generates ONE monolithic holistic-plan.md
Agent/user works through the plan
desloppify resolve fixed "<id>" — marks finding resolved
desloppify scan — re-scan, loop
What We Want
Replace the monolithic plan with per-issue documents in .desloppify/issues/. The new flow:
Scan → automated findings + "N files need review" (same as now)
Triage → agent evaluates each file/issue. Three outcomes:
Fine (score ≥ threshold): mark reviewed, no action
Small fix: fix inline, resolve finding
Needs work: create .desloppify/issues/<short-id>.md with a self-contained work order
Fix → agent reads .desloppify/issues/, works through docs. Each doc is self-contained.
Re-scan → loop
Key Design Points
Issue Docs
One markdown file per finding that needs work
Location: .desloppify/issues/<short-id>.md
Contains: problem, evidence, suggested fix, files to modify, resolve command
Created during review import (replaces generate_remediation_plan())
Cleaned up when finding is resolved
Where Issue Docs Get Created
Currently import_review_findings() and import_holistic_findings() in review.py create findings and call merge_scan(). The generate_remediation_plan() function (lines 1449-1577 in review.py) already computes per-finding data with impact scores — it just writes them all to one file.
Assistant
I'll explore the codebase thoroughly to understand the current architecture before designing the plan.
Assistant
Now let me read the remaining critical files.
Assistant
Now let me check the remaining key files -- the state module, utils, and the CLI argument parser.
Assistant
Let me check the safe_write_text utility and the resolve_findings function in state.py, plus the fix_cmd.py to understand the fix review flow.
Assistant
Let me also check the existing holistic-plan.md referenced in _HOLISTIC_WORKFLOW and the registry to understand the detector tools structure.
Assistant
Now let me look at the plan command output to understand the existing plan generation.
Assistant
Now I have a thorough understanding of the codebase. Let me design the implementation plan.
Implementation Plan: Per-Issue Documents
After thorough exploration of the codebase, here is the complete design.
Answers to Design Questions
1. New module or add to review.py?
Create a new desloppify/issues.py module. review.py is already 1592 lines and is focused on context building, file selection, and finding import. Issue doc lifecycle (create, list, clean up, read) is a separate concern. The new module will be small (~200 lines) and import from review.py only the scoring logic it needs.
2. Short ID format:
Use the first 8 characters of the finding ID's SHA-256 hash. Finding IDs like review::desloppify/state.py::naming_quality::_recompute_stats::a1b2c3d4 are too long for filenames. The hash gives collision-free short IDs. Include a mapping comment in the markdown header (the full finding ID) so resolve can look it up.
Actually, a better approach: use a human-readable slug derived from the finding data. Format: {dimension_short}-{identifier}-{hash8}.md. For example: naming-recompute_stats-a1b2c3d4.md or arch-god-modules-f3e2d1c0.md. This makes ls .desloppify/issues/ immediately scannable by humans and agents. The full finding ID goes inside the document.
3. Should desloppify show review list issue docs?
No. show review already shows review findings from state. Issue docs are a parallel artifact -- adding a one-liner to show output mentioning the count of issue docs is sufficient: "N issue docs in .desloppify/issues/".
4. Should there be a desloppify issues command?
No. ls .desloppify/issues/ is sufficient for agents. The narrative system will point agents there. Adding a command adds complexity with no value -- agents can read markdown files directly.
5. Triage vs fix distinction:
Yes, the existing flow is correct. review --import creates findings in state AND creates issue docs. The agent then reads issue docs to do the work. When done, resolve fixed "<id>" cleans up both the state finding and the issue doc.
The "outliers" in the sibling behavior analysis (missing c import in _move_py.py and _move_ts.py) are not bugs but intentional design — these are pure computation modules with no user-facing output.
compute_tool_hash()
check_tool_staleness()
Generic area derivation, staleness detection
Issues Identified:
Mutable Global State Problem (Line 24-30)
_extra_exclusions is global mutable state
Current workaround: Other modules import the module itself and access _utils_mod._extra_exclusions (not from utils import), so they see runtime updates
Usage sites:
lang/python/detectors/unused.py (correct pattern)
detectors/graph.py (correct pattern)
commands/scan.py (direct import—should use module access)
Risk: If someone imports it the "wrong way" in the future, it won't pick up updates
Recommendation: Consider dependency injection (pass exclusions as a parameter) or clearly document the module-access-only pattern
Cross-cutting Concerns
Terminal output (colors, logging, tables) is mixed with file/path logic
Why normalized findings are needed: Each detector uses different data shapes; findings must be uniform (Finding TypedDict, tier/confidence, summary/detail)
Why in base.py: Shared by Python & TypeScript; single source for tier logic
Not premature generalization: Each function is detector-specific, not generic
Could be improved: Group in a separate module desloppify/findings.py (easier to locate normalization logic)
Current: Buried in 530-line lang/base.py
Proposed: Extract to dedicated module, lang/base.py imports from it
Deterministic classification, zone policies, helpers
No issues
Verdict: NO CHANGES NEEDED
This concludes the holistic review of abstractions and dependencies. The codebase demonstrates solid design with room for polishing in one or two areas, but no critical abstraction fitness issues.
narrative/core.py (line 5): Uses STRUCTURAL_MERGE in _count_open_by_detector()
narrative/dimensions.py (line 1): Uses STRUCTURAL_MERGE in _finding_in_dimension()
narrative/actions.py (line 1): Uses DETECTOR_TOOLS in _compute_tools()
Consistency checks:
✓ Mirrors PythonConfig structure
✓ Has language-specific security detector
✓ Provides all required callables
✓ Different threshold tuning (large_threshold=500 vs 300)
✓ Has fixers (7 TS fixers vs 0 Python fixers) — this is deliberate
✓ Has coupling boundaries (Python empty, TS has shared→tools)
Add docstring to _constants.py explaining test strategy
Benefit: Future maintainers understand why direct tests are missing
File: desloppify/narrative/_constants.py line 1-5
Low Priority
Harmonize zone rules counts
Currently 5 Python rules vs 3 TypeScript
Not a defect, but document the reason
File: desloppify/lang/{python,typescript}/init.py zone rules
CONCLUSION
API Surface Coherence: 9/10 — Excellent consistency in command interface and LangConfig design. Minor asymmetries (get_area, zone rules) are intentional.
Test Strategy: 7/10 — Comprehensive test coverage except for narrative constants initialization. Risk is medium but mitigated by indirect testing through all 6 importing modules.
Recommendation: Add targeted tests for _constants.py initialization + document the test strategy to prevent future refactoring mistakes.
Natural import target: 57 importers is high because utils touches every layer:
Commands (scan, detect, show) need c(), log(), rel()
Detectors need find_*_files(), grep_*(), PROJECT_ROOT
Language plugins need file discovery
Fixers need safe_write_text()
No initialization coupling: No circular dependencies; everything is deferred or pure.
Assessment: HEALTHY — This is a textbook utility module. High import count is a feature, not a bug.
2. desloppify/state.py — State Layer
Role: Persistent finding state management, TypedDict definitions, state I/O.
Size & Exports:
~400+ lines (partially read)
9 public functions + 1 TypedDict + 4 module constants
State constants are computed from PROJECT_ROOT (imported from utils) — only reads
STATE_DIR, STATE_FILE computed at import time (necessary for module to define its contract)
Importer Analysis:
cli.py (lines 268-271): Loads state once at startup, applies exclusions
review.py: Merges review findings into state
Assessment: HEALTHY — Lean, focused state layer with clear dependencies. Low importer count is appropriate (only entry points should load state). The import of TIER_WEIGHTS from scoring is correct (state recomputes stats using scoring weights).
Rationale: Reduces cli.py as a "focal point" (currently 13 importers, mostly for these helpers)
Impact: Would reduce visualize.py's dependency on cli.py
[NO ACTION] Keep utils.py as-is: The 57-importer count is correct for a utility module
Natural cohesion: all utilities are infrastructure-level
No artificial splitting recommended
[NO ACTION] State/Scoring layering is correct: state.py imports from scoring.py for TIER_WEIGHTS
This is correct: state is the data layer, scoring computes metrics
[DOCUMENTATION] Update memory note: The circular import fix via _constants.py could be documented as a pattern example
Conclusion
Overall Architecture Health: EXCELLENT
The desloppify codebase demonstrates mature, well-layered architecture. The high importer count on utils.py is not a smell—it's evidence of correct utility cohesion. All modules have minimal side effects, clean dependencies, and clear responsibilities.
No breaking changes recommended. The optional CLI helpers extraction is a style refinement, not a structural issue.
# For each holistic finding that's "open":
if f.get("file") == "." and f.get("detail", {}).get("holistic"):
weight = CONFIDENCE_WEIGHTS[confidence] # 1.0, 0.7, or 0.3
holistic_sum += weight * 10.0 # 10x multiplier!
# Final dimension score = (potential - weighted_failures) / potential * 100
A single high-confidence holistic finding counts as 10 failures in the "Design quality" dimension scoring.
3. WHAT THE USER SEES IMMEDIATELY AFTER IMPORT
Command: review --import findings.json --holistic
Output (review_cmd.py:131-135):
code
Holistic review imported:
+N new findings, M resolved, R reopened
Run: desloppify show review
Query file (.desloppify/query.json):
Lists imported findings with their dimensions
Includes computed narrative object
4. POST-IMPORT COMMANDS & HOW THEY SURFACE FINDINGS
All open "review" detector findings (both per-file AND holistic)
Holistic findings sort by file name (file=".") + confidence
Output for holistic:
code
review::cross_module_architecture::god_modules::a1b2c3d4
summary: God module identified
file: .
dimension: cross_module_architecture
confidence: high
related files: src/core.ts, src/utils.ts, src/state.ts, ...
suggestion: Split X into separate modules
reasoning: X is imported by 40% of codebase — fragile architecture
Final loop → Repeat next → resolve → status until all holistic findings addressed
Key insight: Holistic findings are first-class scoring citizens (10x weight) but require manual resolution. They're designed to bubble up architecture/design issues that detectors can't find, and their resolution has immediate score impact (no re-scan needed).
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 clarified the vision: They want a recursive loop:
Review → produces findings + remediation plan document
User acts on the plan
Re-scan/re-evaluate → new score
Loop back
Document should be stored in .desloppify/
Sub-agents should fix small issues directly, create document for larger ones
Implementation Phase 3 - Remediation Plan:
Added generate_remediation_plan() to review.py
Added _empty_plan() helper
Hooked into _do_import() in review_cmd.py
Updated _HOLISTIC_WORKFLOW with plan generation step
Updated HOLISTIC_REVIEW_SYSTEM_PROMPT with quick-fix vs plan guidance and scoring info
Added 12 tests for plan generation
Tests were NOT yet run (that's where we left off)
Let me now trace the pending tasks and current state:
Task #7 (tests) was marked in_progress
Task #8 (run tests) is pending
The tests were written but NOT executed yet
Phase 1 (completed): Implement the plan "Make Holistic Review Self-Evident for Agent Users" — enrich holistic context with file excerpts, sibling behavior analysis, investigation batches, workflow instructions, and narrative context. Add compute_narrative() to review_cmd.py.
Phase 2 (completed): Act as an agent and run through the entire holistic review process end-to-end on the desloppify codebase itself — read query.json, investigate batches in parallel, write findings, import them, resolve stale ones.
Phase 3 (in progress): Build a remediation plan document that bridges the gap between "here are findings" and "here's what to fix." The plan should be stored at .desloppify/holistic-plan.md, auto-generated on holistic import, include score impact estimation, prioritized findings with resolve commands, and re-evaluate instructions. Sub-agents should fix small issues directly and create documents for larger ones.
Added _state_with_holistic_findings() helper for plan tests
Added TestGenerateRemediationPlan class with 12 tests: basic content, priority ordering, score impact, resolve commands, related files, re-evaluate section, how-to-use section, empty findings, resolved exclusion, file writing, lang name in commands
holistic_findings.json — The actual findings produced during the end-to-end test
Sibling behavior test failure (TestSiblingBehavior.test_detects_outlier): Files with no imports weren't added to dir_imports, so they couldn't be flagged as outliers. The 4th file (review_cmd.py with no imports) was excluded from tracking, leaving only 3 files that ALL had the import, producing zero outliers. Fixed by removing the if names: guard on line that adds files to dir_imports.
Pre-existing test failures: 11 tests in test_scorecard.py (color values) and test_ts_patterns.py (fragmentation detection) were already failing before changes. These are unrelated to the holistic review work.
holistic_findings.json already existed: Had stale findings from a prior attempt. Had to read it first before overwriting (tool requirement).
resolve command arg order: desloppify resolve takes status before pattern (resolve wontfix "pattern" not resolve "pattern" wontfix).
Problem Solving:
Solved the "missing narrative" problem by adding compute_narrative() to both _do_prepare() and _do_import() in review_cmd.py
Solved the "not self-contained" problem by adding file excerpts, investigation batches, workflow instructions, and sibling behavior analysis
Solved the "behavioral outliers invisible" problem with the sibling behavior analysis that detects files missing imports shared by ≥60% of directory siblings
Solved the "no remediation document" gap by building generate_remediation_plan() that creates a prioritized markdown plan with score impact estimation
Identified that merge_scan() already supports the recursive re-evaluate loop (old findings auto-resolve when not re-reported)
All user messages:
"Implement the following plan: [detailed plan for Make Holistic Review Self-Evident for Agent Users]"
"can you actually run it for this repo, imagine you're an agent actually going through the process"
"And what's the path to actually fixing them? I would like the product of those agents to be to kind of like explore issues, evaluate the current score and to make a plan on how to improve it. And then for that to be, for example, like a document that the user can then act upon. And then once they actually act upon that Then they can update the score based on their new evaluation. Is that what currently happens? Or? Yeah, like what? Yeah, like what would they do next?"
"Yes please and think through where we should store this document you know maybe oh maybe it should just be in the you know the dot the slapify i think we already have we should store these documents yeah that's probably that actually makes more sense i guess and we should obviously yeah let's do that and let's make sure that when we deploy those sub-agents you know both for the pages and for the overall stuff that they they're 100 clear that they should create a document as their output or maybe if it's something small you know they should just fix it themselves you know and then just return the score with it being fixed if that makes sense but if it's bigger then you know something simple they should create a document"
Pending Tasks:
Task #7 (in_progress): Add tests for remediation plan — tests WRITTEN but NOT YET RUN
Task #8 (pending): Run tests and end-to-end verification — run full test suite, then do e2e: import findings, verify plan generated, check content
Current Work:
I had just finished writing 12 tests for generate_remediation_plan() in tests/test_holistic_review.py (Task #7) and was about to run them (Task #8). The tests were appended to the file but python -m pytest was never executed for this latest batch of changes. The remediation plan code in review.py and the hook in review_cmd.py have been written but not verified.
Optional Next Step:
Run the test suite to verify the remediation plan implementation works:
bash
python -m pytest tests/test_holistic_review.py -q
Then run the full suite, and do an end-to-end test by re-importing findings and checking the generated .desloppify/holistic-plan.md. This directly continues Task #8 which was the immediate next step after writing the tests. The user's last request was: "Yes please and think through where we should store this document... let's do that and let's make sure that when we deploy those sub-agents... they should create a document as their output or maybe if it's something small... they should just fix it themselves."
Command: "desloppify show --status wontfix"
To change an action's command or description:
Find the detector name in the appropriate section (auto_fix, reorganize, refactor, or debt_review)
Modify the description or command variables before appending to actions
For subjective_review, the special case is on lines 103–108
2. strategy.py — Execution Strategy & Hints
Key functions:
_compute_strategy() (lines 259–302): Main orchestrator
_compute_fixer_leverage() (lines 25–57): Estimates automation value
_compute_lanes() (lines 60–200): Partitions work into parallelizable lanes
_compute_strategy_hint() (lines 237–256): Generates one- or two-sentence guidance
What it does:
Organizes actions into lanes: "cleanup", "restructure", "refactor_X", "test_coverage", "debt_review"
Annotates each action with a "lane" field (line 276)
Determines if work can parallelize (2+ significant non-blocked lanes)
Generates hints like: "Run fixers first — they cover 65% of findings. Then 3 independent workstreams, safe to parallelize."
Strategy hints are context-aware (lines 237–256):
If strong fixer leverage + parallelizable: mention both
If stagnation: "Try a different dimension to break the plateau."
If maintenance: "Maintenance mode — address new findings as they appear."
Fallback: "Work through actions in priority order."
if det == "subjective_review":
command = "desloppify fix review" # ← Change this
description = f"{count} files need design review — run design review with dimension templates" # ← Or this
Scenario 2: Add a new narrative action like "N issues need attention — work through .desloppify/issues/"
You need to:
Register the detector in DETECTOR_TOOLS (in _constants.py):
python
"issues": {
"action_type": "manual_fix", # or "refactor"
"fixers": [],
"guidance": "work through priority list"
}
Add special-case handling in actions.py if needed:
python
if det == "issues":
command = "desloppify show issues --status open"
description = f"{count} issues need attention — work through .desloppify/issues/"
Refactor actions (lines 91–119) will pick it up automatically once it's in DETECTOR_TOOLS
9. Key Architectural Points for Document Generation
Where to intercept for per-issue docs:
At import time (review.py import_review_findings()):
Could write one file per finding before merge_scan()
File naming: .desloppify/issues/{finding_id}.md
Would need to track file paths in finding detail
In the Finding detail dict:
Currently stores: dimension, evidence, suggestion, reasoning, evidence_lines
Could add: doc_path field pointing to external markdown
In the state after import:
All findings already in state
Could iterate findings with detector="review" and generate docs
Use finding ID as stable filename
Score impact calculation:
Already computed in generate_remediation_plan()
Weight formula: CONFIDENCE_WEIGHTS × (HOLISTIC_MULTIPLIER if holistic else 1)
Could be extracted to helper function for reuse
Auto-resolution behavior to preserve:
Review findings from disappeared imports should NOT auto-resolve (protected by _IMPORT_ONLY_DETECTORS)
But findings that weren't re-reported in subsequent imports SHOULD auto-resolve (handled by finding ID matching)
This traces the complete data flow from agent JSON → Finding objects → state merge → dimension scoring. The key insight is that the Finding is the universal currency — everything goes through make_finding() and merge_scan(), making it a great point to extend with custom output paths.
auto_resolved — Auto-resolved when finding disappears during scan
Key Points:
resolve_findings() in state.py (line 456) is very simple: updates findings with status, note, resolved_at timestamp
Calls _recompute_stats() to recalculate dimensions and scores
Always writes to .desloppify/query.json (via _write_query()) for LLM awareness
Computes narrative (milestone context) before returning
# Atomic write helper (lines 59-73)
def safe_write_text(filepath: str | Path, content: str) -> None:
"""Atomically write text to a file using temp+rename."""
p = Path(filepath)
p.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=p.parent, suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
f.write(content)
os.replace(tmp, str(p)) # Atomic on all platforms
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise
# Path helpers
PROJECT_ROOT = Path(os.environ.get("DESLOPPIFY_ROOT", Path.cwd())).resolve()
QUERY_FILE = PROJECT_ROOT / ".desloppify" / "query.json"
Pattern: All desloppify file writes use safe_write_text() for atomicity + recovery. This is the standard in the codebase (used in 11 files including plan_cmd.py, next.py, show.py, etc.).
def get_next_items(state: dict, tier: int | None = None, count: int = 1) -> list[dict]:
"""Priority: tier (ascending) → confidence (high first) → detail count."""
open_findings = [f for f in state["findings"].values() if f["status"] == "open"]
# ... sort and slice
return open_findings[:count]
Current behavior: Shows next finding with file, lines, category, dimension context, and resolve command examples. Could easily add: "Issue doc: .desloppify/issues/{id}.md" hint.
5. MARKDOWN GENERATION PATTERNS
The codebase already has a mature markdown generation pattern for plans:
Key insight: Each command is a simple function cmd_* that takes args. To hook resolve, just add logic at the end of cmd_resolve() before the return statement (or after save_state()).
7. STATE STRUCTURE FOR FINDINGS
From state.py lines 20-31 (Finding TypedDict):
python
@TypedDict(total=False)
class Finding:
id: str # stable ID
file: str # relative path
tier: int # 1–4
detector: str # detector name
confidence: str # "high" | "medium" | "low"
summary: str
detail: dict
status: str # "open" | "resolved" | "wontfix" | "false_positive"
note: str | None # user explanation
first_seen: str # ISO timestamp
last_seen: str # ISO timestamp
Status counters: _EMPTY_COUNTERS = ("open", "fixed", "auto_resolved", "wontfix", "false_positive")
Architecture for .desloppify/issues/ Integration
Based on this exploration, here's the cleanest approach:
Phase 1: Resolve Hook
After save_state(state, sp) in cmd_resolve(), call a new helper:
python
from ..issues import maybe_cleanup_or_create_issue_doc(state, all_resolved, args.status)
The helper:
If status == "fixed" or status == "false_positive": delete .desloppify/issues/{id}.md
If status == "wontfix": ensure .desloppify/issues/{id}.md exists with decision record
Skip if no note provided (issue docs only for documented decisions)
The change: instead of one big plan, write individual files to .desloppify/issues/.
Both per-file AND holistic imports should create issue docs. Currently only holistic generates a plan.
Where Issue Docs Get Cleaned Up
cmd_resolve() in commands/resolve.py handles marking findings as fixed/wontfix/false_positive. After resolving, delete the corresponding issue doc.
Narrative Integration
The narrative system needs to guide agents to the right step:
After scan: The subjective_review action already says "86 files need design review — run desloppify fix review". This is good.
After triage/import: Need to surface "N issue docs in .desloppify/issues/ — work through them" as the top action
After fixing + re-scan: Score updates, loop continues
The narrative actions.py has a special case for subjective_review (line 103-105) that sets the command to desloppify fix review. We could add a similar special case for review detector findings that checks if issue docs exist.
Agent Guidance
Key places where agents learn what to do next:
_print_llm_summary() in scan.py — markdown table for LLM after scan
compute_narrative() → headline + actions + strategy in every query.json
Terminal output from each command
The headline should mention issue docs when they exist. The actions should point to .desloppify/issues/.
next command
cmd_next() in commands/next.py shows the next priority item. Should show the issue doc path if one exists.
Existing Utilities to Reuse
safe_write_text(filepath, content) in utils.py — atomic file writes
generate_remediation_plan() in review.py — already computes per-finding impact data (reuse logic, change output)
PROJECT_ROOT in utils.py
Finding structure: Finding TypedDict in state.py
make_finding() in state.py
CONFIDENCE_WEIGHTS, HOLISTIC_MULTIPLIER in scoring.py
Constraints
Keep it simple — minimal new modules
Issue docs are disk artifacts, NOT stored in state JSON
Both per-file and holistic review findings should create issue docs
Resolve should clean up docs
The narrative/headline/actions should guide agents step by step
Must be obvious from output what to do next at every stage
Questions to Address
Should we create a new desloppify/issues.py module or add functions to review.py?
Short ID format: hash of finding ID? First 8 chars? Human-readable slug?
Should desloppify show review also list issue docs?
Should there be a desloppify issues command? Or is ls .desloppify/issues/ sufficient?
How does the triage-vs-fix distinction work in practice? Is it just "review --import creates docs, then agent reads them"?
Please design the simplest implementation that achieves this. Prioritize minimal changes and maximum clarity for agent users.
ISSUES_DIR = PROJECT_ROOT / ".desloppify" / "issues"
def _issue_slug(finding: dict) -> str:
"""Generate a short human-readable filename slug from a finding."""
# Extract dimension or detector
detail = finding.get("detail", {})
dimension = detail.get("dimension", finding.get("detector", "issue"))
# Shorten dimension: "naming_quality" -> "naming", "cross_module_architecture" -> "arch"
short_dim = dimension.split("_")[0]
# Extract identifier
identifier = detail.get("identifier") or finding.get("file", "unknown").split("/")[-1].split(".")[0]
# Clean for filesystem
slug = re.sub(r'[^a-z0-9_-]', '', f"{short_dim}-{identifier}".lower().replace(" ", "-"))
# Add hash suffix for uniqueness
hash8 = hashlib.sha256(finding["id"].encode()).hexdigest()[:8]
return f"{slug}-{hash8}"
def write_issue_doc(finding: dict, lang_name: str) -> Path:
"""Write a single issue doc for a finding. Returns the path."""
# Reuse impact computation from generate_remediation_plan logic
slug = _issue_slug(finding)
path = ISSUES_DIR / f"{slug}.md"
content = _render_issue_doc(finding, lang_name)
safe_write_text(path, content)
return path
def _render_issue_doc(finding: dict, lang_name: str) -> str:
"""Render a self-contained markdown work order for one finding."""
# Content:
# - Finding ID (for resolve command)
# - Problem summary
# - Evidence (evidence lines, evidence list)
# - Suggested fix
# - Files to modify (related_files for holistic, or finding.file for per-file)
# - Resolve command
# Template below
def write_issue_docs(findings: list[dict], state: dict, lang_name: str) -> list[Path]:
"""Write issue docs for multiple findings. Returns paths created."""
# Creates ISSUES_DIR if needed
# Calls write_issue_doc for each finding
# Returns list of created paths
def remove_issue_doc(finding_id: str) -> bool:
"""Remove the issue doc for a finding ID, if it exists. Returns True if removed."""
# Hash the finding ID, scan ISSUES_DIR for matching file
# Since we embed the finding ID in the doc, we can also
# just scan all .md files for the ID string as fallback
def list_issue_docs() -> list[Path]:
"""List all issue doc paths, sorted by name."""
if not ISSUES_DIR.exists():
return []
return sorted(ISSUES_DIR.glob("*.md"))
def count_issue_docs() -> int:
"""Count issue docs without reading them."""
if not ISSUES_DIR.exists():
return 0
return len(list(ISSUES_DIR.glob("*.md")))
The _render_issue_doc function produces markdown like:
markdown
# naming: recompute_stats
**Finding ID**: `review::desloppify/state.py::naming_quality::_recompute_stats::a1b2c3d4`
**Dimension**: Naming quality | **Confidence**: high
## Problem
_recompute_stats is a vague name — callers use it for score recalculation after resolve/merge
## Evidence
- Lines 464-465: function name doesn't convey what's being recomputed
- Called from resolve_findings and merge_scan — always about score updates
## Suggested Fix
Rename to `recalculate_scores_and_stats` or `update_score_after_change`
## Files to Modify
- `desloppify/state.py`
## When Done
```bash
desloppify --lang python resolve fixed "review::desloppify/state.py::naming_quality::_recompute_stats::a1b2c3d4"
code
For holistic findings, the template adapts:
- "Files to Modify" uses `detail.related_files`
- "Evidence" uses `detail.evidence` array
- "Why This Matters" section uses `detail.reasoning`
The key design point: `_render_issue_doc` handles both per-file review findings and holistic findings by checking `detail.get("holistic")`.
#### 2. Modify: `desloppify/commands/review_cmd.py` -- `_do_import()`
Currently at line 94, `_do_import` does:
1. Reads JSON
2. Calls `import_review_findings()` or `import_holistic_findings()`
3. Saves state
4. For holistic: calls `generate_remediation_plan()` and writes one big plan
Change: After the import and save, call `write_issue_docs()` for all newly created open findings (both per-file and holistic). Remove the `generate_remediation_plan()` call for holistic imports.
Specifically, in the holistic branch (line 137-149), replace:
```python
# OLD: generate single plan
generate_remediation_plan(state, lang_name, output_path=plan_path)
print("Remediation plan: .desloppify/holistic-plan.md")
With:
python
# NEW: generate per-issue docs
from ..issues import write_issue_docs
# Get the newly created open review findings
new_findings = [f for f in state["findings"].values()
if f["status"] == "open" and f.get("detector") == "review"
and f.get("detail", {}).get("holistic")]
paths = write_issue_docs(new_findings, state, lang_name)
print(f" Created {len(paths)} issue docs in .desloppify/issues/")
print(f" Next: work through each doc, then resolve")
For the per-file branch (line 150-151), add similar logic:
python
from ..issues import write_issue_docs
new_findings = [f for f in state["findings"].values()
if f["status"] == "open" and f.get("detector") == "review"
and not f.get("detail", {}).get("holistic")]
paths = write_issue_docs(new_findings, state, lang_name)
if paths:
print(f" Created {len(paths)} issue docs in .desloppify/issues/")
The terminal output should then say:
code
Review imported:
+5 new findings, 2 resolved, 0 reopened
Created 5 issue docs in .desloppify/issues/
Next: work through each doc in .desloppify/issues/, then resolve
Add an issue doc count check. Currently at line 19-28, there's a review_suffix for review findings. Extend this to mention issue docs when they exist.
In _compute_headline, after the existing review_suffix logic (line 19-28), add:
python
from ..issues import count_issue_docs
issue_count = count_issue_docs()
if issue_count > 0:
s = "s" if issue_count != 1 else ""
review_suffix = f" ({issue_count} issue doc{s} in .desloppify/issues/ -- work through them)"
This overrides the existing review_suffix with one that points to the issue docs. The logic: if issue docs exist, they ARE the review findings -- so pointing to the docs is better than just saying "N review findings pending".
At line 102-105, there's already a special case for subjective_review that redirects to desloppify fix review. Add a similar case for the review detector when issue docs exist:
python
# After the subjective_review special case (line 105):
elif det == "review":
from ..issues import count_issue_docs
n_docs = count_issue_docs()
if n_docs > 0:
command = "ls .desloppify/issues/"
description = f"{n_docs} issue docs to work through in .desloppify/issues/"
else:
command = f"desloppify show {det} --status open"
description = f"{count} {det} findings -- run review cycle to create issue docs"
This means after import, the top action will point agents to the issue docs directory.
When the next item is a review finding, check if there's a corresponding issue doc and display its path. After line 70 (print(f" ID: {item['id']}", "dim")), add:
python
if item.get("detector") == "review":
from ..issues import find_issue_doc_for_finding
doc_path = find_issue_doc_for_finding(item["id"])
if doc_path:
print(f" Issue doc: {doc_path.relative_to(PROJECT_ROOT)}")
This requires adding a small helper find_issue_doc_for_finding(finding_id) to issues.py that hashes the ID and checks if the file exists.
Implementation Sequence
Create desloppify/issues.py -- the core module. No dependencies on other changes.
Modify review_cmd.py -- hook issue doc creation into import flow.
Modify resolve.py -- hook issue doc cleanup into resolve flow.
Modify headline.py -- surface issue doc count in narrative.
Modify actions.py -- point actions to issue docs when they exist.
Modify next.py -- show issue doc path for review findings.
Update _HOLISTIC_WORKFLOW in review.py line 1310-1318 -- change step 7 from "A remediation plan will be generated at .desloppify/holistic-plan.md" to "Issue docs will be created in .desloppify/issues/ -- work through each one".
Steps 4-6 are independent of each other but depend on step 1.
Things NOT Changed
generate_remediation_plan() -- kept in review.py but no longer called from the import flow. It can remain for backward compatibility or be removed later. The plan command still works independently.
State JSON -- no schema changes. Issue docs are disk artifacts only.
scan command -- no changes. The subjective_review flow stays the same.
Scoring -- no changes.
fix review -- no changes. It still prepares context for the agent.
Edge Cases
Re-import: If the agent re-imports after fixing some issues, merge_scan auto-resolves findings that aren't re-reported. The corresponding issue docs for those auto-resolved findings should also be cleaned up. Add a hook in import_review_findings() and import_holistic_findings() in review.py to clean up docs for auto-resolved findings (using the diff["auto_resolved_ids"] -- need to check if merge_scan returns IDs). Actually, looking at merge_scan in state.py, diff contains counts but not IDs. The simplest approach: after import, scan .desloppify/issues/ and remove any doc whose finding ID is no longer open in state. Add a cleanup_stale_docs(state) function to issues.py.
Multiple languages: Issue docs are shared across languages (they're in .desloppify/issues/). This is fine -- the finding IDs include file paths which are language-specific.
No findings: If import produces 0 new findings, write_issue_docs() returns an empty list. The output says "Created 0 issue docs" -- could be suppressed with an if paths: guard.
Testing Plan
Add tests/test_issues.py with:
test_issue_slug_format -- verify slug generation
test_write_and_read_issue_doc -- create a finding, write doc, verify content
test_remove_issue_doc -- write then remove, verify gone
test_find_issue_doc_for_finding -- verify lookup by finding ID
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/issues.py - New module: all issue doc lifecycle logic (create, render, remove, list, cleanup)
/Users/user_c042661f/Documents/desloppify/desloppify/commands/review_cmd.py - Hook issue doc creation into _do_import() for both per-file and holistic flows
/Users/user_c042661f/Documents/desloppify/desloppify/commands/resolve.py - Hook issue doc cleanup into cmd_resolve() after findings are resolved
/Users/user_c042661f/Documents/desloppify/desloppify/narrative/headline.py - Surface issue doc count in the headline so agents know what to do next
/Users/user_c042661f/Documents/desloppify/desloppify/narrative/actions.py - Point the review action to .desloppify/issues/ when docs exist