Research these two schema drift issues in the desloppify codebase. For each, read the file around the indicated line and figure out what the "schema drift" problem is (likely using dict_keys or similar non-serializable type where a list/set is expected).
desloppify/app/commands/next/output.py around line 54
desloppify/engine/_work_queue/synthetic.py around line 239
For each file, read the relevant code and explain:
What exactly is the schema drift issue
What the fix should be
How complex the fix is
Thoroughness: medium
User
Research these three swallowed error issues in the desloppify codebase. For each, read the file around the indicated line and figure out what error is being swallowed (bare except, broad except with pass/continue, etc).
desloppify/app/commands/review/runner_parallel.py around line 131
desloppify/app/commands/scan/plan_reconcile.py around line 334
desloppify/engine/_work_queue/ranking.py around line 62
For each file, read the relevant code and explain:
What exception handling is swallowing the error
What the appropriate fix should be (log it, re-raise, narrow the except clause, etc)
How complex the fix is
Thoroughness: medium
Assistant
I'll read both files to identify the schema drift issues.
Assistant
I'll investigate these three swallowed error issues by reading each file and analyzing the exception handling around the indicated lines.
User
Research these four monster function issues in the desloppify codebase. Read each file and understand the function structure.
desloppify/app/cli_support/parser_groups_admin_review.py starting at line 8
desloppify/app/cli_support/parser_groups_plan_impl.py starting at line 8
desloppify/app/commands/review/batch/execution.py starting at line 44
desloppify/languages/typescript/phases.py at lines 219 and 424
For each, explain:
What the monster function does
How many lines it is
What logical sub-sections could be extracted
How complex/risky the decomposition would be
Thoroughness: very thorough
Assistant
I'll read each of these files to analyze the monster functions. Let me start by fetching all four files.
Assistant
Now let me analyze each of these functions in detail. Let me get the exact line counts and understand the structure better.
User
Research these 5 test debt issues in the desloppify codebase:
UNTESTED MODULES:
desloppify/app/commands/plan/triage/reflect_dashboard.py - read the module, understand what it does
desloppify/base/discovery/scan.py - read the module, understand what it does
OVER-MOCKED TESTS:
3. Test file for desloppify/app/commands/next/render.py - find and read test_next_render.py, understand what's over-mocked
4. Test file for desloppify/app/commands/plan/commit_log_handlers.py - find and read test_commit_log.py, understand what's over-mocked
5. Test file for desloppify/app/commands/scan/plan_reconcile.py - find and read test_plan_reconcile.py, understand what's over-mocked
For each, explain:
What the module/test does
What testing is missing or over-mocked
What kind of tests should be written/improved
How complex this work is
Thoroughness: very thorough
Assistant
I'll systematically research each of these test debt issues. Let me start by examining the untested modules and then the over-mocked tests.
User
Research the orphaned module issue for desloppify/base/discovery/scan.py.
Read the file to understand what it does
Search for any imports of this module across the codebase (grep for "from desloppify.base.discovery.scan" and "from desloppify.base.discovery import scan")
Search for any references to functions/classes defined in it
Check if there's a base/discovery/init.py that might re-export from it
Understand if this module is truly dead code or if it's used somewhere
Explain whether this should be deleted, wired in, or kept.
Thoroughness: very thorough
Assistant
Now let me read the test files:
Assistant
I'll conduct a thorough investigation of the orphaned module issue. Let me start by examining the file and then systematically search for all references to it.
Assistant
Looking at the code, I can now identify the schema drift issues in both files:
Issue 1: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next/output.py around line 54
The Problem:
There is no schema drift issue at line 54 itself. However, looking at the build_query_payload function (lines 115-135), there's a subtle issue at line 122:
python
member_ids = set(cluster.get("issue_ids", []))
The variable member_ids is assigned a set object, but then at line 126 it's used to compute a length:
python
"item_count": len(member_ids),
While this works (sets have len()), the issue is that member_ids is created as a set but the schema expects this data to be JSON-serializable. If member_ids were ever passed directly to json.dumps(), it would fail because sets are not JSON-serializable.
More critically, the real schema drift is that member_ids is a set, which is not JSON-serializable, so if any downstream code tried to serialize the intermediate member_ids variable or a dict containing it, it would fail.
Complexity: Very simple (1-2 line change) — just avoid creating the set if it's not needed, or convert it back to a list for serialization.
Issue 2: /Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/synthetic.py around line 239
User
Research how the desloppify exclude mechanism works:
Search for "exclude" in CLI commands (grep for "exclude" in desloppify/app/ and desloppify/cli.py)
Look at how exclusions are stored (check .desloppify/ directory config files)
Read the matches_exclusion function in base/file_paths.py
Understand what desloppify exclude .claude/worktrees would do
Thoroughness: quick
Assistant
Now let me examine the actual modules being tested to better understand what's happening:
Assistant
Now let me check if the discovery module itself exists and what its init.py contains:
Assistant
I'll quickly research the desloppify exclude mechanism by searching for exclude in CLI commands, checking config files, and reading the exclusion logic.
Assistant
Let me use a proper approach:
Assistant
Perfect! I've found all three files and identified the swallowed errors. Let me analyze each one:
OSError exceptions during file write operations are caught and only logged at DEBUG level
The execution continues silently without marking the payload write as failed or re-raising
Appropriate fix:
This is actually acceptable as-is. The code logs the error at debug level, which is appropriate for a non-critical file normalization operation. The payload is already validated, and failure to write the normalized version doesn't prevent further processing. If stricter handling is needed, you could:
Mark the batch as requiring regeneration on next run
Log at WARNING instead of DEBUG if this is important for auditability
Complexity: Very Low — if a change is needed, just change logger.debug to logger.warning
def reconcile_plan_post_scan(runtime: Any) -> None:
"""Reconcile plan queue metadata and stale subjective review dimensions."""
try:
# ... all the reconciliation logic (lines 292-333)
if dirty:
save_plan(plan, plan_path)
except PLAN_LOAD_EXCEPTIONS as exc:
logger.warning("Plan reconciliation skipped: %s", exc)
What's being swallowed:
The entire reconcile_plan_post_scan() function wraps all post-scan plan reconciliation in a broad try-except that catches
Assistant
Now let me look at the underlying source discovery module and check what helper functions are being used:
Assistant
Let me correct those paths:
Assistant
Good! Now let me check what the init.py exports and search for all imports of the scan module:
Assistant
Let me check the epic_triage module and also look at what tests exist for the modules:
Assistant
Let me find the correct file structure first:
Assistant
Good results! Let me examine these files to understand how scan.py is being used:
Assistant
Let me search for existing tests related to these modules more broadly:
Assistant
Great! Now I can read the exclude command and the file_paths.py:
Assistant
Now let me check the remaining files to see if any actually import from desloppify.base.discovery.scan:
Assistant
Now let me check the config module to understand how exclusions are stored:
Assistant
Let me check the structure of test directories more carefully and look at how discovery/scan.py is used:
Assistant
Let me check what imports reflect_dashboard and also look at more context around these modules:
Assistant
Let me check the remaining files and also do a more specific search:
Assistant
Now let me examine how the tests are structured and look at what patterns are used for mocking:
Assistant
Now let me do a comprehensive search for any reference to functions/classes that are actually defined in scan.py. Let me first check what's defined in scan.py more carefully:
Assistant
Perfect! Now let me get more context on what would be good integration tests by looking at other test patterns:
Assistant
Perfect! Now let me search for references to the specific functions exported by scan.py in the codebase:
Assistant
Great! Now let me check a few key files to see which ones import from base.discovery.scan vs base.discovery.source:
Assistant
Perfect! Now I have all the information I need. Let me compile my findings:
3. matches_exclusion() Function (base/discovery/file_paths.py)
This is the core matching logic (lines 13-32):
python
Assistant
Excellent! Now let me check if scan.py itself is imported anywhere:
Assistant
Perfect! None of those imports are from desloppify.base.discovery.scan. Let me now verify by checking the discovery init.py and source.py to understand the relationship:
Assistant
Perfect! Now let me do a final comprehensive check to see if anyone imports from desloppify.base.discovery.scan anywhere in the codebase:
Assistant
Perfect! Now let me verify the git history to understand when this module was created and if it was ever part of the public API:
Assistant
Let me check what happened in that rename commit:
Assistant
Good, so it was just a rename. Let me look at the previous commit to see if scan.py was ever part of the facade or public API:
Assistant
Excellent! The key finding is in that commit 2e221b4. Let me look at that commit more closely:
Assistant
Let me try a different approach:
Assistant
Let me check the actual file creation history more carefully:
Assistant
Now let me examine the TypeScript phases.py more carefully to identify the monster functions at lines 219 and 424.
Based on my thorough analysis of the four files, here is a comprehensive breakdown of each monster function:
1. _add_review_parser() in parser_groups_admin_review.py (lines 8–287)
What it does
Builds the complete argument parser for the desloppify review command by adding 6 nested argument groups with dozens of individual flags. It defines options for:
Post-processing group (lines 273–284): 11 lines — Merge and similarity threshold
Complexity & decomposition risk
Low-Medium Risk
Pros:
Each group is self-contained with no cross-dependencies
Simple pattern: g_* = p_review.add_argument_group(...) followed by .add_argument() calls
No business logic, purely declarative parser setup
Each function would be a straightforward ~30-60 line builder
Cons:
The function is a facade; it would multiply the number of public functions
Each extracted function would need a similar signature: (p_review) -> None
Risk: Maintainers might forget to call a new extracted function, breaking the parser
Recommendation: Extract into 5 small helper functions (, , , , ). Straightforward refactoring with minimal risk if extracted functions are in .
Assistant
Perfect! Now let me check what was importing from the old source_scan_api:
Assistant
Perfect! Now let me check what imports currently use base.discovery.scan to see if there's a public re-export somewhere:
Assistant
Now let me check what actually imports from scan.py in the cli.py (which was shown in the grep results):
Assistant
Let me read the cli.py directly:
Assistant
Excellent! I found it. The cli.py imports from desloppify.base.discovery.source, NOT from desloppify.base.discovery.scan. Let me do one more comprehensive check of all imports to verify scan.py is truly orphaned:
Assistant
Perfect! Let me also check if there's a public re-export in any init.py file:
Assistant
Let me verify the exact difference between scan.py and source.py to understand the relationship:
Assistant
Perfect! Now I have a complete picture. Let me create a comprehensive summary. First, let me also check if there are any references to scan.py in tests or documentation:
Assistant
Excellent! I can see from the agent runs that the issue was already under investigation. Let me check what was concluded:
Assistant
Perfect! Now I have the full context. Let me verify one more thing - whether source.py actually exports from __all__:
Assistant
Excellent! Now I have sufficient context. Let me create a comprehensive research report covering all 5 test debt issues:
TEST DEBT RESEARCH REPORT
Based on my thorough analysis of the desloppify codebase, here is the detailed research on the 5 test debt issues:
What the module does:
This is a small utility module (82 lines) containing 4 private functions that render the "reflect stage" dashboard display for the epic triage workflow:
_print_reflect_dashboard(si, plan) - Main orchestrator that displays completed clusters, resolved issues, and recurring patterns
_print_completed_clusters(completed) - Shows clusters completed in previous triage runs
_print_resolved_issues(resolved) - Shows issues that have been fixed since last triage
_print_recurring_patterns(open_issues, resolved) - Detects and displays dimensions with both resolved AND open issues (indicating potential recurring loops)
Current testing status:Zero tests - This module is completely untested. The function is actually used in display.py (line 426) in cmd_triage_dashboard(), but there are no dedicated tests.
What's missing:
No tests for the main _print_reflect_dashboard() function behavior
No tests for cluster completion display formatting
No tests for resolved issues filtering and display
No tests for detect_recurring_patterns() integration (called from epic_triage.py)
No tests for the "first triage" messaging path (when no prior work exists)
No edge case coverage: empty lists, None values, truncation at 10 items, etc.
What testing is needed:
Unit tests verifying each helper function's output formatting
Test _print_completed_clusters() with 0, 1, 5, and 11+ clusters (tests the truncation at 10)
Test _print_resolved_issues() with varying resolved counts and issue structures
Test _print_recurring_patterns() correctly detects dimensions with both resolved and open issues
Test colorization and formatting is applied correctly
Assistant
Perfect! Now I have all the information I need. Let me write a comprehensive report.
The file is a facade/wrapper layer that sits between callers and the actual implementation in source.py. It provides a canonical public API for source file discovery by:
Normalizing inputs (extensions and exclusion patterns) before delegation
Re-exporting functions from source.py with optional preprocessing
aliases.update(cli_keys)
aliases.update(slugify(key) for key in cli_keys)
Finally, at line 251 (within the detail dict being assigned to item), the aliases set is never directly serialized, but the real issue is at line 251 where cli_keys is used:
python
"cli_keys": cli_keys,
However, the more critical schema drift is that aliases is a set object used internally (lines 217-225) for set operations. While it's not directly serialized here, the pattern is problematic. The actual schema drift issue is that if this aliases variable were ever included in the JSON output, it would fail serialization.
Actually, looking more carefully: The real schema drift is that nothing appears to be explicitly wrong at line 239 in terms of what's shown. But examining the broader pattern, the code uses set() and set operations on aliases (lines 217, 223-224), which is fine internally, but this is a pattern that could lead to serialization issues if aliases were added to the output dict.
What the Fix Should Be:
If aliases needs to be serialized (which it currently doesn't), convert it to a list:
python
"aliases": list(aliases), # instead of "aliases": aliases,
But since aliases isn't currently in the output, the code is actually fine as-is for serialization purposes.
Complexity: The actual "drift" here is minimal/non-existent in current code. If this were meant to be included in the output, the fix would be trivial (wrap with list()).
Summary
next/output.py (line 122): Creating a set from issue_ids but not serializing it directly — low risk, but could be cleaner by just using the list directly or avoiding the set if it's only for len().
synthetic.py (line 217+): Using set for aliases for efficient lookups and updates, but it's never serialized to JSON — no actual schema drift issue in current code.
Neither file has a critical schema drift bug at the indicated lines, but the first one has a minor code smell (creating a non-serializable type unnecessarily).
PLAN_LOAD_EXCEPTIONS
If ANY error in the reconciliation pipeline occurs (whether loading, processing, or saving), it logs a warning and silently continues
The caller has no indication that reconciliation failed or was partial
Appropriate fix:
The broad exception handling loses context about which reconciliation step failed (apply, sync_unscored, sync_stale, auto_clusters, triage, communicate_score, create_plan, start_scores, or save)
Better approach: wrap individual high-risk operations (plan load/save) and let internal operations propagate errors, or use granular error context like:
python
try:
plan = load_plan(plan_path)
except PLAN_LOAD_EXCEPTIONS as exc:
logger.warning("Cannot load plan for reconciliation: %s", exc)
return
# ... all the sync operations without top-level catch
try:
save_plan(plan, plan_path)
except PLAN_LOAD_EXCEPTIONS as exc:
logger.warning("Failed to save reconciled plan: %s", exc)
Or add detailed logging before each major step so if it fails, the warning includes context
Complexity: Medium — requires refactoring the exception handling to provide better error attribution and granularity
def _workflow_stage_index(item: WorkQueueItem) -> int:
raw_index = item.get("stage_index")
if raw_index is not None:
try:
return int(raw_index)
except (TypeError, ValueError) as exc:
logger.debug("Invalid workflow stage index %r: %s", raw_index, exc)
return _TRIAGE_STAGE_ORDER.get(workflow_stage_name(item).lower(), 0)
What's being swallowed:
TypeError or ValueError from int(raw_index) conversion are caught and logged at DEBUG level
The function then falls back to deriving the index from the workflow stage name
Appropriate fix:
This is acceptable as-is. It's a defensive fallback pattern:
Tries the fast path (direct integer conversion)
Falls back to slower path (derive from stage name) if data is malformed
Logs at appropriate DEBUG level for troubleshooting
If you want to be stricter, you could:
Log at WARNING level instead of DEBUG
Validate stage_index is numeric when writing it to the queue
But this would be premature — the current pattern gracefully handles data inconsistencies
Complexity: Very Low — acceptable as-is, or minimal change if you want DEBUG→WARNING
Summary Table
File
Line
Issue
Severity
Fix Complexity
runner_parallel.py
131
DEBUG-only logging on OSError during payload write
Low
Very Low (if needed)
plan_reconcile.py
334
Broad try-except swallows all reconciliation errors without context
Medium
Medium (requires refactoring)
ranking.py
62
DEBUG-only logging on type/value errors with graceful fallback
Low
Very Low (if needed)
The primary concern is plan_reconcile.py, where the broad exception handler at the function level loses diagnostic information about which reconciliation step failed and why.
def matches_exclusion(rel_path: str, exclusion: str) -> bool:
"""Check if a relative path matches an exclusion pattern."""
parts = Path(rel_path).parts
# 1. Exact component match: ".claude/worktrees" matches ANY path containing it
if exclusion in parts:
return True
# 2. Wildcard patterns:
# - Per-component: "*.py" matches "foo.py" in any component
# - Full path: "foo/**" matches "foo/anything/deeper"
if "*" in exclusion:
if any(fnmatch.fnmatch(part, exclusion) for part in parts):
return True
if "/" in exclusion or os.sep in exclusion:
normalized_path = rel_path.lstrip("./")
if fnmatch.fnmatch(normalized_path, exclusion):
return True
# 3. Path prefix match: ".claude/worktrees" matches full path prefix
if "/" in exclusion or os.sep in exclusion:
normalized = exclusion.rstrip("/").rstrip(os.sep)
return rel_path == normalized or \
rel_path.startswith(normalized + "/") or \
rel_path.startswith(normalized + os.sep)
return False
4. What desloppify exclude .claude/worktrees Does
Adds the pattern.claude/worktrees to config["exclude"] in .desloppify/config.json
Marks for rescan: Sets needs_rescan = True
Immediately prunes state:
Finds all issues with file paths in .desloppify/worktrees/ (matches via matches_exclusion())
Removes them from state["issues"]
Saves the cleaned state file
Updates the plan: Removes those issue IDs from the living plan's queue, skips, and clusters
Displays progress: Shows how many issues were removed
Matching behavior for .claude/worktrees:
matches_exclusion("some/path", ".claude/worktrees") checks if the path starts with .claude/worktrees/ (prefix match via line 29-31)
Files like .claude/worktrees/decompositions/file.py ✓ matched
Files like .desloppify/worktrees/... ✗ NOT matched (different prefix)
5. Import Path in CLI
From cli.py lines 75-94:
CLI loads persisted exclusions from config
Calls set_exclusions(combined) in base/discovery/source.py to apply them globally before scanning
Prints which exclusions are active (from config or CLI flags)
This ensures all subsequent scans respect the exclusion list without needing to manually re-specify them each time.
_add_core_options()
_add_external_review_options()
_add_batch_execution_options()
_add_trust_options()
_add_postprocessing_options()
called explicitly
_add_review_parser()
2. add_plan_parser() in parser_groups_plan_impl.py (lines 8–366)
What it does
Builds the argument parser for the desloppify plan command and all of its subcommands. It defines 11 subparsers (show, queue, reset, reorder, describe, note, skip, unskip, reopen, resolve, focus, cluster, triage, commit-log) with their own nested options. Handles complex help text and examples.
_add_resolve_subparser() — resolve with attestation
_add_focus_subparser() — focus
_add_cluster_subparser() — cluster family (already complex due to nested structure)
_add_commit_log_subparser() — commit-log family
Already has the _add_triage_flags() pattern, so adding _add_*_subparser() functions would be consistent. Medium risk due to nested subparser dependencies.
3. do_run_batches() in execution.py (lines 44–549)
What it does
Orchestrates the entire batch execution workflow for the review command:
Validates runner and loads/prepares the batch packet
Sets up batch execution options (parallelization, timeouts, retries)
Builds and tracks batch tasks with a live progress callback
Executes batches (in parallel or serial) with heartbeat monitoring
Progress reporting is a self-contained closure that could move to a helper
Result collection and status mapping are distinct steps
Failure handling is modular
Cons:
Heavy state interdependence: Variables like batch_status, append_run_log, batch_positions, selected_indexes, run_dir, logs_dir, etc. are shared across many closures
The _report_progress() closure (145 lines) captures 20+ outer variables; extracting it would require passing many parameters
Import step (lines 516–536) has try/except for SystemExit and general Exception with different logging — can't easily extract
Function has 13 named dependencies injected as kwargs — each extracted function would need a subset of these
Runtime artifacts (paths, run_log writer, batch status dict) are mutated throughout; refactoring requires careful state threading
Recommendation:Extract with caution. Best candidates:
_build_progress_reporter() — Extract the _report_progress() closure into a standalone function that returns the closure. Signature: (batch_positions, selected_indexes, total_batches, append_run_log, colorize_fn, stall_warning_seconds) -> Callable. This reduces the monster function to ~360 lines.
Extracted functions would still need 5–10 parameters each. Feasibility: 6/10. The interconnected state and multiple closures make this risky without comprehensive refactoring.
4. phase_structural() in typescript/phases.py (lines 219–369)
What it does
Orchestrates structural analysis of TypeScript code by running 5 detector families and aggregating findings:
Large files detection
Complexity scoring with weighted signals
God component detection (excessive hooks)
Mixed concern detection
Flat directory detection
Prop interface bloat detection
Passthrough component detection
Returns merged signals into issues (using structural signal merging) plus flat dirs and props-specific issues.
Line count
150 lines (lines 219–369, excluding function signature/docstring)
Logical sub-sections that could be extracted
Large files (lines 224–232): 8 lines — Detect, add to structural dict
Complexity (lines 234–247): 13 lines — Detect with signals, store score in lang.complexity_map
Gods (lines 249–261): 12 lines — Detect god components, add to structural
Each detector (large, complexity, gods, concerns) is independent — could become helpers
Flat dirs, props, and passthrough are already independent blocks
Each creates issues from detector output following the same pattern
lang parameter is passed to most helpers; each extracted function could have signature (path, lang) -> list[Issue]
No cross-dependencies between sections
Cons:
The structural dict is built up across 4 sections (large, complexity, gods, concerns) then merged — can't extract those 4 independently without returning partial dicts
Return type is complex: (list[Issue], dict[str, int]) — extracted functions need consistent returns
lang.complexity_map and lang.zone_map are mutated; extracted functions would mutate outer state
Recommendation: Extract into logical phase sub-functions:
Most sections are independent: single-use, cycles, orphaned, facades, patterns, naming
Each follows a pattern: detect → filter → iterate → make_issue
Could extract 6–7 independent phase sub-functions
Cons:
Boundary candidates (lines 442–470) depends on single_entries from the single-use phase — can't extract independently
Result accumulation: All 7 detector branches results.extend() into a shared list — extraction requires consistent returns
Edge count aggregation (lines 569–570): coupling_edge_counts and cross_edge_counts are used in potentials calculation — must be returned from extracted functions
lang.zone_map is used heavily for filtering — mutates state indirectly through calls to filter_entries()
The _make_boundary_issues() helper already exists but is only called once — indicates this function is tightly coupled
Recommendation: Extract into phase blocks with shared dependencies:
Feasibility: 6/10. The boundary-candidates dependency on single-use and edge-count threading make this moderately complex, but doable. The existing _make_boundary_issues() helper shows the pattern is acceptable here.
Summary Table
Function
File
Lines
Extract Risk
Best Approach
_add_review_parser()
parser_groups_admin_review.py
280
Low
5 small helpers (~60 lines each)
add_plan_parser()
parser_groups_plan_impl.py
358
Medium
6–7 subparser builders (~50 lines each)
do_run_batches()
execution.py
505
High
Extract progress callback + import/merge blocks; heavy state sharing
All four are candidates for decomposition, but with varying difficulty. The parser builders are safest (low interdependence), while do_run_batches() has the highest risk due to shared closures and state mutations.
Integration tests with detect_recurring_patterns() from epic_triage.py
What the module does:
This is a thin facade module (118 lines) that acts as the canonical public API for source file discovery. It wraps the internal source.py module and provides:
Current testing status:Zero tests - This module has NO dedicated test coverage. The underlying source.py may have some tests, but the facade layer itself is untested.
What's missing:
No tests for the public API functions
No tests for normalization logic (pattern/extension deduplication)
No tests for the caching enable/disable lifecycle
No tests for path resolution with collect_exclude_dirs()
No tests for the multi-language file discovery functions (find_py_files, find_ts_files, find_tsx_files)
No edge case testing: empty paths, None values, duplicate patterns, malformed extensions
What testing is needed:
Unit tests for normalization:
_normalize_patterns() - test deduplication, empty/whitespace stripping, None handling
_normalize_extensions() - test . prefix addition, case normalization, deduplication
Integration tests with source.py:
Test find_source_files() returns correct file list
Test find_py_files() and find_ts_files() work with real temp directories
Test collect_exclude_dirs() respects exclusion patterns
Lifecycle tests for file caching:
Test enable/disable toggles the cache state correctly
What the module being tested does:render.py contains the terminal rendering helpers for the next command. It renders a single item or queue of items with scoring context, dimensions, and auto-fix suggestions. Functions include:
render_terminal_items() - Main orchestrator that routes to different renderers based on item kind
_render_item() - Full item card rendering with type, detail, code snippet, explain info
All rendering functions are mocked away - Tests only verify that the correct function is called, not that output is formatted correctly
colorize() is mocked to no-op - This hides whether color styles are applied correctly
_render_grouped, _render_item, _render_compact_item are mocked - These are the actual work functions, so testing only their invocation is shallow
No integration with render_support module - The render_support functions (render_grouped, render_compact_item) that do real work are completely bypassed
No code snippet rendering tested - read_code_snippet() is never called in tests
No dimension scoring tested - compute_health_breakdown() and compute_score_impact() are never invoked
What testing is missing:
Integration tests with actual render_support functions:
Test _render_grouped() actually groups items by detector/file correctly
Test _render_item() with realistic issue data shows all fields
Test cluster drill-in logic with real item filtering
Output correctness tests:
Verify color codes are applied to output
Verify item labels ("Next item", "[#1/5]", etc.) are formatted correctly
Verify single vs multi-item rendering differences
Field rendering tests:
Test dimension context is printed correctly
Test impact estimates are calculated and displayed
Test auto-fix batch hints show correct count
Test code snippets are retrieved and formatted
Test explain mode adds explanation footer
Edge cases:
Items with missing fields (no detector, no file, no detail)
Confidence levels (high/medium/low)
Review dimension vs regular detector items
Subjective dimension items
Workflow stage/action items
How complex is this work?Complexity: Medium-High (4-6 hours)
Need to create realistic item data structures matching actual state.json issue format
Tests should use real render_support functions, not mock them
Need to capture and verify printed output using capsys
Need to mock external dependencies (render_support imports, read_code_snippet) at a deeper level
Should test integration with scoring functions (compute_health_breakdown, compute_score_impact)
Consider adding parametrized tests for different item kinds (cluster, workflow_stage, workflow_action, regular issue, review, subjective_dimension)
Test pattern to follow:
Similar to test_scan_reporting_direct.py which tests actual output content with capsys.readouterr().out verification and realistic data structures.
No workflow injection tested - Tests never verify that triage/create-plan workflow items are added
No dimension syncing tested - Unscored and stale dimension logic is never exercised
No score seeding tested - Plan start scores are never actually set
No error handling tested - Exception swallowing is tested, but not error logging
What testing is missing:
Plan reconciliation tests:
Test superseded issues are removed from queue_order
Test superseded issues move to plan["superseded"]
Test issue cluster refs are cleared for superseded issues
Dimension syncing tests:
Test unscored subjective dimensions are injected into queue
Test stale dimensions are removed from queue after review period
Test newly stale dimensions are injected
Auto-clustering tests:
Test clusters are regenerated based on current state
Test cluster issue_ids are updated post-scan
Workflow injection tests:
Test "triage::needed" workflow is injected when review issues change
Test "workflow::create-plan" is injected when reviews complete
Test "workflow::communicate-score" is injected conditionally
Score seeding tests:
Test plan_start_scores is set on first queue cycle
Test plan_start_scores is cleared when queue empties
Test scores use correct snapshot format (strict, overall, objective, verified)
Integration tests:
Test full reconciliation flow with realistic plan and state data
Test plan is saved only when dirty flag is True
Test all syncs run in correct order
Test changes are captured in plan log entries
Edge cases:
Plan load failures are caught and logged, not re-raised
Plan has no user content (empty queue_order, no clusters)
State has no scoring data available
How complex is this work?Complexity: High (6-8 hours)
This module orchestrates a complex multi-step process with many interdependencies
Tests need realistic plan and state data structures matching actual schema
Each sync function has its own complex logic that needs testing:
_apply_plan_reconciliation() - needs plan with queue_order, overrides, clusters
_sync_stale_and_log() - needs subjective dimensions with review state
_sync_auto_clusters_and_log() - needs logic to understand auto-clustering
_seed_plan_start_scores() - needs state with scoring data
Currently, each sync function is mocked, but they should be tested in isolation AND in integration
Should follow the pattern of test_reconcile.py which tests actual state mutations
May need to create helper fixtures for building realistic plan and state structures
Consider testing with just 2-3 sync functions at a time rather than mocking all 10+
Test pattern to follow:
The test_reconcile.py file has excellent patterns for testing plan reconciliation:
python
def _plan_with_queue(*ids: str) -> dict:
plan = empty_plan()
plan["queue_order"] = list(ids)
return plan
def _state_with_issues(*ids: str, status: str = "open") -> dict:
issues = {}
for fid in ids:
issues[fid] = {...}
return {"issues": issues, "scan_count": 5}
# Then test the actual mutation:
result = reconcile_plan_after_scan(plan, state)
assert "a" in result.superseded # Verify actual state changed
SUMMARY TABLE
Issue
Type
Module
Lines
Status
Complexity
Est. Hours
1
Untested
reflect_dashboard.py
82
0 tests
Low-Med
2-3
2
Untested
scan.py
118
0 tests
Medium
3-5
3
Over-mocked
test_next_render.py
3 tests
Tests routing only
Med-High
4-6
4
Over-mocked
test_commit_log.py
3 tests
Tests calls only
Med-High
5-7
5
Over-mocked
test_plan_reconcile.py
3 tests
Tests save decision only
High
6-8
Total estimated effort: 20-29 hours of work
Priority recommendation:
First: Issue #5 (plan_reconcile) - Most critical, orchestrates complex workflow
Second: Issue #4 (commit_log) - Important user-facing feature
Third: Issue #3 (next_render) - Affects user experience with output quality
Fourth: Issue #2 (scan.py) - Infrastructure, medium importance
from desloppify.base.discovery.source import find_source_files
76+ other files import from source.py directly
Not exposed in the base/discovery module's public API:
/desloppify/base/discovery/__init__.py is empty (only 2 lines)
No re-exports of scan.py or its functions
Functionally redundant:
Both scan.py and source.py export identical function signatures in __all__
scan.py only adds input normalization (lowercase extensions, strip whitespace)
But callers bypass this normalization by importing directly from source.py
Historical Context
From commit 2e221b4 (F6 directory reorganization):
The original file was desloppify/core/source_scan_api.py (a standalone facade)
It was moved to desloppify/core/discovery/scan.py as part of module reorganization
Then renamed again to base/discovery/scan.py in commit 2f0d9c2
The issue is explicitly documented in a prior analysis run (20260304_033501):
"Parallel discovery APIs create behavior drift and inconsistent call-site dependencies"
"scan.py is a facade that normalizes extension/pattern inputs before delegation, but source.py exposes direct find_source_files without that normalization path, yielding different behavior depending on import path... generic.py imports find_source_files from base.discovery.source, bypassing the canonical normalization layer."
Recommendation
DELETE desloppify/base/discovery/scan.py
Reasoning:
Zero active imports — no code depends on it
Behavior bypass — the normalization it provides is ignored because callers import from source.py directly
Fits CLAUDE.md policy — "Remove re-export facades, wrapper shims, and compatibility layers that exist solely so old import paths keep working"
Unifies the API — eliminates the dual-entrypoint confusion documented in the agent analysis
No migration burden — there are no callers to update
Post-deletion verification:
All existing imports from base.discovery.source will continue working unchanged
The normalization functions in scan.py were never used by real callers anyway
Tests (76 files mention find_*_files functions) all use the functions via source.py
Alternative (NOT recommended):
If there's concern about the normalization being useful:
Merge the normalization logic into source.py's find_source_files() directly
Update source.py's __all__ and imports
Then delete scan.py
But this is unnecessary since the normalization is currently bypassed everywhere.