I need to understand the full desloppify pipeline end-to-end. Research these specific areas and give me a detailed summary:
Scan pipeline: How does cmd_scan work? What does it detect? How does it call detectors? How does merge_scan work? What does the scan output tell the agent to do next?
The fixer system: How do programmatic fixers work? Look at commands/fix_cmd.py, the fixer registry in the TS plugin, FixerConfig, apply_fixer. What's the flow from "agent sees a finding" to "agent runs a fixer" to "finding resolved"?
The actions/narrative system: How does narrative/actions.py (_compute_actions) decide what to recommend? How does it differentiate between auto_fix, manual_fix, reorganize, refactor action types? How does it currently handle the "review" detector?
The resolve flow: How does cmd_resolve work? What happens to findings in state? How is score recalculated?
The review system: How does review --prepare → agent evaluates → review --import work? What data does a review finding contain? How does it differ from objective findings?
The current issues system: What does issues.py do today? How is it called from review_cmd.py and resolve.py?
The next command: How does get_next_items prioritize findings? How does it handle review findings specifically?
Read the actual source files. Focus on the data flow and the interfaces between components. I want to understand the exact shape of data at each step.
I'll research the full desloppify pipeline by reading all the key source files in parallel.
Assistant
Now let me read the remaining files I need -- the _constants.py for DETECTOR_TOOLS, and the review_cmd.py for the review flow.
Assistant
User
I need to understand the holistic (non-file-based) review findings in desloppify. Research:
What are the holistic review dimensions? Look at HOLISTIC_DIMENSIONS in review.py and HOLISTIC_REVIEW_SYSTEM_PROMPT — what does it ask the agent to evaluate?
How do holistic findings differ from per-file findings in state? Look at how import_holistic_findings creates them vs import_review_findings. What's the file field set to? What's different in the detail dict?
How do holistic findings interact with scanning? Are they protected from auto-resolve? Look at _IMPORT_ONLY_DETECTORS in state.py and how _find_suspect_detectors works.
How does the scoring system handle holistic vs per-file review findings? Look at HOLISTIC_MULTIPLIER and _FILE_BASED_DETECTORS in scoring.py.
Look at the narrative reminder system — is there already a review staleness mechanism? Check narrative/reminders.py for review_stale.
How does review --prepare --holistic know if it needs to be re-run? Is there a timestamp/cache mechanism like per-file review?
Read the actual source files. Return specific code references.
Assistant
I'll research all six questions in parallel by reading the relevant source files.
User
I need to understand how desloppify currently communicates next steps to agents. Research:
Scan output: In commands/scan.py, look at _show_post_scan_analysis() and _print_llm_summary(). How does the scan output tell agents what to do next? What goes into query.json?
Narrative actions: In narrative/actions.py, how does _compute_actions order recommendations? What's the type_order sorting? When review findings exist, what does the top action say?
Strategy hints: In narrative/strategy.py, what are strategy hints? How do they guide the agent?
The reminder system: In narrative/reminders.py, how do reminders work? How does decay work (reminder_history)? Is there already a reminder for review findings?
query.json structure: What does the full query.json output look like after a scan? What fields does the narrative dict contain?
I want to understand all the mechanisms by which desloppify nudges agents toward specific actions.
This is research only.
Assistant
Now let me also check the review command to see how --prepare --holistic handles staleness/caching.
Assistant
I'll research all the mechanisms by which desloppify communicates next steps to agents. Let me read all the relevant files in parallel.
Assistant
Now let me read the remaining files I need: the constants file, the headline module, and the _write_query function in cli.py.
Assistant
Now let me also look at the next and review_cmd commands to understand how those communicate actions, plus the commands/show.py for completeness.
Assistant
Assistant
I now have a comprehensive picture of the entire pipeline. Here is the detailed summary.
1. Scan Pipeline (cmd_scan)
Entry point: commands/scan.py::cmd_scan(args)
Flow:
Loads persistent state from .desloppify/state-{lang}.json via load_state(sp)
Resolves the language config (_resolve_lang(args)) which returns a LangConfig dataclass
Populates the review_cache on the lang config so the review_coverage detector can use it
Calls generate_findings(path, include_slow, lang, zone_overrides) from plan.py
generate_findings in /Users/user_c042661f/Documents/desloppify/desloppify/plan.py (line 26):
Delegates to _generate_findings_from_lang()
First builds a FileZoneMap from lang.zone_rules + lang.file_finder(path). This stamps every file with a zone (production/test/config/generated/script/vendor).
Then iterates through lang.phases -- a list of DetectorPhase objects. Each phase has a .label, .run(path, lang) callable, and .slow flag.
Each phase.run(path, lang) returns (findings: list[dict], potentials: dict[str, int]). Potentials map detector names to "checked counts" (denominators for scoring).
After all phases run, stamps lang and zone on each finding. Applies zone-policy confidence downgrades.
Returns (findings, all_potentials).
Back in cmd_scan:
5. Collects codebase metrics (file count, LOC, directories)
6. Audits excluded directories for staleness
7. Calls merge_scan(state, findings, ...) -- this is the critical merge step
merge_scan in /Users/user_c042661f/Documents/desloppify/desloppify/state.py (line 372)
For each new finding, checks against ignore patterns
If finding ID already exists in state: updates last_seen, tier, confidence, summary, detail, zone. If previously fixed/auto_resolved, reopens it (increments reopen_count, sets status back to "open")
If finding ID is new: inserts it into existing
Returns (current_ids, new_count, reopened_count, by_detector) where by_detector counts findings per detector in this scan
Calls _find_suspect_detectors(): identifies detectors that previously had open findings but returned 0 this scan. The review detector is always marked suspect (it's import-only, never runs during scan). If ran_detectors (from potentials) includes the detector, it's trusted.
Calls _auto_resolve_disappeared(): for open/wontfix findings not in current_ids, sets status to "auto_resolved" -- but skips findings from suspect detectors, wrong language, wrong scan_path, or excluded directories.
Calls _recompute_stats() which recalculates stats, score (weighted progress), strict_score, and _update_objective_health() (dimension-based scores from potentials).
Appends a scan_history entry (timestamp, lang, scores, open count, diff counts, dimension snapshots). Keeps last 20.
Detects chronic reopeners (reopen_count >= 2 and still open).
Python has no auto-fixers (lang == "python" causes actions to suggest manual_fix instead).
Flow from finding to fix to resolution
cmd_fix in /Users/user_c042661f/Documents/desloppify/desloppify/commands/fix_cmd.py (line 11):
Loads the fixer from lang.fixers[fixer_name] via _load_fixer()
Warns about uncommitted changes
Runs fixer["detect"](path) -- returns list[dict] of fixable entries (each has file, name, line, etc.)
Runs fixer["fix"](entries, dry_run=dry_run) -- returns either a FixResult or raw results list. Each result is {file, removed: [symbol_names], lines_removed}
For each result, constructs the finding ID as {detector}::{rel(file)}::{symbol}
If that ID exists in state and is "open", marks it "fixed" with note "auto-fixed by desloppify fix {fixer_name}"
Saves state
Runs post_fix hook if present (e.g., _cascade_import_cleanup for debug-logs and dead-useeffect -- after removing debug logs, checks for newly-orphaned imports)
Computes narrative and writes query.json
Prints post-fix retro checklist
The key linkage is the finding ID format: {detector}::{relative_file}::{symbol_name}. Both the scan pipeline and the fixer use the same convention, so _resolve_fixer_results can match fix results to finding IDs in state.
Command-level post-fix hooks
_COMMAND_POST_FIX dict at module level (line 297-298) attaches cascade import cleanup after debug-logs and dead-useeffect fixers.
3. The Actions/Narrative System
Entry: compute_narrative() in /Users/user_c042661f/Documents/desloppify/desloppify/narrative/core.py (line 65)
Orchestrator that calls:
_count_open_by_detector(findings) -- counts open findings per detector, merging structural sub-detectors. Separately tracks review_holistic count.
_detect_phase() -- trajectory analysis from scan history
_analyze_dimensions() -- dimension health analysis
_analyze_debt() -- wontfix debt analysis
_detect_milestone() -- milestone detection
_compute_actions(by_det, dim_scores, state, debt, lang) -- the action engine
_compute_strategy() -- parallelization hints
_compute_tools() -- available tools inventory
_compute_headline() -- coaching headline
_compute_reminders() -- contextual reminders with decay
_compute_actions in /Users/user_c042661f/Documents/desloppify/desloppify/narrative/actions.py (line 8)
Input:by_det (open counts per detector), dim_scores, state, debt, lang
Logic by action_type (from DETECTOR_TOOLS):
auto_fix (line 31-67): Iterates DETECTOR_TOOLS where action_type == "auto_fix". For Python, downgrades to manual_fix (no fixers). For TypeScript, emits desloppify fix {fixer} --dry-run command. Computes impact via compute_score_impact().
reorganize (line 69-89): Iterates detectors with action_type == "reorganize". Emits desloppify show {det} --status open command with guidance text.
refactor and manual_fix (line 91-131): Iterates detectors with action_type in ("refactor", "manual_fix"). Has special handling for two detectors:
subjective_review: Commands desloppify fix review (runs the review prepare workflow)
review: Checks count_issue_docs(). If issue docs exist (>0), the command becomes cat .desloppify/issues/*.md with action_type overridden to "issue_docs". If no docs, commands desloppify show review --status open and suggests running a review cycle.
debt_review (line 133-143): If wontfix debt gap > 2.0 points, suggests reviewing wontfix items.
Sorting (line 146-149): Actions are sorted by (type_order, -impact) where type_order is:
So issue_docs always come first, then auto_fix, then reorganize, etc. Within each type, highest impact first.
_compute_tools (line 154)
Returns inventory of available fixers, move tool relevance, plan command, and badge status.
4. The Resolve Flow
cmd_resolve in /Users/user_c042661f/Documents/desloppify/desloppify/commands/resolve.py (line 9)
If status == "wontfix" and no --note, exits (enforces reasoning for technical debt)
Loads state, records prev_score
For each pattern in args.patterns, calls resolve_findings(state, pattern, args.status, args.note)
resolve_findings in state.py (line 456):
python
def resolve_findings(state, pattern, status, note=None):
now = _now()
resolved = []
for f in match_findings(state, pattern, status_filter="open"):
f.update(status=status, note=note, resolved_at=now)
resolved.append(f["id"])
_recompute_stats(state, scan_path=state.get("scan_path"))
return resolved
match_findings (line 449) matches by: exact ID, glob pattern, ID prefix, detector name, or file path.
After resolving:
4. Saves state
5. Removes issue docs for each resolved finding via remove_issue_doc(fid) from issues.py
6. Computes narrative (checks for milestones)
7. Writes query.json
Score recalculation
_recompute_stats is called inside resolve_findings itself (line 464). This recalculates:
Per-status counters (open, fixed, wontfix, etc.)
_weighted_progress() -- legacy progress score
_update_objective_health() -- dimension-based objective scores using potentials
The finding's status change from "open" to "fixed"/"wontfix" reduces open counts in the relevant dimension, improving dimension pass rates and overall health.
5. The Review System
Two modes: per-file review and holistic (codebase-wide) review
Per-file: review --prepare
_do_prepare in /Users/user_c042661f/Documents/desloppify/desloppify/commands/review_cmd.py (line 32):
_setup_lang() builds zone map and dep graph
Calls prepare_review(path, lang, state, ...) from review.py
prepare_review in /Users/user_c042661f/Documents/desloppify/desloppify/review.py (line 845):
build_review_context() -- gathers codebase conventions: naming vocabulary (prefix frequency), error handling patterns, module patterns per directory, import graph summary (top-imported files), zone distribution, existing findings per file, codebase stats, sibling function conventions
select_files_for_review() -- picks production files not yet reviewed (or stale): skips test/generated/vendor zones, checks review_cache for content hash + reviewed_at date, sorts by _compute_review_priority() which scores based on importer count, existing findings, LOC, and deprioritizes types/constants files
_build_file_requests() -- for each selected file: reads content, gets zone, gets import neighbors from dep graph, gets existing findings
Updates potentials[lang]["review"] = number of unique files reviewed
Calls merge_scan(state, review_findings, lang=lang_name) -- this is the same merge used by scan, so findings are upserted, existing findings from previous reviews that disappeared are auto-resolved, etc.
Updates review cache with timestamps and content hashes
import_holistic_findings (line 1361):
Similar but file="." (dot), name includes "holistic::" prefix
detail includes holistic: True, related_files: [...]
Uses HOLISTIC_POTENTIAL = 10 for potentials
Holistic findings bypass per-file scoring caps and get HOLISTIC_MULTIPLIER = 10.0 weight
How review findings differ from objective findings:
detector = "review" (not a scan-time detector)
tier = always 3
Protected from auto-resolve: _find_suspect_detectors always marks "review" as suspect (line 290: _IMPORT_ONLY_DETECTORS = {"review"}), so scan won't auto-resolve review findings
Evidence (from detail.evidence and detail.evidence_lines)
Suggested Fix (from detail.suggestion)
Files (related_files for holistic, file path for per-file)
Why This Matters (reasoning, holistic only)
When Done: the exact desloppify resolve fixed "{fid}" command
write_issue_docs(findings, state, lang_name): Writes docs for all findings. Called from review_cmd.py::_do_import() (line 142) after importing review findings.
remove_issue_doc(finding_id): Deletes the doc for a resolved finding. Called from resolve.py::cmd_resolve() (line 33-34) when findings are resolved.
cleanup_stale_docs(state): Removes docs whose finding is no longer open. Called from review_cmd.py::_do_import() (line 143).
count_issue_docs(): Counts .md files in issues dir. Called from narrative/actions.py (line 107) to decide whether to recommend reading issue docs vs running a review cycle.
find_doc_for_finding(finding_id): Looks up a doc by finding ID (reads first few lines to match). Called from commands/next.py (line 73) to show doc path when next item is a review finding.
How it's called:
Creation: review_cmd.py::_do_import() creates issue docs for all open review findings after import
Consumption: actions.py::_compute_actions() checks count_issue_docs() -- if >0, top action is cat .desloppify/issues/*.md with priority issue_docs (rank 0, above auto_fix)
Presentation: next.py::cmd_next() shows the doc path when displaying a review finding
Deletion: resolve.py::cmd_resolve() removes the doc when a finding is resolved
Cleanup: review_cmd.py::_do_import() cleans up stale docs after each import
7. The next Command
cmd_next in /Users/user_c042661f/Documents/desloppify/desloppify/commands/next.py (line 9)
Loads state
Checks tool staleness (warns if detectors have changed since last scan)
Calls get_next_items(state, tier, count) from plan.py
get_next_items in /Users/user_c042661f/Documents/desloppify/desloppify/plan.py (line 247)
python
def get_next_items(state, tier=None, count=1):
open_findings = [f for f in state["findings"].values() if f["status"] == "open"]
if tier is not None:
open_findings = [f for f in open_findings if f["tier"] == tier]
open_findings.sort(key=lambda f: (
f["tier"], # tier ascending (1 first)
CONFIDENCE_ORDER.get(f["confidence"], 9), # high > medium > low
-f.get("detail", {}).get("count", 0), # more instances first
f["id"], # stable tiebreaker
))
return open_findings[:count]
Priority order:
Tier (ascending): Tier 1 auto-fixable first, Tier 4 major refactors last
Confidence (descending): high > medium > low
Detail count (descending): findings with more instances first
Finding ID (alphabetical): stable tiebreaker
Review finding handling in next:
Review findings (detector="review") are always tier 3 (judgment-required), so they appear after tier 1 and tier 2 findings but alongside other tier 3 findings. They compete with structural, smells, dupes, etc. on confidence and count.
Special display for review findings (line 72-76):
python
if item.get("detector") == "review":
from ..issues import find_doc_for_finding
doc = find_doc_for_finding(item["id"])
if doc:
print(f" Doc: {doc.relative_to(PROJECT_ROOT)}")
When showing a review finding, it looks up and displays the issue doc path so the agent knows where to find the detailed work order.
Dimension context display (line 87-96):
For any finding, looks up its dimension via get_dimension_for_detector(det) and shows the dimension's current health score and issue count.
Summary of Data Flow
code
scan --path src/
-> generate_findings() runs all DetectorPhase.run() functions
-> returns (findings: list[Finding], potentials: dict[str, int])
-> merge_scan() upserts/resolves/reopens in state["findings"]
-> _recompute_stats() recalculates scores from potentials + findings
-> compute_narrative() generates actions, headline, strategy
-> query.json written for agent consumption
fix {fixer}
-> fixer.detect(path) finds fixable entries
-> fixer.fix(entries) modifies files, returns results
-> _resolve_fixer_results() matches results to findings by ID format
-> post_fix hooks (cascade cleanup)
review --prepare
-> build_review_context() + select_files_for_review()
-> query.json with file contents, prompts, context
review --import findings.json
-> import_review_findings() validates, creates Finding objects (detector="review", tier=3)
-> merge_scan() integrates them (review is protected from auto-resolve)
-> write_issue_docs() creates .desloppify/issues/*.md work orders
resolve fixed "finding_id"
-> resolve_findings() sets status, recalculates scores
-> remove_issue_doc() deletes the work order
next
-> get_next_items() sorts open findings by (tier, confidence, count)
-> shows issue doc path for review findings
This is research only.
I now have all the information needed. Let me also quickly check the path_scoped_findings holistic handling and the _update_holistic_review_cache logic more closely.
There are 8 holistic dimensions. Each has a structured prompt in HOLISTIC_DIMENSION_PROMPTS (lines 33-148) with description, look_for, and skip fields. For example, cross_module_architecture looks for god modules, circular deps, layer violations, hidden coupling, and sys.path manipulation.
The system prompt (HOLISTIC_REVIEW_SYSTEM_PROMPT, lines 150-189) instructs the agent to:
Only emit findings for codebase-wide patterns (not single-file issues)
Every finding MUST include a related_files array with 2+ files as evidence
Every finding MUST include a concrete, actionable suggestion
Be specific (e.g., "3 different error handling strategies across 4 modules")
Calibrate confidence: high/medium/low
Return fewer high-quality findings (most codebases should have 2-5)
Each finding impacts the Design quality dimension
Each finding becomes an individual issue doc in .desloppify/issues/
The output format asks for: dimension, identifier, summary, related_files, evidence, suggestion, reasoning, confidence -- notably no file or evidence_lines fields (contrast with per-file review format).
Requires only dimension, identifier, summary, confidence -- no file required
file field set to "" which make_finding converts via rel("") to "." (line 1388-1389, comment: "Use empty string for file -- make_finding calls rel('') which returns '.'")
Finding name: f"holistic::{dimension}::{f['identifier']}::{content_hash}" (prefixed with holistic::)
detail dict contains: holistic: True, dimension, related_files, evidence, suggestion, reasoning -- notably no evidence_lines, and adds holistic flag and related_files
Tier is always 3
Updates potentials[lang]["review"] differently: uses HOLISTIC_POTENTIAL constant (value 10) rather than file count
Updates review_cache["holistic"] (not per-file cache) with reviewed_at, file_count_at_review, finding_count
Key structural differences:
file="." for holistic (vs actual path for per-file)
detail.holistic = True flag
detail.related_files list instead of detail.evidence_lines
Finding ID prefix holistic:: vs bare dimension::
Separate cache key (review_cache.holistic vs review_cache.files)
# review is import-only (not a scan detector) -- always protect from auto-resolve
_IMPORT_ONLY_DETECTORS = {"review"}
suspect = set()
for det, n in prev.items():
if det in _IMPORT_ONLY_DETECTORS:
suspect.add(det)
continue
...
The _find_suspect_detectors function (lines 267-305) always adds "review" to the suspect set because it is in _IMPORT_ONLY_DETECTORS. This means:
When _auto_resolve_disappeared runs during a scan (lines 308-332), any open finding whose detector is in suspect_detectors is skipped (line 323-324):
python
if old.get("detector", "unknown") in suspect_detectors:
continue
This protects both per-file and holistic review findings from being auto-resolved by scans. Since both types have detector="review", they are both protected.
Additionally, path_scoped_findings (lines 197-207) explicitly includes holistic findings regardless of scan path:
python
def path_scoped_findings(findings: dict, scan_path: str | None) -> dict:
...
return {k: v for k, v in findings.items()
if v.get("file", "").startswith(prefix) or v.get("file") == scan_path
or v.get("file") == "."}
The or v.get("file") == "." clause ensures holistic findings (with file=".") are always included in stats/scoring regardless of which scan path is active.
Both holistic and per-file review findings feed into the same dimension:
python
Dimension("Design quality", 4, ["review", "subjective_review"]), # line 37
Tier 4 is the highest weight (TIER_WEIGHTS = {... Tier.MAJOR_REFACTOR: 4}).
The "review" detector is in _FILE_BASED_DETECTORS (line 49), which means per-file findings are subject to a per-file cap of 1.0 on weighted failures.
However, holistic findings get special treatment in _detector_pass_rate (lines 114-118):
python
# Holistic findings: no per-file cap, 10x multiplier
if f.get("file") == "." and f.get("detail", {}).get("holistic"):
weight = CONFIDENCE_WEIGHTS.get(f.get("confidence", "medium"), 0.7)
holistic_sum += weight * HOLISTIC_MULTIPLIER
issue_count += 1
continue
Key scoring constants:
HOLISTIC_MULTIPLIER = 10.0 (line 59) -- each holistic finding has 10x the weight of a single per-file finding
HOLISTIC_POTENTIAL = 10 (line 60) -- the denominator for holistic review; used as potentials["review"] when holistic findings are imported
So a single high-confidence holistic finding contributes 1.0 * 10.0 = 10.0 weighted failures against a potential of 10, which is a 100% failure on that slice. A medium-confidence one contributes 0.7 * 10.0 = 7.0. The holistic_sum is added to the regular per-file weighted failures (line 139: weighted_failures += holistic_sum) to produce the combined pass rate.
The potential stacking logic in import_holistic_findings (lines 1411-1416):
python
if not rc.get("holistic"):
pots["review"] = HOLISTIC_POTENTIAL # First holistic review: set to 10
elif review_findings:
pots["review"] = pots.get("review", 0) + HOLISTIC_POTENTIAL # Subsequent: add 10
Yes, there are two review-related reminder mechanisms:
Reminder #9 -- review_not_run (lines 135-144): Triggers when review_cache["files"] is empty AND objective_strict >= 80. Nudges the user to run their first review.
python
if not review_cache.get("files"):
obj_strict = state.get("objective_strict", 0)
if obj_strict >= 80:
reminders.append({
"type": "review_not_run",
"message": ("Mechanical checks look good! Run a subjective design review ..."),
})
Reminder #10 -- review_stale (lines 147-164): Triggers when review_cache["files"] exists and the oldest reviewed file is over 30 days old.
python
if review_cache.get("files"):
oldest_str = min(f["reviewed_at"] for f in review_cache["files"].values() ...)
oldest = _dt.fromisoformat(oldest_str)
age_days = (_dt.now(_tz.utc) - oldest).days
if age_days > 30:
reminders.append({
"type": "review_stale",
"message": (f"Design review is {age_days} days old -- run: desloppify review --prepare"),
})
Notable: The review_stale reminder only checks review_cache["files"] (per-file review). It does not check review_cache["holistic"]. There is no "holistic review stale" reminder. Both reminders are subject to the standard decay mechanism (_REMINDER_DECAY_THRESHOLD = 3 -- suppressed after 3 showings).
The _do_prepare function for holistic mode (holistic=True) calls prepare_holistic_review directly with no staleness check. Unlike per-file review which has:
select_files_for_review with content-hash-based cache checking (lines 673-719 of review.py)
max_age_days parameter (default 30)
Per-file review_cache["files"] with content_hash and reviewed_at
The holistic prepare path does none of this. It always rebuilds the full holistic context from scratch. There is no "skip because already reviewed" logic for holistic review.
The _update_holistic_review_cache function (review.py lines 1428-1446) does store metadata:
import_holistic_findings lines 1413-1416: to decide whether to set or add to potentials["review"]
Nowhere for staleness checking -- there is no code that reads review_cache["holistic"]["reviewed_at"] to decide whether a re-run is needed
Summary: Holistic review has no timestamp/cache-based staleness mechanism. Running review --prepare --holistic always re-prepares from scratch. The stored reviewed_at timestamp and file_count_at_review are available in state but not currently used for any staleness detection or "already reviewed, skip" logic. The narrative reminder system also does not have a "holistic review stale" reminder (only per-file review staleness is checked).
I now have a comprehensive picture of all the mechanisms. Here is my complete research report.
How Desloppify Communicates Next Steps to Agents
There are 6 distinct mechanisms by which desloppify nudges agents toward specific actions. They operate at different layers: terminal output (what the agent reads from stdout), structured JSON (what the agent reads from query.json), and issue docs (on-disk markdown work orders).
_show_post_scan_analysis (lines 121-165) is the primary terminal nudge after every scan. It:
Prints warnings (lines 123-138): Contextual alerts for regressions (>5 reopened), cascading failures (>10 new with <3 resolved), and chronic reopeners.
Computes narrative (line 143): Calls compute_narrative(state, diff=diff, lang=lang_name, command="scan") which returns the full narrative dict.
Displays strategy hint OR top action (lines 146-159): There's a priority system:
If a strategy hint exists AND (lanes can be parallelized OR fixer recommendation is "strong"), it prints: Strategy: {hint} with Start with: {actions[0]['command']} underneath.
Otherwise, if there are actions, it prints: Suggested next: {top['command']} -- {top['description']}
Displays the headline (lines 161-163): A single sentence like "File health is your biggest lever: 12 items -> +4.2 pts" or "Score plateaued at 87.3 for 4 scans. Code quality (82.1%) is where the breakthrough is."
_print_llm_summary (lines 307-358) is a separate block explicitly labeled INSTRUCTIONS FOR LLM. It:
Prints overall health + strict health scores
Outputs a markdown table of dimensions (name, health, strict, issues, tier)
Prints total/open/fixed finding counts
Mentions the scorecard image path and suggests adding it to README
This block is designed for LLM consumption -- the agent reads terminal output and this gives it structured data to present to the user.
_write_query writes to .desloppify/query.json via safe_write_text. Every command calls it. After a scan, the full query.json payload is (from scan.py lines 262-271):
python
{
"command": "scan",
"score": state["score"],
"strict_score": state.get("strict_score", 0),
"prev_score": prev_score,
"diff": diff, # +new/-resolved/reopened counts
"stats": state["stats"], # open/total/fixed/by_tier
"warnings": warnings, # list of warning strings
"objective_score": ..., # LOC-weighted lenient score
"objective_strict": ..., # LOC-weighted strict score
"dimension_scores": ..., # per-dimension breakdown
"potentials": ..., # scoring potential data
"zone_distribution": ..., # files by zone type
"narrative": { # <-- THE FULL NARRATIVE DICT
"phase": str, # "first_scan"|"early_momentum"|"middle_grind"|"refinement"|"maintenance"|"stagnation"|"regression"
"headline": str | None, # one-sentence terminal headline
"dimensions": {
"lowest_dimensions": [...], # up to 3, sorted by strict score
"biggest_gap_dimensions": [...],
"stagnant_dimensions": [...]
},
"actions": [...], # prioritized action list (see below)
"strategy": {
"fixer_leverage": {...}, # coverage, impact_ratio, recommendation
"lanes": {...}, # cleanup/restructure/refactor lanes
"can_parallelize": bool,
"hint": str # one-sentence strategy hint
},
"tools": {
"fixers": [...], # available auto-fixers
"move": {...}, # move tool info
"plan": {...}, # plan command info
"badge": {...} # scorecard badge status
},
"debt": {
"overall_gap": float,
"wontfix_count": int,
"worst_dimension": str,
"worst_gap": float,
"trend": str # "stable"|"growing"|"shrinking"
},
"milestone": str | None, # "Crossed 90%!" etc
"reminders": [...], # context-specific reminders
"reminder_history": {...} # decay tracking (persisted back to state)
}
}
The next command writes a similar structure but with items (the actual findings to work on) plus the full narrative dict. The review command writes review preparation data plus narrative.
So the sort is: first by action type (issue_docs > auto_fix > reorganize > refactor > manual_fix > debt_review), then by descending impact within each type. Impact is computed by compute_score_impact() which estimates how many health points fixing N findings of a given detector would gain.
When review findings exist, the behavior depends on whether issue docs exist (lines 106-117):
If det == "review" AND count_issue_docs() > 0: The action type is boosted to "issue_docs" (priority 0 in type_order), the command becomes cat .desloppify/issues/*.md, and the description says "N issue docs in .desloppify/issues/ -- read and fix each one". This makes review issue docs the absolute top priority action.
If det == "review" AND no issue docs exist: The command is desloppify show review --status open and the description says "N review findings -- run review cycle to create issue docs".
If det == "subjective_review": Points to desloppify fix review.
Each action has: priority, type, detector, count, description, command, impact (estimated health points), dimension (which scoring dimension), and lane (added by strategy).
Strategy hints are one- or two-sentence execution plans that tell the agent HOW to work, not just WHAT to work on. They're computed in _compute_strategy_hint (lines 237-256).
The strategy system has three components:
a) Fixer Leverage (_compute_fixer_leverage, lines 25-57): Estimates what fraction of findings auto-fixers can handle. Produces a recommendation: "strong" (>40% coverage or >30% impact ratio), "moderate" (>10% coverage), or "none". Python always gets "none" (no auto-fixers).
b) Lanes (_compute_lanes, lines 60-200): Partitions all actions into parallelizable work lanes:
cleanup lane: all auto_fix actions, ordered by cascade dependency
restructure lane: reorganize actions (moves conflict, must serialize)
refactor_N lanes: grouped by file overlap using union-find
test_coverage lane: always separate
debt_review lane: separate
If cleanup lane files overlap with other lanes, cleanup is marked run_first=True.
c) The hint itself (lines 237-256):
Strong fixer + parallelizable: "Run fixers first -- they cover N% of findings. Then M independent workstreams, safe to parallelize."
Strong fixer only: "Run fixers first -- they cover N% of findings."
Parallelizable only: "M independent workstreams, safe to parallelize."
Maintenance phase: "Maintenance mode -- address new findings as they appear."
Stagnation: "Try a different dimension to break the plateau."
Default: "Work through actions in priority order."
The strategy hint is displayed in _show_post_scan_analysis (line 152) with higher priority than the top action -- it only shows when can_parallelize or fixer_leverage.recommendation == "strong".
Reminders are contextual nudges that live in the narrative dict (not printed to terminal by scan). They're consumed by agents reading query.json. There are 11 reminder types:
auto_fixers_available: "N findings are auto-fixable. Run desloppify fix X --dry-run."
rescan_needed: Only after fix/resolve/ignore commands.
badge_recommendation: When strict >= 90 and scorecard not in README.
wontfix_growing: When wontfix debt trend is "growing".
stagnant_nudge: Per stagnant dimension, suggests different angle or wontfix.
dry_run_first: When top action is auto_fix.
zone_classification: Shows zone distribution, suggests overrides for misclassifications.
fp_calibration_{det}_{zone}: When false positive rate >30% for a detector+zone combo.
review_not_run: When objective_strict >= 80 AND no review cache exists. Message: "Mechanical checks look good! Run a subjective design review to catch issues linters miss: desloppify review --prepare"
review_stale: When oldest review is >30 days old. Message: "Design review is N days old -- run: desloppify review --prepare"
feedback_nudge: After 2+ scans, scan-only. Encourages filing GitHub issues for false positives or missing patterns.
Decay system (lines 196-208): Each reminder type has a counter in reminder_history (persisted in state). The _REMINDER_DECAY_THRESHOLD is 3 (from _constants.py line 22). Once a reminder has been shown 3 times, it's suppressed forever. The decay is non-mutating: _compute_reminders returns (filtered_reminders, updated_history), and the scan command persists updated_history back to state (scan.py lines 258-260).
Review-specific reminders: Yes, there are two:
review_not_run (line 135-144): fires when mechanical score is high (>=80) but no review has ever been run.
review_stale (line 147-163): fires when the oldest review is >30 days old.
Issue docs are self-contained markdown work orders written to .desloppify/issues/. They are created during desloppify review --import (review_cmd.py lines 137-149) for each open review finding.
Each doc contains:
Title: {dimension}: {identifier}
Finding ID, dimension, confidence, score impact
Problem section (the finding's summary)
Evidence section (evidence lines from the review)
Suggested Fix section
Files section
"When Done" section with the exact resolve command
The key integration point is in _compute_actions (actions.py line 107-114): when count_issue_docs() > 0, review findings are boosted to issue_docs type (priority 0), and the command becomes cat .desloppify/issues/*.md. This means issue docs are always the #1 recommended action when they exist.
The headline also surfaces issue docs (headline.py lines 20-33): in maintenance/stagnation phases, if issue docs exist, the headline appends "(N issue docs in .desloppify/issues/)". If no docs exist but review findings are open, it appends "(N design review findings pending)".
Stale docs are cleaned up on review import (cleanup_stale_docs removes docs whose finding is no longer open).
Strategy hint (if applicable) -- "Run fixers first, then 3 parallel lanes"
Top action command -- "desloppify fix unused --dry-run" or "cat .desloppify/issues/*.md"
Headline -- one motivational/directional sentence incorporating security prefix and review suffix
LLM instructions block -- dimension table for the agent to present to the user
query.json -- the full narrative dict with actions, strategy, dimensions, reminders, tools, debt, milestone
The ordering of what agents see first is: issue_docs > auto_fix > reorganize > refactor > manual_fix > debt_review, with impact as the tiebreaker within each category. Security findings get a headline prefix that appears before everything else. Review findings get boosted to the absolute top when issue docs exist on disk.