I need to thoroughly understand how desloppify generates coaching prompts/guidance for users after scans. Explore these areas:
desloppify/narrative.py — the main narrative computation. I need to understand:
What phases exist and how they're determined
What actions/suggestions are generated
The DETECTOR_TOOLS mapping
How reminders work
The full structure of what gets returned
desloppify/commands/scan.py — how narrative results are displayed after a scan
desloppify/commands/next.py — the "next" command that suggests what to work on
desloppify/commands/show.py — how findings are shown
desloppify/commands/fix_cmd.py — what fixers exist and how they're invoked
desloppify/commands/plan_cmd.py — the plan command
Any fixer modules in desloppify/lang/typescript/fixers/ and desloppify/lang/python/ to understand what automated fixes are available
Read ALL of these files fully. I need the complete picture of:
What guidance/nudges currently exist
What fixers are available and what they fix
How findings are categorized and prioritized
The flow from scan → narrative → user action
Be very thorough - read every file completely.
Assistant
I'll read all the requested files in parallel to build a complete picture of the coaching/guidance system.
Assistant
Now let me read the fixer modules and the plan generation logic.
Assistant
Now let me read all the fixer modules and the scoring/dimensions system.
Assistant
Now let me read the scoring/dimensions system and the Python fixers.
Assistant
Now let me read the state module for completeness on how findings are managed.
Assistant
User
I need to understand the complete data flow from scan → narrative → query.json → agent consumption. Focus on:
In desloppify/narrative.py:
The exact signature and return shape of compute_narrative()
What _compute_actions() returns — exact dict keys per action
What _compute_tools() returns
How _compute_reminders() works (especially the auto_fixers_available reminder)
The FIXER_CASCADE / post_fix dependency — is there a static graph or only runtime hooks?
In desloppify/commands/scan.py:
How _show_post_scan_analysis() displays the narrative (what gets printed)
What gets written to query.json
In desloppify/commands/fix_cmd.py:
The _cascade_import_cleanup function — what triggers it
The fixer registry — full list of fixers and their detectors
In desloppify/commands/next.py:
What narrative data is written to query.json from next command
Assistant
I'll systematically read all the relevant files to trace the complete data flow. Let me start by reading the key files in parallel.
User
I need to understand the finding data structure and what file-level information is available for computing file overlap between detectors/actions. Explore:
In desloppify/state.py:
make_finding() — exact fields in a finding dict
How findings are keyed (the ID format)
The _upsert_findings / merge_scan flow
In the codebase, search for how findings group by file. Is there already a utility for "get all open findings for detector X"? What about "get file set for detector X"?
Look at the actual finding IDs — format is detector::file::name. This means we can extract file sets from finding IDs without scanning values.
In desloppify/narrative.py:
_count_open_by_detector() — currently only counts, doesn't track files. This is the function that would need to change (or a sibling function added).
Check the test files in tests/ — what test patterns exist for narrative.py? What fixtures/helpers are available?
Look at tests/test_narrative.py if it exists — understand the testing pattern so the plan can include tests.
Be thorough.
Assistant
Good, I have all five main files. Now let me search for the terms "lane", "parallel", "strategy", and "workstream" across the codebase, and also read the _write_query function and cli.py for the query.json write path.
Assistant
I'll systematically explore each area you've outlined. Let me start with parallel searches across the key files.
Assistant
Good, I have the main files. Now let me read the test file for narrative.py and search for file-grouping utilities and how findings are queried by detector.
Assistant
Let me also read the top of cli.py for imports and the _json_default helper, and check the other commands that write to query.json.
Assistant
Now let me also check the show.py and status.py commands for their query.json writes, to complete the picture.
Assistant
Now let me check a few more things: the plan.py grouping logic, how _compute_actions uses by_det, and look at the finding ID format more closely by examining how findings are actually created in the lang plugins.
Assistant
Now let me also look at how finding IDs are parsed/split elsewhere, and check what _compute_actions actually passes around (to understand where file overlap info would be useful).
Assistant
Let me also check the scoring.py compute_score_impact function (used in _compute_actions) and look at how the _compute_actions description strings are built, to understand where file overlap info would be consumed.
Assistant
Now let me check what the STRUCTURE.md says about finding IDs and look at a real example of findings in the codebase.
Assistant
Assistant
User
Assistant
I'll start by thoroughly exploring the codebase to understand the current architecture before designing the implementation plan.
Assistant
Now let me explore the fixer infrastructure to understand the cascade hooks and how fixers work.
Assistant
Now let me look at how _compute_actions is consumed downstream and understand the full fixer registry to map fixer names to detectors precisely.
Assistant
Let me now look at how the narrative is consumed in query.json, and check the test_cmd_scan tests to understand integration patterns.
Assistant
Let me now check the existing query.json to see the full narrative output shape, and look at how actions flow to understand the detector field naming used in findings vs in DETECTOR_TOOLS.
Assistant
Now I have a thorough understanding of the entire architecture. Let me look at one more thing -- the _compute_actions function to confirm each action has a detector name I can trace back to DETECTOR_TOOLS, and check what the actions list looks like with auto_fix items for a TS scan.
Assistant
I now have a comprehensive understanding of all the pieces. Let me also quickly check whether actions carry a detector field currently (looking at the action dicts being built in _compute_actions).
Assistant
I notice that actions do NOT carry a detector field -- they have description, command, type, count, impact, dimension, and optionally tool_hint and gap. The detector name is only embedded in the description string and command. This is an important observation for the design. Let me verify by checking if there's a detector key in any action.
Assistant
Now I have a complete picture. Here is my thorough analysis.
Complete Analysis: Desloppify Coaching & Guidance System
This is the core intelligence that computes structured coaching context. It is a pure-function module (no print statements, no side effects) that returns a dict consumed by commands and written to .desloppify/query.json.
8 types of contextual reminders, each with decay (suppressed after 3 occurrences):
auto_fixers_available -- "{N} findings are auto-fixable. Run {command}."
rescan_needed -- Only after fix/resolve/ignore commands
badge_recommendation -- Score >= 90 and scorecard not in README
wontfix_growing -- Debt trend is "growing"
stagnant_nudge -- Per stagnant dimension, specific guidance
dry_run_first -- When top action is auto_fix
zone_classification -- Non-production zone files exist, suggest override
fp_calibration_{det}_{zone} -- When FP rate > 30% for a detector+zone combo
Reminder decay: reminder_history dict in state tracks show count per type. Reminders shown >= 3 times are suppressed. The updated history is returned (not mutated in place) and persisted by the calling command.
Dimension score: potential-weighted pass rate across all detectors in that dimension
Overall score: tier-weighted average of dimension scores, dampened by sample size (MIN_SAMPLE=200)
Tier weights: T1=1, T2=2, T3=3, T4=4
Two modes: lenient (only "open" counts as failure) and strict (both "open" and "wontfix" count)
Zones excluded from scoring: test, generated, vendor, script (from zones.py)
Impact estimation (compute_score_impact): Simulates fixing N issues in a detector by reducing weighted failures, recomputing the dimension score, then recomputing the overall score. Returns the delta.
Runs a single detector directly (bypasses state tracking). Requires --lang flag. Validates detector name against the language's detect_commands registry.
COMPLETE FLOW: Scan -> Narrative -> User Action
code
User runs: desloppify scan --path <dir>
1. SCAN PHASE
- Language resolved (--lang or auto-detect)
- Zone map built from file paths + zone rules
- Detector phases run sequentially (each phase = one detector)
- Each finding gets: id, detector, file, tier, confidence, summary, detail, zone
- Potentials collected (checked counts per detector)
- Excluded directories audited for staleness
2. STATE MERGE
- New findings upserted (update existing, insert new)
- Reopened findings tracked (was fixed/auto_resolved, now reappeared)
- Disappeared findings auto-resolved (unless suspect detector)
- Stats recomputed: per-status counters, tier breakdowns
- Scores recomputed: weighted progress + dimension-based objective health
- Scan history appended for trajectory tracking
3. DISPLAY
- Diff: +new / -resolved / reopened
- Score with deltas
- Detector progress bars
- Dimension deltas
- Warnings (mass reopens, cascading fixes, chronic reopeners)
4. NARRATIVE COMPUTATION
- Phase detected from scan history trajectory
- Dimensions analyzed (lowest, biggest gap, stagnant)
- Debt analyzed (wontfix gap, trend)
- Milestones checked
- Actions prioritized (auto_fix > reorganize > refactor > manual_fix > debt_review)
- Tools inventoried
- Headline computed (one sentence, priority cascade)
- Reminders generated with decay
5. USER SEES
- "Suggested next: `desloppify fix unused-imports --dry-run` -- 42 unused findings -- auto-fixable"
- "-> Import hygiene is your biggest lever: 42 items -> +3.2 pts"
- Reminders: "Always --dry-run first, review changes, then apply."
6. USER ACTS
- `desloppify next` -- get specific highest-priority finding with resolution commands
- `desloppify fix <fixer> --dry-run` -- preview auto-fix
- `desloppify fix <fixer>` -- apply auto-fix, see retro checklist
- `desloppify show <detector>` -- dig into all findings for a detector
- `desloppify move <src> <dest>` -- restructure files with import rewiring
- `desloppify plan` -- generate full markdown plan
- `desloppify resolve fixed/wontfix "<id>"` -- manually mark findings
- `desloppify scan` -- rescan to see updated scores
In desloppify/scoring.py:
The compute_score_impact function signature and what it returns
Search for any existing notion of "lane", "parallel", "strategy", "workstream" in the codebase to confirm none exists yet.
Be very thorough — read all relevant files completely.
Now I have the complete picture. Here is the thorough analysis:
auto_fixers_available -- only if lang != "python" and there are auto_fix actions. Message includes total count and first fixer command.
rescan_needed -- only if command in ("fix", "resolve", "ignore").
badge_recommendation -- only if obj_strict >= 90 and scorecard exists but not in README.
wontfix_growing -- only if debt["trend"] == "growing".
stagnant_nudge -- one per stagnant dimension.
dry_run_first -- if top action is auto_fix.
zone_classification -- if any non-production files in zone distribution.
fp_calibration_{detector}_{zone} -- for any (detector, zone) pair with FP rate > 30% and >= 5 total findings.
Decay mechanism (lines 780-791): Each reminder type has a counter in reminder_history (persisted in state). When a reminder has been shown >= _REMINDER_DECAY_THRESHOLD (3) times, it is filtered out. Only shown reminders increment the counter.
FIXER_CASCADE / post_fix dependency
There is NO static dependency graph. The cascade is purely runtime hooks. The only cascade mechanism is the post_fix field on fixer configs:
In /Users/user_c042661f/Documents/desloppify/desloppify/commands/fix_cmd.py, line 95-96:
python
if fixer.get("post_fix"):
fixer["post_fix"](path, state, prev_score, False)
Only two fixers have post_fix set (both to _cascade_import_cleanup):
"debug-logs" (line 163)
"dead-useeffect" (line 177)
_cascade_import_cleanup (line 265) runs detect_unused(path, category="imports") then fix_unused_imports on any results. This is the only cascade -- removing code (logs or dead useEffect) may orphan imports, so it re-detects and cleans them.
The FixerConfig dataclass in /Users/user_c042661f/Documents/desloppify/desloppify/lang/base.py line 35 defines post_fix: Callable | None = None, so language plugins can also register post_fix hooks, but currently only the built-in registry uses it.
2. commands/scan.py — what gets printed and what gets written
Additionally, after the query write, reminder_history from the narrative is persisted back to state (lines 253-255).
3. commands/fix_cmd.py — cascade and fixer registry
_cascade_import_cleanup (line 265)
Trigger: Called as a post_fix hook after debug-logs and dead-useeffect fixers run (in non-dry-run mode only). It is invoked at line 95-96 of _apply_and_report:
python
if fixer.get("post_fix"):
fixer["post_fix"](path, state, prev_score, False)
What it does: Re-runs unused import detection, then fixes any newly-orphaned imports, then resolves matching findings in state.
Full fixer registry (lines 157-181 in _get_fixer()):
Fixer name
label
detector
post_fix
unused-imports
unused imports
unused
None
debug-logs
tagged debug logs
logs
_cascade_import_cleanup
dead-exports
dead exports
exports
None
unused-vars
unused vars
unused
None
unused-params
unused params
unused
None
dead-useeffect
dead useEffect calls
smells
_cascade_import_cleanup
empty-if-chain
empty if/else chains
smells
None
These are the built-in (TypeScript) fixers. Language plugins can register additional fixers via LangConfig.fixers (a dict[str, FixerConfig]). The _load_fixer function at line 41 checks the language plugin first, falling back to the built-in registry.
Note: next passes command="next" to compute_narrative(), which means the rescan_needed reminder will NOT fire (it only fires for "fix", "resolve", "ignore").
5. scoring.py — compute_score_impact()
Signature (line 191):
python
def compute_score_impact(
dimension_scores: dict, # {dim_name: {"score": float, "tier": int, "detectors": dict}}
potentials: dict[str, int], # {detector: potential_count}
detector: str, # which detector's issues to simulate fixing
issues_to_fix: int, # how many issues to simulate fixing
) -> float # estimated point increase in overall objective score
What it does:
Finds which Dimension the detector belongs to (line 202-205).
Looks up the detector's weighted_failures from dimension_scores[dim_name]["detectors"][detector].
Simulates reducing weighted_failures by issues_to_fix * 1.0 (assumes high-confidence fixes).
Recomputes the dimension score with the simulated improvement.
Recomputes the overall objective score with the simulated dimension score.
Returns round(new_score - old_score, 1).
Returns 0.0 if the detector is not found in any dimension, has no potential, or has no data in dimension_scores.
6. Confirming absence of "lane", "parallel", "strategy", "workstream"
The grep for lane|parallel|strategy|workstream (case-insensitive) across the entire /Users/user_c042661f/Documents/desloppify directory returned zero matches. None of these concepts exist in the codebase.
Summary of the complete query.json write sites
Every command writes to the same QUERY_FILE at /Users/user_c042661f/Documents/desloppify/.desloppify/query.json. Each overwrites the previous content. Commands that write:
Command
File
Includes narrative?
scan
commands/scan.py:257
Yes (full)
fix (apply)
commands/fix_cmd.py:105
Yes
fix (dry-run)
commands/fix_cmd.py:123
Yes
next
commands/next.py:38
Yes
show
commands/show.py:101
Yes
status
commands/status.py:123
Yes
resolve
commands/resolve.py:51
Yes
ignore
commands/resolve.py:79
Yes
I now have a thorough understanding of the entire data flow. Here is my comprehensive report.
Finding Data Structure and File Overlap Analysis
1. make_finding() -- Exact Fields
Located at /Users/user_c042661f/Documents/desloppify/desloppify/state.py, lines 218-228:
id -- string, the stable key (see ID format below)
detector -- string, e.g. "unused", "smells", "large", "coupling"
file -- string, relative path from project root (via rel())
tier -- int (1-4)
confidence -- string: "high", "medium", "low"
summary -- string, human-readable description
detail -- dict, detector-specific metadata
status -- string, starts as "open" (others: "fixed", "auto_resolved", "wontfix", "false_positive")
note -- string or None
first_seen -- ISO timestamp
last_seen -- ISO timestamp
resolved_at -- ISO timestamp or None
reopen_count -- int, starts at 0
Additional fields added during merge:
lang -- string, set in _upsert_findings if lang param is provided (line 309)
zone -- string, set during upsert if present on incoming finding (line 315)
2. Finding ID Format
The ID is detector::relative_file::name when name is truthy, or detector::relative_file when name is empty/falsy. From STRUCTURE.md line 91: "Finding ID format: detector::file::name -- if a detector changes naming, findings lose state continuity."
Examples of real IDs (from the lang plugins):
unused::src/utils.ts::helperFn
smells::src/App.tsx::eval_exec
structural::src/components/Form.tsx (name is empty for structural)
Key insight: The file is always the second :: delimited component. You can extract the file from a finding ID by splitting on :: and taking index 1. No code currently does this -- every place that needs the file accesses f["file"] directly from the finding dict value.
3. The _upsert_findings / merge_scan Flow
_upsert_findings (state.py lines 293-327):
Takes existing findings dict (by reference), a list of current finding dicts, ignore list, timestamp, and optional lang.
Iterates current findings, skips ignored ones, adds to current_ids set.
Builds by_detector counter (counts per detector name, used for suspect detection).
For existing findings: updates last_seen, tier, confidence, summary, detail, zone; reopens if previously resolved.
For new findings: inserts directly into existing dict.
Calls _find_suspect_detectors to identify detectors that disappeared suspiciously.
Calls _auto_resolve_disappeared to auto-resolve findings no longer found.
Calls _recompute_stats for scoring.
Appends to scan_history.
Returns a diff summary dict.
4. Grouping by File -- Existing Patterns
There is no centralized utility for "get all open findings for detector X" or "get file set for detector X". Each consumer re-implements the pattern inline:
Location
Pattern
narrative.py:_count_open_by_detector (line 61)
Counts open by detector, merges structural. Returns dict[str, int] -- counts only, no files.
show.py:show_cmd (line 116)
by_file[f["file"]].append(f) for display grouping
show.py:_build_show_payload (line 172)
Same grouping for JSON output
plan.py:_plan_tier_sections (line 166)
by_tier_file[f["tier"]][f["file"]].append(f)
visualize.py (lines 108, 262)
findings_by_file[f["file"]].append(f)
scoring.py:_detector_pass_rate (line 88)
by_file[file_key] for file-based detectors only
state.py:_find_suspect_detectors (line 248)
Counts open by detector (duplicates narrative logic)
No function computes file sets per detector. Each consumer filters by status and/or detector ad hoc. The _count_open_by_detector function in narrative.py is the closest thing, but it only counts -- it does not collect files or file sets.
5. _count_open_by_detector() in narrative.py
Located at /Users/user_c042661f/Documents/desloppify/desloppify/narrative.py, lines 61-71:
python
def _count_open_by_detector(findings: dict) -> dict[str, int]:
"""Count open findings by detector, merging structural sub-detectors."""
by_det: dict[str, int] = {}
for f in findings.values():
if f["status"] != "open":
continue
det = f.get("detector", "unknown")
if det in STRUCTURAL_MERGE:
det = "structural"
by_det[det] = by_det.get(det, 0) + 1
return by_det
This function:
Iterates all findings once, filters to status == "open".
Merges structural sub-detectors (large, complexity, gods, concerns) into "structural".
Returns only counts, not file lists.
This is called once in compute_narrative (line 98) and the result by_det is passed to _compute_actions and _compute_tools.
To add file overlap info, you would either:
Modify this function to return dict[str, dict] with both count and file set (e.g., {"unused": {"count": 5, "files": {"a.ts", "b.ts"}}}).
Add a sibling function like _open_files_by_detector(findings) -> dict[str, set[str]] that computes file sets, and call both from compute_narrative.
Option 2 (sibling function) is cleaner -- it avoids changing the return type which would ripple to all callers of _count_open_by_detector.
6. How _compute_actions Would Use File Overlap
_compute_actions (narrative.py lines 356-473) currently receives by_det: dict[str, int] and iterates over DETECTOR_TOOLS, computing impact and building action dicts. Each action gets:
count -- from by_det.get(det, 0)
impact -- from compute_score_impact
description -- formatted string
dimension -- from get_dimension_for_detector
If file overlap were available, actions could include:
"files_shared_with" -- list of other detectors that touch the same files
"unique_files" -- count of files only touched by this detector
Better prioritization (a detector whose files overlap heavily with a higher-impact detector might be deprioritized, or they could be grouped as "while you're in these files...")
7. Extracting File Sets from Finding IDs
You mentioned that detector::file::name format means you can extract file sets from finding IDs without scanning values. This is true but has a caveat:
The ID parsing would be:
python
parts = fid.split("::", 2) # maxsplit=2 since name can contain "::"
file_part = parts[1] if len(parts) >= 2 else ""
However, some finding names themselves contain :: (e.g., react::src/hooks/useAuth.tsx::nesting::5), so you must use maxsplit=2 or just access f["file"] from the value. Since the findings dict is {fid: finding_dict}, and every finding_dict has "file", it is simpler and safer to use the value's "file" field rather than parsing the ID.
No code in the codebase currently parses finding IDs by splitting on ::. The grep for .split("::") returned zero matches. Every consumer accesses f["file"] from the finding dict.
8. Test Patterns for narrative.py
The test file is at /Users/user_c042661f/Documents/desloppify/tests/test_narrative.py (1000 lines).
Helpers defined (lines 22-60):
python
def _finding(detector, *, status="open", confidence="high", file="a.py", zone="production") -> dict:
"""Build a minimal finding dict."""
return {"detector": detector, "status": status, "confidence": confidence,
"file": file, "zone": zone}
def _findings_dict(*findings: dict) -> dict:
"""Wrap a list of finding dicts into an id-keyed dict."""
return {str(i): f for i, f in enumerate(findings)}
def _history_entry(objective_strict=None, objective_score=None, lang=None, dimension_scores=None) -> dict:
# ...builds history entry dict
Note: The _finding helper already takes a file parameter with a default of "a.py". The _findings_dict helper keys findings by sequential integer strings ("0", "1", etc.) rather than real finding IDs. This means tests do NOT rely on ID parsing -- they use dict values.
Test classes and coverage:
Class
Tests
What's covered
TestCountOpenByDetector
9 tests
Empty, status filtering, multi-detector, structural merge for all 4 sub-detectors, combined, non-structural separation, missing detector key
TestDetectPhase
14 tests
All phases: first_scan, regression, stagnation, early_momentum, maintenance, refinement, middle_grind. Priority ordering. Edge cases with None values
TestDetectMilestone
10 tests
All milestones: 90/80 crossings, T1/T2 cleared, zero open findings. Edge cases
Return type, decay suppression, history increment, rescan triggers, wontfix growing, badge recommendation, auto-fixers, stagnant dimensions, dry-run, state immutability
TestComputeHeadline
12 tests
All headline paths: milestone priority, first_scan, regression, stagnation (with/without wontfix), leverage point, maintenance, middle_grind, early_momentum, gap callout, None edge case
Testing pattern: Each test function is focused on one behavior. The helper _finding() creates minimal dicts (not full make_finding output). The helpers are local to the test file (not shared fixtures). The _findings_dict helper is identical in both test_narrative.py and test_scoring.py (copied, not shared).
No pytest fixtures are used in test_narrative.py -- all setup is inline. The pattern is pure-function testing: call the function with constructed inputs, assert on the output.
9. Summary: What Exists vs. What's Missing
Exists:
_count_open_by_detector() -- counts per detector (narrative.py)
_count_findings() -- counts per status and tier (state.py)
Ad-hoc by_file grouping in show, plan, visualize, scoring
Finding dict has "file" and "detector" fields always available
Well-established test patterns in test_narrative.py with helpers for creating test findings
Missing (would need to be added for file overlap):
A function to compute dict[str, set[str]] mapping detector -> set of files (open only)
A function to compute overlap matrix or pairwise file overlap between detectors
Any use of file overlap information in _compute_actions or action prioritization
No finding ID parsing utility (and none is needed -- f["file"] is always available)
Design an implementation plan for adding execution strategy computation to the desloppify narrative system. Here is the complete context from my exploration:
Background
Desloppify is a Python CLI codebase health tool. After scanning, it computes a "narrative" (structured coaching context) that flows into .desloppify/query.json for LLM agents to consume. The narrative currently has: phase, headline, dimensions, actions (prioritized flat list), tools, debt, milestone, reminders.
The MISSING piece: the narrative tells agents WHAT to do but not HOW to approach the work. Specifically:
When to use automated fixers first (clear the noise before manual work)
When work can be split across multiple parallel agents (independent file sets)
Current architecture
narrative.py (pure functions, no side effects)
compute_narrative(state, diff, lang, command) -> dict is the entry point. Key internal functions:
_count_open_by_detector(findings) -> dict[str, int] — counts only, no file info
Each action has: priority, type ("auto_fix"|"reorganize"|"refactor"|"manual_fix"|"debt_review"), count, description, command, impact, dimension
Findings structure
Each finding has: id, detector, file (relative path), tier, confidence, status, detail, zone.
Keyed by ID in state["findings"].
Fixer cascade (runtime only, no static graph)
Two fixers have post_fix hooks pointing to _cascade_import_cleanup:
debug-logs → re-runs unused-imports detection after
dead-useeffect → same
Test patterns (test_narrative.py, ~1000 lines)
Helper: _finding(detector, status="open", confidence="high", file="a.py", zone="production")
Helper: _findings_dict(*findings) — wraps list into id-keyed dict
Pure function tests: construct inputs, call function, assert output.
Design requirements
1. Fixer leverage analysis
Compute what fraction of open findings and recoverable impact is auto-fixable.
Strong recommendation when coverage > 40% or impact > 30% of total
Phase-aware: especially strong for first_scan (T1 noise), stagnation (untouched fixers), regression (fixable regression)
Never for Python (no fixers)
2. Parallelism analysis (lanes)
Group actions into independent work streams based on:
Auto-fix actions → one "cleanup" lane (with cascade ordering)
Reorganize actions → one "restructure" lane (serialized — moves conflict)
Refactor actions → partition by file overlap (connected components)
test_coverage → always independent
Lane computation needs file sets per detector from open findings. Add a sibling function _open_files_by_detector(findings) -> dict[str, set[str]] alongside existing _count_open_by_detector.
A lane is parallelizable with another lane only when their file sets don't intersect.
3. Static cascade graph
Extract from runtime post_fix hooks into a constant:
hint — one or two sentences of specific, actionable guidance
5. Display integration
_show_post_scan_analysis in scan.py currently shows "Suggested next: {top action}". When strategy exists and is meaningful, show the strategy hint instead of (or in addition to) the bare top action.
6. Sense-check step
After implementing, run desloppify scan against both the Python self-scan and a TS codebase, inspect the query.json to verify the strategy output makes sense.
Constraints
narrative.py must remain pure functions (no side effects)
Follow existing patterns (same helper style, same test patterns)
Minimal changes to existing data structures — enrich, don't restructure
Keep it simple — no over-engineering
Please design:
The exact functions to add/modify in narrative.py
The strategy dict structure
How actions get lane annotations
The fixer leverage computation
The file overlap / lane computation algorithm
Changes to scan.py display
Test plan (what test cases for each new function)
A sense-check step to verify the output is reasonable
Think about edge cases: zero findings, Python (no fixers), single detector dominance, all findings in same file, maintenance phase.
Only in _compute_tools, not in actions themselves. Good. Now I have everything I need. Let me produce the complete implementation plan.
Here is the complete implementation plan for adding execution strategy computation to the desloppify narrative system.
Implementation Plan: Execution Strategy for Narrative System
1. Overview
The narrative currently tells agents WHAT to fix but not HOW to approach the work. This plan adds a strategy key to the narrative output that computes:
Fixer leverage: what fraction of findings are auto-fixable and how much impact that represents
Lanes: independent work streams that can be executed in parallel
Cascade ordering: which fixers should run before others
A strategy hint: one or two sentences of actionable guidance
All new code goes in /Users/user_c042661f/Documents/desloppify/desloppify/narrative.py as pure functions. Display integration touches /Users/user_c042661f/Documents/desloppify/desloppify/commands/scan.py. Tests go in /Users/user_c042661f/Documents/desloppify/tests/test_narrative.py.
2. Static Cascade Graph (Constant)
Add at module level in narrative.py, after the DETECTOR_TOOLS constant (around line 55):
python
# Fixer cascade: fixers whose post_fix hook triggers re-detection of another detector.
# Derived from fix_cmd.py _get_fixer registry post_fix hooks.
FIXER_CASCADE = {
"debug-logs": ["unused-imports"],
"dead-useeffect": ["unused-imports"],
}
This is a static extraction of the runtime post_fix -> _cascade_import_cleanup relationship from /Users/user_c042661f/Documents/desloppify/desloppify/commands/fix_cmd.py lines 163 and 177. The cascade graph encodes: "after running fixer X, detector Y may have new findings to fix."
At the detector level, the cascade means:
python
# Which detector's findings get created/changed after fixing another detector.
# Keyed by source detector, values are affected detectors.
_DETECTOR_CASCADE = {
"logs": ["unused"], # debug-logs fixer -> unused-imports cleanup
"smells": ["unused"], # dead-useeffect fixer -> unused-imports cleanup
}
This second mapping (derived from FIXER_CASCADE by looking up detector names in DETECTOR_TOOLS) is what the lane computation needs.
3. New Function: _open_files_by_detector
Add as a sibling to _count_open_by_detector (around line 61). Same structure, returns file sets instead of counts:
python
def _open_files_by_detector(findings: dict) -> dict[str, set[str]]:
"""Collect open findings' file paths by detector, merging structural sub-detectors."""
by_det: dict[str, set[str]] = {}
for f in findings.values():
if f["status"] != "open":
continue
det = f.get("detector", "unknown")
if det in STRUCTURAL_MERGE:
det = "structural"
by_det.setdefault(det, set()).add(f.get("file", ""))
return by_det
Key design point: this mirrors _count_open_by_detector exactly (same filtering, same structural merge) to keep them consistent.
4. New Function: _compute_fixer_leverage
python
def _compute_fixer_leverage(
by_det: dict[str, int],
files_by_det: dict[str, set[str]],
actions: list[dict],
phase: str,
lang: str | None,
) -> dict:
"""Compute what fraction of work is auto-fixable and how impactful that is.
Returns dict with: auto_fixable_count, total_count, coverage, impact_ratio,
recommendation ("strong"|"moderate"|"none"), reason.
"""
Logic:
If lang == "python", return {"recommendation": "none", "reason": "no auto-fixers for Python", ...} with zero counts. Python has no fixers.
Count auto-fixable findings: sum by_det[det] for detectors where DETECTOR_TOOLS[det]["action_type"] == "auto_fix".
Count total open findings: sum(by_det.values()).
coverage = auto_fixable / total if total > 0, else 0.
Impact ratio: sum impact of auto_fix actions vs sum of all action impacts.
python
auto_impact = sum(a.get("impact", 0) for a in actions if a["type"] == "auto_fix")
total_impact = sum(a.get("impact", 0) for a in actions)
impact_ratio = auto_impact / total_impact if total_impact > 0 else 0
Recommendation strength:
"strong" if coverage > 0.4 or impact_ratio > 0.3
Phase boost: also "strong" for phase in ("first_scan", "stagnation", "regression") when coverage > 0.15
first_scan: clear T1 noise first
stagnation: untouched fixers are easy wins
regression: fixable regressions are the fastest recovery path
"moderate" if coverage > 0.1 (some fixable work exists)
"none" otherwise
Reason string: describe why, e.g. "42% of findings are auto-fixable -- run fixers first to clear noise".
The current _compute_actions function builds action dicts but does not include a detector key. The detector name is only embedded in the description string. Lane computation needs to map actions back to detectors.
Modify _compute_actions to add "detector": det to each action dict (for the auto_fix, reorganize, refactor, and manual_fix action types). The debt_review action gets "detector": None.
This is a minimal enrichment: add one key to each action dict. Example change at line 404:
All auto_fix actions go into one lane named "cleanup".
Ordered by cascade: if detector A cascades into detector B, A runs first.
Cascade ordering within the cleanup lane: use _DETECTOR_CASCADE to topologically sort.
All reorganize actions go into one lane named "restructure" (serialized because moves conflict).
Each refactor / manual_fix action starts as its own candidate lane.
debt_review actions go into a lane named "debt_review".
test_coverage (if present as a refactor action) goes into its own lane "test_coverage" -- always independent since test files don't overlap with production findings.
Step 2: Merge refactor lanes by file overlap (connected components).
For refactor/manual_fix actions, compute connected components based on file set intersection:
python
# Build adjacency: two detectors share a lane if their file sets overlap
# Union-Find (simple dict-based) over detector names
parent = {}
def find(x):
while parent.get(x, x) != x:
parent[x] = parent.get(parent[x], parent[x])
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
refactor_dets = [a["detector"] for a in actions
if a["type"] in ("refactor", "manual_fix") and a.get("detector")]
for i, d1 in enumerate(refactor_dets):
for d2 in refactor_dets[i+1:]:
f1 = files_by_det.get(d1, set())
f2 = files_by_det.get(d2, set())
if f1 & f2:
union(d1, d2)
# Group into components
components = {}
for d in refactor_dets:
root = find(d)
components.setdefault(root, []).append(d)
Name each component lane: if single detector, use "refactor_{detector}". If multiple, use "refactor_{first_detector}_group".
Step 3: Check inter-lane independence.
Two lanes are parallelizable if their file sets do not intersect. Compute the union of files per lane, then check pairwise. Special cases:
cleanup lane files overlap with some refactor lanes -- that's expected. But the cleanup lane should run FIRST (it reduces noise), so mark these as "serial_after_cleanup" rather than parallel.
test_coverage lane is always independent (test files are not in production file sets).
Step 4: Build lane dicts.
For each lane:
python
{
"actions": [priority_ints], # which actions belong here
"files": sorted(file_set), # for transparency (capped at 20 for readability)
"file_count": len(file_set),
"total_impact": sum_of_impacts,
"automation": "full"|"partial"|"manual",
"depends_on": [], # lane names that must complete first
}
automation:
"full" if all actions in the lane are auto_fix
"partial" if some actions are auto_fix
"manual" if no actions are auto_fix
Step 5: Build the return value including can_parallelize.
python
can_parallelize = len([l for l in lanes.values() if not l["depends_on"]]) > 1
7. New Function: _compute_strategy_hint
python
def _compute_strategy_hint(
fixer_leverage: dict,
lanes: dict[str, dict],
can_parallelize: bool,
phase: str,
) -> str:
"""Generate one or two sentences of actionable execution guidance."""
Logic (priority order, first match wins):
Strong fixer leverage + parallelizable: "Run fixers first (cleanup lane) to clear {N} auto-fixable findings, then split remaining work across {M} parallel lanes."
Strong fixer leverage, single lane: "Start with auto-fixers -- they cover {pct}% of open findings. Rescan after to see what remains."
No fixers, parallelizable: "Work can split into {M} independent lanes with no file overlap. Assign each to a separate agent."
Phase-specific:
first_scan + fixers: "First scan: run fixers to clear the low-hanging fruit, then focus on {lowest_dim}."
stagnation + fixers: "Plateau detected -- untouched fixers could break through. Run cleanup first."
regression + fixers: "Score dropped -- {N} findings are auto-fixable. Fix those first to recover fast."
maintenance: "Maintenance mode. No strategy needed -- address individual items as they arise."
Fallback: "Work through actions in priority order. Top action: {top_action_description}."
8. New Function: _compute_strategy
This is the top-level orchestrator, called from compute_narrative:
python
def _compute_strategy(
findings: dict,
by_det: dict[str, int],
actions: list[dict],
phase: str,
lang: str | None,
) -> dict:
"""Compute execution strategy: fixer leverage, lanes, parallelism hint.
Returns dict with: fixer_leverage, lanes, can_parallelize, hint.
Returns minimal dict if no meaningful strategy exists (e.g. zero findings).
"""
files_by_det = _open_files_by_detector(findings)
fixer_leverage = _compute_fixer_leverage(by_det, files_by_det, actions, phase, lang)
lanes = _compute_lanes(actions, files_by_det)
# Determine parallelizability
independent_lanes = [name for name, lane in lanes.items() if not lane.get("depends_on")]
can_parallelize = len(independent_lanes) > 1
hint = _compute_strategy_hint(fixer_leverage, lanes, can_parallelize, phase)
# Annotate actions with lane names
lane_by_priority = {}
for lane_name, lane_data in lanes.items():
for p in lane_data["actions"]:
lane_by_priority[p] = lane_name
for action in actions:
action["lane"] = lane_by_priority.get(action["priority"])
return {
"fixer_leverage": fixer_leverage,
"lanes": {name: {k: v for k, v in lane.items() if k != "files"} # omit raw file set
for name, lane in lanes.items()},
"can_parallelize": can_parallelize,
"hint": hint,
}
Note: the files set is excluded from the serialized output to avoid bloating query.json. Only file_count is included.
9. Integration into compute_narrative
In compute_narrative (line 74), after computing actions (line 105) and before building the return dict (line 112):
python
# After line 105:
actions = _compute_actions(by_det, dim_scores, state, debt, lang)
# NEW: compute execution strategy (annotates actions with lane field)
strategy = _compute_strategy(findings, by_det, actions, phase, lang)
# Modified return dict (line 112):
return {
"phase": phase,
"headline": headline,
"dimensions": dimensions,
"actions": actions, # now enriched with "detector" and "lane" fields
"tools": tools,
"debt": debt,
"milestone": milestone,
"strategy": strategy, # NEW
"reminders": reminders,
"reminder_history": updated_reminder_history,
}
Order matters: _compute_strategy must run after _compute_actions because it consumes the actions list and annotates it with lane assignments.
10. Display Integration in scan.py
In /Users/user_c042661f/Documents/desloppify/desloppify/commands/scan.py, function _show_post_scan_analysis (line 121):
Current code (lines 146-151):
python
actions = narrative.get("actions", [])
if actions:
top = actions[0]
print(c(f" Suggested next: `{top['command']}` -- {top['description']}", "cyan"))
print()
Replace with:
python
strategy = narrative.get("strategy", {})
hint = strategy.get("hint")
actions = narrative.get("actions", [])
if hint and strategy.get("can_parallelize") or strategy.get("fixer_leverage", {}).get("recommendation") == "strong":
# Show strategy hint when it's meaningful
print(c(f" Strategy: {hint}", "cyan"))
if actions:
top = actions[0]
print(c(f" Start with: `{top['command']}`", "dim"))
print()
elif actions:
top = actions[0]
print(c(f" Suggested next: `{top['command']}` -- {top['description']}", "cyan"))
print()
This shows the strategy hint when it provides value (parallelism or strong fixer leverage) and falls back to the existing top-action display otherwise. The top action command is still shown as a concrete starting point.
11. Edge Cases
Scenario
Expected behavior
Zero findings
_compute_strategy returns {"fixer_leverage": {"recommendation": "none", ...}, "lanes": {}, "can_parallelize": False, "hint": "No open findings."}
Python lang
fixer_leverage.recommendation = "none", no cleanup lane. All actions are manual_fix/refactor lanes.
Single detector
One lane, can_parallelize = False. Hint falls through to phase-specific or fallback.
All findings in same file
Union-find merges all refactor detectors into one component. Single lane, not parallelizable.
Maintenance phase
Hint: "Maintenance mode. No strategy needed." Lanes still computed for completeness but hint downplays them.
Only auto_fix findings
One "cleanup" lane. can_parallelize = False (single lane). Hint emphasizes running fixers.
Only reorganize findings
One "restructure" lane. Serial. Hint: "Work through reorganization actions in order."
test_coverage only
One "test_coverage" lane. Independent by definition but single lane so can_parallelize = False.
Cascade: logs + unused
Both in cleanup lane. Logs action ordered before unused-imports due to cascade (logs -> unused).
12. Test Plan
All tests in /Users/user_c042661f/Documents/desloppify/tests/test_narrative.py, following existing patterns (pure function tests, _finding / _findings_dict helpers).
Test class: TestOpenFilesByDetector (mirrors TestCountOpenByDetector)
Test
Input
Assertion
test_empty_findings
{}
Returns {}
test_only_open_counted
Mix of statuses
Only open findings' files in result
test_multiple_detectors
Findings across detectors
Correct file sets per detector
test_structural_merge
large + complexity findings
Both merged under "structural" key
test_deduplicates_same_file
Two findings same detector same file
File appears once in set
test_different_files
Two findings same detector different files
Both files in set
Test class: TestFixerLeverage
Test
Input
Assertion
test_python_no_fixers
lang="python"
recommendation == "none"
test_no_auto_fix_findings
by_det with only reorganize detectors
coverage == 0, recommendation == "none"
test_high_coverage_strong
50 unused out of 80 total
coverage > 0.4, recommendation == "strong"
test_high_impact_ratio_strong
auto_fix actions with dominant impact
impact_ratio > 0.3, recommendation == "strong"
test_first_scan_phase_boost
phase="first_scan", coverage 0.2
recommendation == "strong" (phase boost)
test_stagnation_phase_boost
phase="stagnation", coverage 0.2
recommendation == "strong"
test_regression_phase_boost
phase="regression", coverage 0.2
recommendation == "strong"
test_moderate_coverage
coverage 0.15, no phase boost
recommendation == "moderate"
test_low_coverage_none
coverage 0.05
recommendation == "none"
test_zero_findings
all counts zero
recommendation == "none", coverage == 0
Test class: TestComputeLanes
Test
Input
Assertion
test_empty_actions
[]
Returns {}
test_single_auto_fix_lane
One auto_fix action
One "cleanup" lane
test_single_reorganize_lane
One reorganize action
One "restructure" lane
test_independent_refactor_lanes
Two refactor actions, disjoint file sets
Two separate lanes
test_overlapping_refactor_merged
Two refactor actions, shared file
One merged lane
test_test_coverage_always_independent
test_coverage + other refactor
Two lanes, test_coverage separate
test_cleanup_depends_on_nothing
auto_fix actions
depends_on == []
test_cascade_ordering
logs + unused auto_fix
logs action before unused in cleanup lane
test_automation_levels
Mix of auto_fix and manual
cleanup: "full", restructure: "manual"
test_debt_review_own_lane
debt_review action
Goes into "debt_review" lane
test_all_in_same_file
Multiple refactor detectors, all pointing to same file
All merged into one lane
Test class: TestComputeStrategy (integration-level)
Test
Input
Assertion
test_zero_findings_strategy
Empty findings
can_parallelize == False, hint mentions no findings
test_actions_annotated_with_lane
Multiple actions
Each action has a "lane" field
test_actions_annotated_with_detector
Multiple actions
Each action has a "detector" field
test_strategy_structure
Normal findings
Has keys: fixer_leverage, lanes, can_parallelize, hint
test_python_no_cleanup_lane
lang="python"
No "cleanup" lane in lanes dict
test_parallelizable_true
Two independent lanes
can_parallelize == True
test_parallelizable_false_single_lane
All findings same type
can_parallelize == False
Test class: TestStrategyHint
Test
Input
Assertion
test_strong_fixer_parallel
strong leverage, 2+ lanes
Hint mentions "fixers" and "parallel"
test_strong_fixer_single
strong leverage, 1 lane
Hint mentions "auto-fixers"
test_no_fixer_parallel
no fixers, 2+ lanes
Hint mentions "independent lanes"
test_maintenance_hint
phase="maintenance"
Hint mentions "maintenance"
test_fallback_hint
nothing special
Hint mentions top action
Existing test updates:
TestShowPostScanAnalysis.test_shows_top_action: should still pass (fallback path when strategy is not meaningful). May need to update the monkeypatched compute_narrative return to include "strategy": {}.
13. Implementation Sequence
Add FIXER_CASCADE and _DETECTOR_CASCADE constants to narrative.py
Add _open_files_by_detector function and its tests
Add "detector" field to all action dicts in _compute_actions (small change, 4 sites)
Add _compute_fixer_leverage function and its tests
Add _compute_lanes function and its tests
Add _compute_strategy_hint function and its tests
Add _compute_strategy orchestrator function and its integration tests
Wire _compute_strategy into compute_narrative return dict
Update _show_post_scan_analysis in scan.py for display
Update monkeypatched compute_narrative returns in test_cmd_scan.py to include strategy key
Sense-check: run python -m desloppify --lang python scan --path desloppify and python -m desloppify --lang typescript scan --path <ts-codebase>, inspect .desloppify/query.json to verify strategy output
14. Sense-Check Protocol
After implementation, run both scan commands and verify:
query.json has a strategy key with the expected structure
strategy.fixer_leverage.coverage is reasonable (should be 0 for Python self-scan, nonzero for TS)
strategy.lanes contain the expected lane names
strategy.can_parallelize reflects whether lanes are actually independent
strategy.hint is a coherent English sentence
Each action in actions has a "lane" field
Each action in actions has a "detector" field
Terminal output shows either strategy hint or fallback top-action as appropriate
No existing tests broken
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/narrative.py - All new functions added here: _open_files_by_detector, _compute_fixer_leverage, _compute_lanes, _compute_strategy_hint, _compute_strategy, constants FIXER_CASCADE and _DETECTOR_CASCADE. Also enriches _compute_actions with detector field and wires strategy into compute_narrative return.
/Users/user_c042661f/Documents/desloppify/tests/test_narrative.py - All new test classes: TestOpenFilesByDetector, TestFixerLeverage, TestComputeLanes, TestComputeStrategy, TestStrategyHint.
/Users/user_c042661f/Documents/desloppify/desloppify/commands/scan.py - Display integration in _show_post_scan_analysis to show strategy hint.
/Users/user_c042661f/Documents/desloppify/tests/test_cmd_scan.py - Update monkeypatched compute_narrative returns to include strategy key so existing tests pass.
/Users/user_c042661f/Documents/desloppify/desloppify/commands/fix_cmd.py - Reference only: source of truth for post_fix cascade hooks that FIXER_CASCADE is derived from.