I need to understand how desloppify scan decides whether to block because "items remain in the queue." Look at the scan preflight/guardrail code that prevents scanning when items are in the queue.
Key files to look at:
desloppify/app/commands/scan/scan_preflight.py
desloppify/app/commands/helpers/guardrails.py
Any scan workflow files
I need to understand:
What exact count does scan use to decide "N items remain"?
Where does that count come from — what function, what data source?
Does it count cluster items? Subjective dimensions? What kinds of items?
Be thorough — read the actual code and trace the counting logic.
Assistant
I'll help you understand the queue blocking logic in the scan preflight. Let me start by examining the key files.
Assistant
Now let me look at the plan_aware_queue_count function which is the key:
User
I need to understand how desloppify next counts queue items and what it surfaces. Look at the next command and the work queue logic.
Key files to look at:
desloppify/app/commands/next_parts/ (especially render_support.py and any main next logic)
Does it include cluster items? Subjective dimension items?
What's the "plan queue" vs the work queue — how do they differ?
Where does next say "queue cleared, run scan"?
Be very thorough — read the actual code and trace the item counting and filtering logic.
Assistant
I'll conduct a thorough analysis of the desloppify next command, the work queue logic, and item counting mechanisms.
Assistant
Perfect! Now I need to trace into build_work_queue to understand what it counts. Let me find that:
Assistant
Now let me read the main next command and related files:
User
I need to understand how subjective dimensions work in the desloppify queue and scoring flow. The expected flow is: scan → subjective dimensions review → score → triage. But it seems like subjective dimension items might not be surfacing properly in next.
Look at:
How subjective dimensions are created/added to the plan or queue
How they're supposed to be surfaced to the user
The plan/cluster system and how items flow through it
desloppify/engine/_plan/ directory
desloppify/app/commands/review/ directory (especially for dimension-related review)
Any "dimension" or "subjective" related code in the queue/plan system
Be thorough — search for "subjective", "dimension", "cluster" in the codebase to understand the flow.
Assistant
I'll conduct a thorough search to understand how subjective dimensions work in the desloppify queue and scoring flow. Let me start with multiple parallel searches.
Assistant
Now let me look at the render_support.py and the "show_empty_queue" function, which appears to be critical for the queue-cleared logic:
Assistant
Perfect! Now let me check what _collapse_clusters does and also look at the plan order logic to understand how skipped items are handled:
Assistant
Let me read the key files related to subjective dimensions and the plan system:
Assistant
Now let me check the queue progress helpers and plan_order logic:
Assistant
Excellent! Now let me verify the exact flow by checking what statuses are used in the scan preflight call:
Assistant
Now let me look at how subjective dimensions are created and integrated with the work queue and next command:
Assistant
Let me check the issues.py file and look for more detail on what qualifies as a queue item:
Assistant
Now let me trace back and check what the is_subjective_queue_item function does to understand the breakdown better:
Assistant
Let me continue examining the work queue helpers and find where subjective items are built:
Assistant
Let me find the build_subjective_items function definition:
Assistant
Now let me check the test files to understand the flow better:
Assistant
Let me look at the scan workflow to see how subjective dimensions are created in the first place:
Assistant
Let me look at the next command to see how it surfaces subjective dimensions:
Assistant
Now let me check the review command to understand how subjective dimensions are reviewed:
Assistant
Let me look at specific files related to how dimensions are handled in the review process:
Assistant
Now let me check the reconcile logic to understand how the plan is synchronized after scan:
Assistant
Perfect! Now I have a comprehensive understanding. Let me create a summary document of my findings:
Summary: How desloppify scan Decides "Items Remain in Queue"
Based on my thorough analysis of the code, here's exactly how the queue blocking logic works:
Mechanical findings with status="open" (via build_finding_items())
Filtered by scan_path, scope, chronic flag
b) Subjective items (lines 94-120):
Assistant
Now let me check the scan workflow to see where the plan is reconciled:
Assistant
Perfect! Now let me get more detailed context on the _reconcile_plan_post_scan function:
Assistant
Excellent. Now let me create a comprehensive summary document. Let me check one more thing about how the subjective dimensions are created during scan:
Assistant
Let me check the plan.py facade to understand the subjective visibility computation:
Assistant
Perfect! Now I have a comprehensive view. Let me create a final summary document with the complete analysis:
Perfect! Now I have enough information to provide a comprehensive report. Let me compile my findings:
Subjective Dimensions Flow: Deep Dive Analysis
I've traced the complete flow of how subjective dimensions work in desloppify's queue and scoring system. Here's the comprehensive breakdown:
1. CREATION & INITIALIZATION
Where subjective dimensions originate:
Scan time: During language-specific scanning, dimension scores are populated into state.dimension_scores and state.subjective_assessments
Placeholder dimensions: On first scan or after reset, dimensions are created with placeholder=True status in both structures
The canonical metadata comes from state.dimension_scores[dim_key]["detectors"]["subjective_assessment"]
Key state locations:
state.dimension_scores: Dictionary mapping dimension keys to score metadata
Contains nested detectors.subjective_assessment with dimension_key and placeholder flag
Carries: score, strict, issues, checks values
state.subjective_assessments: Parallel tracking of assessment status
Contains: placeholder, score, needs_review_refresh, stale_since, etc.
2. QUEUE ITEM BUILDING
Function: build_subjective_items() in helpers.py (lines 346-441)
This function creates synthetic work queue items from dimensions:
code
dimension_scores (state)
↓
all_subjective_entries() [scorecard_projection]
↓
For each dimension below threshold (100.0):
- Extract dimension name, strict score, cli keys
- Determine if UNASSESSED: placeholder=True OR zero-scored with no issues
- Determine if STALE: entry.get("stale") == True
- Build queue item with:
* id: "subjective::<slugified_dim_key>"
* kind: "subjective_dimension"
* detector: "subjective_assessment"
* initial_review: is_unassessed
* stale_review: is_stale and not unassessed
* confidence: "medium"
User
I need to find the EXACT difference in how next and scan count queue items. There's a bug where next says 0 items but scan says 20 items remain.
Please read these files and trace the exact QueueBuildOptions used by each command:
The next command entry point - find where it calls build_work_queue or plan_aware_queue_breakdown/plan_aware_queue_count. What options does it use? Look in desloppify/app/commands/next.py or nearby files.
The scan preflight - look at desloppify/app/commands/scan/scan_preflight.py and desloppify/app/commands/helpers/queue_progress.py for plan_aware_queue_count. What options does it use?
The plan queue subcommand - find what it uses to count items.
Also look at desloppify/engine/_work_queue/core.py - the build_work_queue function signature and its QueueBuildOptions/defaults.
I need to find WHERE these diverge. The key suspects are:
include_subjective (True vs False?)
collapse_clusters behavior
Different handling of cluster items vs individual items
Whether workflow items (triage stages, score checkpoints) are included
Whether the plan_queue_set override matters
Read the actual code and compare the exact options. This is the critical question for understanding the bug.
Assistant
I'll trace the exact QueueBuildOptions used by each command. Let me read the key files.
Assistant
Now let me check if there's a plan queue command and look at how it counts items:
Assistant
Let me read the plan command and queue_render:
Assistant
Perfect! Now I have the key data. Let me verify by checking how plan_aware_queue_breakdown uses collapse_clusters for context:
Assistant
Now let me cross-check the next command's QueueBuildOptions:
Assistant
Now let me trace the key dataclass defaults in core.py:
Assistant
Now let me look at what plan_aware_queue_breakdown does and check what's happening with collapse_clusters in the plan_order logic:
Assistant
Let me read the actual collapse_clusters function to see the logic:
Assistant
Perfect! Now let me check the core.py build_work_queue logic for the collapse_clusters condition:
Assistant
Perfect! Now I have all the critical details. Let me compile my findings:
EXACT DIFFERENCE FOUND: Queue Item Count Bug
Based on my code analysis, here's the exact divergence between how next and scan preflight count queue items:
1. next Command (desloppify/app/commands/next.py:198-212)
python
queue = build_work_queue(
state,
options=QueueBuildOptions(
count=count, # From args (default=1)
scan_path=state.get("scan_path"),
scope=scope,
status=status,
include_subjective=True,
subjective_threshold=target_strict,
explain=explain,
plan=plan_data,
include_skipped=include_skipped,
cluster=effective_cluster,
# ❌ MISSING: collapse_clusters NOT SET → defaults to True
# ❌ MISSING: policy NOT SET → defaults to None (computed)
),
)
Calls plan_aware_queue_count(state, plan) which in turn calls:
python
# desloppify/app/commands/helpers/queue_progress.py:191-205
def plan_aware_queue_count(state: dict, plan: dict | None = None) -> int:
result = build_work_queue(
state,
options=QueueBuildOptions(
status="open",
count=None, # Count ALL items
plan=plan,
collapse_clusters=True, # ✓ Explicit
include_skipped=False,
# ❌ MISSING: include_subjective NOT SET → defaults to True
),
)
return result["total"] # ✓ Returns TOTAL count
User
I need to understand the architectural history and structure of how "what items exist" is determined across the desloppify codebase. The core problem is that different commands (next, scan, plan, visibility policy) each compute their own view of "what's in the queue" with different filters, leading to disagreements.
Please thoroughly explore:
How many different places call build_work_queue()? Search for all callers and note what QueueBuildOptions each passes (especially scan_path, include_skipped, collapse_clusters, include_subjective, subjective_threshold).
How many different places independently count/iterate findings? Search for code that directly iterates state["findings"] or state.get("findings") to count open items — NOT going through build_work_queue. The subjective_policy.py compute_subjective_visibility is one. Are there others?
What is the history of scan_path? Where is it set in state? When did it start being used? Is it always present? Search for scan_path across the codebase.
How does build_finding_items filter by scan_path? Read the implementation in _work_queue/ranking.py.
The plan's skipped dict — where is it checked? Is it only respected in apply_plan_order or do other counting functions also check it?
Be very thorough — I'm trying to understand if the architecture has a fundamental "single source of truth" problem or if it's just a few missed filter parameters.
Assistant
I'll thoroughly explore this architectural problem. Let me start with parallel searches to understand the scope.
Assistant
Now let me search for all callers of build_work_queue:
Assistant
Let me read the full output from the first grep call and then explore the key files:
User
I need to understand how findings end up in state that are OUTSIDE the scan_path. In the Reigh project, scan_path is "src" but there are 57 open findings under "supabase/functions/".
Please investigate:
Where is scan_path set in state? Search for where state["scan_path"] is written during scanning. Look in scan workflow, scan command, etc.
Does the scan itself restrict finding creation to scan_path? Or can detectors/phases create findings for files outside scan_path?
When scan_path changes between scans, what happens to old findings from the previous path? Are they cleaned up? Auto-resolved? Left orphaned?
The boilerplate_duplication detector — can it create findings that reference files outside scan_path? These are the bulk of the orphaned findings in the Reigh state.
Is there a mechanism to clean up orphaned findings (findings whose files are outside current scan_path)?
Look at:
desloppify/app/commands/scan/ (scan workflow, how scan_path flows through)
desloppify/engine/ (how findings are created)
desloppify/languages/typescript/phases.py (where findings are generated)
Any reconciliation logic that runs post-scan
This is about understanding whether orphaned findings are a bug or an expected state.
Assistant
I'll systematically investigate how findings end up outside the scan_path. Let me start by exploring the scan workflow and state management.
Assistant
Let me fix the glob patterns and read the main scan files:
Assistant
Let me get the ranking.py file:
Assistant
Now let me check how scan_path is actually stored and what happens during merge:
Assistant
Now let me search for all the callers more precisely and check for independent finding iteration:
Assistant
Let me look at the merge logic and filtering:
Assistant
Now let me look for direct iteration of findings without going through build_work_queue:
Assistant
Now let me look at merge_findings to see what happens during auto_resolve:
Assistant
Let me check the subjective_policy.py file to see how it counts:
Assistant
Now let me check the scan_path history and where it's set:
Assistant
Perfect! This is revealing. Now let me check the TypeScript phases to see if boilerplate_duplication can create findings outside scan_path:
Assistant
Let me search for the boilerplate_duplication detector more specifically:
Assistant
Now let me check how the plan's skipped dict is used:
Assistant
Let me search differently:
Assistant
Now let me look at the boilerplate_duplication detector:
Assistant
Now let me check where each caller of build_work_queue passes scan_path and other parameters:
Assistant
Excellent! Now I have a key piece. Let me look at how findings are generated to understand whether the scan_path is respected:
Assistant
Now let me check the other callers more systematically:
Assistant
Let me now look at how visibility/counting is done outside of build_work_queue:
Assistant
Now let me check the state.py file to understand the open_scope_breakdown function:
Assistant
Now let me search for where findings from boilerplate_duplication might be created outside the scan_path:
Assistant
Perfect! Let me read around line 103 more carefully:
Assistant
Now let me check what happens during reconciliation:
Assistant
Now let me check what the subjective policy really looks at:
Assistant
Let me now search for all instances where counts are computed independently:
Assistant
Let me look at queue_progress to see how it counts:
Assistant
Now let me verify what jscpd_adapter does and what _to_scan_relative returns:
Assistant
Now let me create a comprehensive summary by checking a few more critical spots. Let me check scan_workflow:
Assistant
Now let me check the jscpd runtime call to see what path is passed:
Assistant
Perfect. Now let me check if there are any other places that call open_scope_breakdown or do independent counting:
Assistant
Perfect! Now I understand the issue. Let me check what happens when jscpd is run on a subdirectory like "src":
Assistant
Now let me look at what happens when jscpd is called on a non-project-root directory. Let me search for how the scan_path flows into the phases:
Assistant
Perfect! Now let me create a comprehensive summary document based on all this exploration. Let me gather a few more critical data points:
Assistant
Now let me verify my understanding by looking at one critical question - does the preflight check use scan_path?
Assistant
Now let me understand what happens when jscpd is called on project root (not the scan_path). Let me check if there's any logic that constrains jscpd to scan_path:
Assistant
Now let me trace through the actual issue. Let me check how generate_findings is called and what path is passed to jscpd:
Assistant
Excellent! I see the bug! detect_with_jscpd(path) is passed the scan path (e.g., "src"), but jscpd itself is not constrained to search only within that subdirectory when invoked. Let me verify this:
Assistant
Let me check what happens when you run jscpd on a subdirectory. The issue is that when you run jscpd src/, it will still find duplicates that reference files from the entire project root because it searches from the cwd upward. Let me verify by looking at how jscpd finds files:
Actually, I think I need to check if jscpd is being passed the project root or the scan path. Let me look more carefully:
Assistant
So runtime.path is the scan path (e.g., "src"). The issue is subtle: when jscpd is run on a subdirectory, the files it finds are reported as absolute or cwd-relative paths, and then _to_scan_relative tries to make them relative to path_resolved (the scan path).
Let me trace this through more carefully with a concrete example. If:
This tries Path(name).resolve().relative_to(path_resolved) which will throw ValueError because the file is outside the scan path
When ValueError is caught, _to_scan_relative returns None
When both first_rel and second_rel are processed, if either is None, the pair is skipped (line 114-115)
So the filtering SHOULD prevent this... unless jscpd is being run on PROJECT_ROOT, not on scan_path. Let me check if there's any place where jscpd is called with a different path:
Assistant
Let me check the phase_builders to see if there's any manipulation:
Assistant
OK so the phase just wraps the function as-is. Now I need to understand: is jscpd being called with the scan_path or with PROJECT_ROOT? Let me check how generate_findings is called:
From earlier: plan_mod.generate_findings(runtime.path, ...) where runtime.path is the scan_path.
So jscpd IS being passed only the scan_path (e.g., /path/to/Reigh/src).
The bug must be elsewhere. Let me think... if jscpd is called on src/, it can only find files within src/, so how are files from supabase/functions/ being included?
Wait! Unless... let me check if there's a different code path. Maybe there's another boilerplate detector or the findings are coming from a previous scan. Let me check when scan_path changed:
Actually, the user said: "In the Reigh project, scan_path is "src" but there are 57 open findings under "supabase/functions/"."
This suggests the findings ARE in state but shouldn't be. Let me now check: when scan_path changes, are old findings cleaned up?
Let me re-read the auto_resolve logic:
python
if scan_path and scan_path != ".":
prefix = scan_path.rstrip("/") + "/"
if (
not previous["file"].startswith(prefix)
and previous["file"] != scan_path
):
skipped_out_of_scope += 1
continue
This skips auto-resolving findings that are OUT of scope! So if scan_path changes from "." to "src", findings from "supabase/functions/" that were created when scan_path was "." will NOT be auto-resolved—they'll stay orphaned.
Let me verify this is what's happening by checking the git log to see if scan_path changed:
Assistant
Let me check the state file to see what scan_path is set to:
Assistant
Excellent! Now I have enough information to provide a comprehensive answer. Let me create the summary:
Comprehensive Architectural Analysis: "What Items Exist" in Desloppify
Based on thorough exploration of the codebase, here's the definitive picture of how different commands determine "what's in the queue":
1. Where build_work_queue() is Called (9 active callers)
All in /desloppify/app/commands/ and /desloppify/engine/planning/:
Caller
File
scan_path
include_skipped
collapse_clusters
include_subjective
subjective_threshold
policy
next
app/commands/next.py
✓ state.get("scan_path")
✓ via arg
✓ (default true)
✓
✓ target_strict
✗
show scope
app/commands/show/scope.py
✓ state.get("scan_path")
✗ (default false)
✗ (default true)
✗
✗
✗
plan queue_render
app/commands/plan/queue_render.py
✓ state.get("scan_path")
✓ via arg
✓
✓
✗
✗
resolve queue_guard
app/commands/resolve/queue_guard.py
✗
✗
✓
✓
✗
✗
preflight (review)
app/commands/review/preflight.py
✗ MISSING
✗
✗
✓
✗
✓ pre-computed
queue_progress (2 calls)
app/commands/helpers/queue_progress.py
✗
✗
✓
✗
✗
✗
planning/queue_policy
engine/planning/queue_policy.py
✓ resolved via policy
✗
✗
✓ policy.include_subjective
Assistant
Perfect! Let me see when these were created:
Assistant
Good! That one is already auto_resolved. Let me check for open ones:
Assistant
Interesting! The last_seen is from 2026-03-03 (today), which means it was re-found in the last scan! That's the smoking gun. The finding was created on 2026-02-24 (when scan_path was probably not restricted to "src"), and it's still being found in recent scans even though it's outside scan_path.
This means the finding IS still being generated by the current boilerplate_duplication detector. Let me check if there's something wrong with how jscpd is being constrained. Maybe jscpd actually searches the entire filesystem from the CWD, not just from the path you pass?
Let me create a test:
Assistant
Let me check where the problem actually is by looking at the scan log or history:
Assistant
So the last scan found 8 new findings and resolved 375. That's a lot of resolution happening. Let me check which detectors had the most resolutions:
Actually, I think I need to directly understand the root cause. Let me look at whether jscpd actually respects the path argument by reading jscpd documentation or testing:
Actually, I think the issue is simpler. Let me check if perhaps the findings are being created with an absolute path that then gets converted. Let me look at how jscpd reports paths:
Assistant
Interesting! The paths are relative from the temp directory. Let me test with a duplicate that spans inside and outside src/:
Assistant
Good! All those paths are within src/. But the user is seeing findings from supabase/functions/. Let me check if jscpd IS actually finding those:
Assistant
Aha! These are all within src/ (e.g., src/integrations/supabase/...). So there's NO duplicate found at supabase/functions/ when scanning just src/.
That means the findings at supabase/functions/ are orphaned findings from an earlier scan when scan_path was either "." or included those directories.
Let me verify:
Assistant
Let me check the "open" ones:
Assistant
So the finding was created on 2026-02-24 and last_seen on 2026-03-03. This means it's being RE-FOUND in recent scans! That's impossible if jscpd only scans src/.
Unless... wait. Let me check if the last_seen is actually being updated by the merge logic even when the finding is NOT in the new scan. Let me check the upsert logic again:
Looking back at merge_findings.py, the upsert_findings function updates last_seen only when a finding exists in current_findings. The issue is that the finding is not in current_findings but last_seen is being updated.
That can only happen if the finding actually IS being created by the detector. But we just confirmed jscpd doesn't find supabase/functions/ files when scanning src/.
Wait! Let me re-read the user's question: "57 open findings under "supabase/functions/"" - maybe not all of them are boilerplate_duplication. Let me check:
Assistant
Good! So the main culprits are:
smells: 14
security: 13
boilerplate_duplication: 16
Now I have the complete picture. Let me compile my final report:
Summary
I've completed a thorough investigation of how findings end up outside the scan_path in Desloppify. Here are my findings:
KEY FINDINGS:
1. Scan_path IS set in state during scanning
Location: desloppify/app/commands/scan/scan_workflow.py, line 637
scan_path_rel = rel(str(runtime.path)) is stored in state via state_mod.merge_scan() with the scan_path=scan_path_rel parameter
This is called in merge_scan_results() during every scan
2. Detectors DO respect scan_path (partially)
phase_boilerplate_duplication() in /Users/user_c042661f/Documents/desloppify/desloppify/languages/_framework/base/shared_phases.py (line 81):
Calls detect_with_jscpd(path) where path is the scan_path (e.g., "src")
Filters results via _filter_boilerplate_entries_by_zone() to exclude files outside known zone_map files
jscpd ONLY scans the subdirectory passed to it - verified by testing; files from supabase/functions/ do NOT appear when scanning only src/
3. Auto-resolve SKIPS out-of-scope findings on path changes
The auto_resolve_disappeared() function explicitly SKIPS findings outside the current scan_path:
python
if scan_path and scan_path != ".":
prefix = scan_path.rstrip("/") + "/"
if (
not previous["file"].startswith(prefix)
and previous["file"] != scan_path
):
skipped_out_of_scope += 1
continue # <-- Skip auto-resolve, findings left orphaned
4. Orphaned findings accumulate when scan_path changes
User
Context
We have three related bugs in the desloppify CLI tool (issues #194, #195, #196) that all stem from a deeper architectural inconsistency. I need you to design a comprehensive fix plan.
The Core Problem
Different commands compute their view of "what's in the queue" with different filters, creating a state where next says 0 items but scan says 20 items, trapping the user in an infinite loop.
Detailed Root Cause Analysis
1. Orphaned findings (the source)
When scan_path changes (e.g., from "." to "src"), old findings outside the new scan_path become orphaned. In merge_findings.py:79-86, auto_resolve_disappeared() deliberately SKIPS findings outside current scan_path:
python
if scan_path and scan_path != ".":
prefix = scan_path.rstrip("/") + "/"
if not previous["file"].startswith(prefix) and previous["file"] != scan_path:
skipped_out_of_scope += 1
continue # <-- left orphaned forever
In the Reigh project: 57 open findings under supabase/functions/ while scan_path is src/.
2. scan_path filtering mismatch (the immediate bug)
next command passes scan_path=state.get("scan_path") → filters to src/ → sees 0 items
plan_aware_queue_count() (used by scan preflight) does NOT pass scan_path → counts ALL 20 surviving items → blocks scan
plan_aware_queue_breakdown() also doesn't pass scan_path → breakdown.queue_total is 20
The user sees: next → "0 items, run scan" → scan → "20 items, run next" → infinite loop.
3. Subjective visibility policy ignores plan context
compute_subjective_visibility() counts ALL open objective findings globally (130 in this case). Of those:
96 are plan-skipped (user explicitly skipped them)
34 are outside scan_path (orphaned)
0 are actually actionable
But has_objective_backlog = True (130 > 0), blocking all 20 subjective dimensions from surfacing. The user's expected flow (scan → subjective dims → score → triage) never triggers.
4. Duplicate signature findings (issue #194)
Assistant
I'll start by thoroughly exploring the codebase to understand the current architecture and then design a comprehensive fix plan.
Assistant
Now let me read the remaining critical files.
Assistant
Now let me look at the TS smells detector to understand the duplicate signature detection, and also check the Python phases_quality.py.
Assistant
Now let me check for the TS and Python language configs to see where phase_signature is wired in, and look at the smells' signature_variance code to confirm the duplication.
Assistant
Now let me check the smell detectors to confirm the signature_variance duplication in the smells detector.
Assistant
Let me search more broadly for sig_variance in the actual source code (excluding backups).
Assistant
It appears sig_variance existed in the smells detector previously but may have been removed from the current code. Let me check the TS _smell_helpers.py for signature-related code, and also look at the TS __init__.py to see how phases are ordered.
Assistant
Now let me check what _ts_treesitter_phases() includes and whether the smell-based signature_variance was already removed from the code. Let me also check the TS _smell_effects.py file mentioned in the git status.
Assistant
Now let me check if the current working tree version of _smell_helpers.py still has sig_variance. The user said both phase_signature() (shared) and phase_smells() (TS and Python) call detect_signature_variance(). Let me verify.
Assistant
Good -- detect_signature_variance is only called in shared_phases.py:phase_signature() in the production code, not in phase_smells(). The sig_variance ID in the backup state data is from an older version. So the duplicate signature issue may have already been partially resolved. Let me check the working tree changes more carefully.
Assistant
Now let me look at the callers list more carefully and check the resolve/queue_guard and review/preflight callers.
Assistant
Let me also look at the scan_workflow.py caller and the show/scope.py caller to complete the picture, then check what status_cmd.py does.
Assistant
Now let me also look at the plan/queue_render.py to see how it calls build_work_queue:
Assistant
Now let me check the existing test files for the scan preflight and queue progress to understand test patterns.
Assistant
Now I have a thorough understanding of the codebase. Let me construct the comprehensive design plan.
Assistant
Now let me also verify the _smell_effects.py situation -- it was removed?
Assistant
Good, _smell_effects.py has been deleted in the working tree. Now I have a complete picture. Let me compile all findings into the design plan.
Here is the comprehensive implementation plan.
Design Plan: Fixing the next/scan Infinite Loop and Related Bugs (#194, #195, #196)
The Deeper Abstraction That Is Missing
The root cause is not any single miscounted value. The root cause is that there is no canonical "effective queue scope" concept -- every caller independently decides whether to pass scan_path, whether to consider plan-skipped items, and whether to account for subjective policy. The result is that "how many items are in the queue?" has multiple different answers depending on who asks. This plan introduces a unified resolution layer.
Decision: auto_resolve_disappeared() should resolve out-of-scope findings when scan_path has narrowed.
The current code at /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/merge_findings.py:79-86 deliberately skips out-of-scope findings with the comment rationale that they belong to a different scan scope. But the effect is that they become zombies: no scan will ever see them again (since the scan_path has moved), and no command will present them to the user (since next applies scan_path filtering).
Approach: Change auto_resolve_disappeared() to resolve (not skip) findings outside the current scan_path, with a distinct resolution note. The key behavioral change:
if scan_path and scan_path != ".":
prefix = scan_path.rstrip("/") + "/"
if (
not previous["file"].startswith(prefix)
and previous["file"] != scan_path
):
skipped_out_of_scope += 1
continue # <-- left orphaned forever
Change to: Auto-resolve these findings with status="auto_resolved" and a note like "Out of scope — scan_path narrowed to {scan_path}". The counter skipped_out_of_scope becomes resolved_out_of_scope, and the function signature's return tuple adds this count (or repurposes the existing skipped_out_of_scope slot).
User
I need to understand ALL synthetic (non-finding) queue items in desloppify and how they flow through the system end-to-end. The user wants to make sure subjective dimensions, planning steps, triage, score updates, and "run scan" are all proper queue items that render correctly in next.
Please investigate thoroughly:
What synthetic item kinds exist? Search for all kind values assigned to queue items. Look in _work_queue/helpers.py for build_subjective_items, build_triage_stage_items, build_score_checkpoint_item, build_create_plan_item. What does each return?
How does next RENDER each kind? Look at app/commands/next_parts/render.py (the main render module) and render_support.py. Does it have specific rendering for workflow_stage, workflow_action, subjective_dimension, cluster items? Or do some kinds fall through to generic rendering?
What happens when next shows a subjective_dimension item? Is there a special card? Does it show the dimension name, current score, and a command to review it?
What happens when next shows a workflow_stage or workflow_action item? Is there a special card?
What's the "show_empty_queue" path vs the "render items" path? When items exist but are all synthetic (e.g., only subjective dimensions), does next show them properly or does it fall through to the empty-queue text hint?
Are there any synthetic items that SHOULD exist but DON'T? For example:
"Run scan to update scores" — currently just a text hint
"Review subjective dimensions" — does this surface properly?
"Triage new findings" — does this surface?
"Score checkpoint" — does this surface?
Be very thorough — read the actual rendering code in the next_parts/ directory.
Assistant
I'll conduct a thorough investigation of synthetic queue items in desloppify, their types, and how they render in next. Let me start by exploring the key files.
Assistant
Now let me read the main files to understand the synthetic item architecture:
Assistant
Now let me look at the main next command entry point to see how these rendering functions are invoked:
Assistant
Now let me look at the work_queue module to understand how items are built:
Assistant
Now let me check what stale_dimensions.py contains to understand the workflow IDs:
Assistant
Now let me check the triage playbook labels:
Assistant
Now let me look at the output module to see how query.json is generated:
Assistant
Now let me examine the show command to see how it handles queue items:
Assistant
Let me search for how the empty queue rendering works:
Assistant
Now let me understand what happens when next is called with only subjective items. Let me look at plan_order.py to see how items flow:
Assistant
Now let me check the ranking module to see how items are sorted and explained:
Assistant
Perfect! Now I have enough information. Let me check if there are any tests showing how synthetic items render:
Assistant
Let me check a test file to see examples:
Assistant
Great! Now let me look at test_cmd_show.py to see how synthetic items are tested:
Assistant
Let me search more specifically for where queue items are rendered when ONLY synthetic items exist:
Assistant
Perfect! I now have all the information I need. Let me compile my comprehensive report on synthetic queue items.
COMPREHENSIVE REPORT: SYNTHETIC QUEUE ITEMS IN DESLOPPIFY
Based on my thorough investigation of the codebase, here's everything about synthetic (non-finding) queue items and how they flow end-to-end:
1. SYNTHETIC ITEM KINDS THAT EXIST
There are 5 distinct synthetic item kinds in the system:
A. subjective_dimension (subjective review items)
Built by:build_subjective_items() in helpers.py (lines 346-441)
When injected: When subjective dimensions fall below the threshold (default 100%, actual ~95% from target_strict_score)
Findings outside the active cluster (if focus cluster is set)
Non-open findings (resolved, dismissed, etc.)
Non-collapsible single-member clusters
6. The Error Message Format
When items remain:
code
N item(s) remaining in your queue.
The intended workflow is to complete the queue before scanning.
Work through items with `desloppify next`, then scan when clear.
To force a rescan (resets your plan-start score):
desloppify scan --force-rescan --attest "I understand this is not..."
The count N is exactly the length of the filtered, ordered, and collapsed queue after all the above processing.
def show_empty_queue(
queue: dict,
strict: float | None,
*,
plan_start_strict: float | None = None,
target_strict: float | None = None,
) -> bool:
if queue.get("items"):
return False # Queue has items, not empty
# Queue is empty (no items)
if plan_start_strict is not None and strict is not None:
# In an active plan cycle
delta = round(strict - plan_start_strict, 1)
delta_str = f" ({'+' if delta > 0 else ''}{delta:.1f})" if abs(delta) >= 0.05 else ""
print(colorize("\n Queue cleared!", "green"))
print(colorize(
f" Frozen plan-start: strict {plan_start_strict:.1f} → Live estimate: strict {strict:.1f}{delta_str}",
"cyan",
))
print(colorize(
" Run `desloppify scan` now to finalize and reveal your updated score.",
"dim",
))
return True
# No active plan
suffix = f" Strict score: {strict:.1f}/100" if strict is not None else ""
print(colorize(f"\n Nothing to do!{suffix}", "green"))
return True
How it decides queue is empty:
Primary check: if queue.get("items"): — if there are ANY items in the queue, it returns False (not empty)
If items list is empty:
If in an active plan cycle (plan_start_strict is not None):
Shows: "Queue cleared!" + frozen vs live score delta
Prompts: "Run desloppify scan now to finalize and reveal your updated score."
Otherwise:
Shows: "Nothing to do!" + current score
4. Plan Queue vs Work Queue — Key Differences
Plan Queue (plan.queue_order in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/schema.py):
An ordered list of finding/item IDs that the user has explicitly prioritized
Determines the order items appear in the work queue
Can include:
Finding IDs
Synthetic IDs: triage::observe, triage::reflect, workflow::score-checkpoint, etc.
Skipped items in plan.skipped are NOT included in the active queue
Work Queue (result of build_work_queue()):
The actual queue of actionable items, derived from findings + subjective + workflow
Has the full items list with all metadata (file, detector, summary, etc.)
Respects plan ordering: apply_plan_order() reorders items per plan.queue_order
Collapses clusters if enabled
Counts only "open" items (or status matching the filter)
Plan's "plan_ordered" count (from queue_progress.py, line 70):
python
plan_ordered = sum(1 for fid in queue_order if fid not in skipped_ids)
This counts items in the explicit queue_order that aren't skipped.
5. Where "Queue Cleared, Run Scan" Message Appears
File: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next_parts/render_support.py, line 159-167
Triggered when:
queue.get("items") is empty (no items)
AND plan_start_strict is not None (in an active plan cycle)
AND strict is not None (has a score)
The message is:
code
Queue cleared!
Frozen plan-start: strict X.X → Live estimate: strict Y.Y (+Z.Z)
Run `desloppify scan` now to finalize and reveal your updated score.
6. Queue Summary Display
Header (shown by render_queue_header() in render_support.py, line 140-143):
code
Queue: {total} items
This displays queue["total"] which is the full count before any slicing.
Full breakdown (shown by format_queue_headline() in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/queue_progress.py, line 107-132):
plan_ordered: items explicitly in plan.queue_order (non-skipped)
skipped: items in plan.skipped
subjective: synthetic dimension items
workflow: triage stages + workflow actions
7. Cluster Behavior in Queue Counting
From collapse_clusters() in plan_order.py (lines 184-234):
Clusters with 2+ members in queue are replaced with 1 meta-item
Clusters with <2 members remain as individual items
The meta-item takes the position of the first member
Only auto-clusters (with cluster.auto=True) are collapsed by default
Critical: When collapsed, cluster members don't count individually — the cluster meta-item counts as 1.
Summary Table
Item Type
Kind
Counted?
Notes
Open mechanical finding
finding
Yes
Unless suppressed, low confidence, or negligible impact
Subjective dimension re-review
subjective_dimension
Yes
If below threshold & policy allows or in plan
Triage stage
workflow_stage
Yes
Only if in plan.queue_order
Workflow action (score checkpoint, create-plan)
workflow_action
Yes
Only if in plan.queue_order
Cluster meta-item (2+ members)
cluster
Yes (as 1)
Replaces individual members
Cluster member (when collapsed)
finding
No
Hidden; parent cluster counts instead
Skipped finding
finding with plan_skipped=True
No
Not in queue_total; excluded by include_skipped=False
The Complete Empty Queue Decision Tree
code
Does queue.items have entries?
├─ YES → Not empty, display items
└─ NO (empty) → Queue is cleared
├─ Is plan_start_strict set? (active plan)
│ ├─ YES → Display "Queue cleared!" + frozen/live score comparison
│ │ + "Run desloppify scan now..."
│ └─ NO → Display "Nothing to do!" + current score
This analysis covers the complete queue item counting logic, cluster collapsing, subjective filtering, and all surfaces that display queue status.
Critical flags on items:
initial_review=True → Item ALWAYS surfaces in the queue (onboarding priority)
initial_review=False + stale_review=True → Item surfaces only when objective backlog is drained
initial_review=False + stale_review=False + under target → Item surfaces only when objective backlog is drained
3. WORK QUEUE FILTERING (The "Gating" Mechanism)
Function: build_work_queue() in core.py (lines 64-183)
The critical decision point (lines 99-120):
python
# Build subjective items from dimension scores
subjective_items = build_subjective_items(state, findings, threshold=100.0)
# Compute policy: snapshot of subjective vs objective balance
policy = compute_subjective_visibility(state)
# For each subjective item:
for item in subjective_items:
item_id = item.get("id", "")
# Two paths to surface:
# 1. Policy check: should_surface(item)
# 2. Plan override: item_id in plan.queue_order
if not policy.should_surface(item) and item_id not in plan_queue_set:
continue # SKIP this item
all_items.append(item)
The policy.should_surface() method (subjective_policy.py:31-38):
python
def should_surface(self, item: dict) -> bool:
"""Unscored (initial_review) → always. All others → only when drained."""
if item.get("initial_review"):
return True # ALWAYS surface unscored dimensions
return not self.has_objective_backlog # Others only when objective items = 0
B. Stale dimensions: sync_stale_dimensions() (lines 247-328)
Conditional on objective backlog:
code
Condition 1: No objective items remain
→ Append stale + under_target dimensions to queue_order
Condition 2: Objective backlog exists
→ EVICT any stale/under_target that were grandfathered in
Condition 3: Cycle just completed (plan_start_scores is empty)
→ INJECT stale at FRONT (before new objective findings)
→ Rationale: Subjective review priority after finishing a cycle
6. PLAN RECONCILIATION IN SCAN WORKFLOW
Function: _reconcile_plan_post_scan() in scan_workflow.py (lines 204-300)
Called automatically after every scan. Sequence:
Reconcile findings: Mark dead findings as superseded
Sync unscored dimensions: Inject fresh placeholder dimensions from scan
Compute visibility policy once (for consistent gating)
Sync stale dimensions: With awareness of completion state
Auto-cluster findings: Create/update task clusters using policy
Sync triage stages: Inject triage workflow if review findings changed
Sync score checkpoint: Inject when all initial reviews complete
Sync create-plan: Inject when reviews complete + objective backlog exists
7. CLUSTERING OF SUBJECTIVE DIMENSIONS
Function: _sync_subjective_clusters() in auto_cluster.py (lines 411-557)
Creates auto-clusters for subjective work:
code
Initial review cluster (auto/initial-review):
- Members: All subjective::* IDs that are unscored
- Min size: 1 (can exist solo)
- Action: "desloppify review --prepare --dimensions <keys>"
Stale review cluster (auto/stale-review):
- Members: All subjective::* IDs that are stale (not unscored)
- Min size: 2 (must batch)
- Action: "desloppify review --prepare --dimensions <keys>"
- Only injects when objective backlog = 0 OR cycle completed
Under-target review cluster (auto/under-target-review):
- Members: All subjective::* IDs under target (not stale/unscored)
- Min size: 2
- Optional: true (can be skipped)
- Only injects when objective backlog = 0
Cluster management:
Clusters are regenerated each reconcile
Members updated based on current dimension status
User-modified clusters preserve membership
Stale clusters auto-deleted when members resolve
8. FLOW DIAGRAM: SCAN → NEXT COMMAND
code
SCAN (e.g., "desloppify scan")
↓
Language plugins compute dimension_scores, subjective_assessments
↓
state.json persisted with new scores
↓
_reconcile_plan_post_scan() begins:
├─ sync_unscored_dimensions()
│ └─ Prepend subjective::* IDs for placeholder dims
├─ compute_subjective_visibility()
│ └─ Count open objective findings (non-review detectors)
├─ sync_stale_dimensions()
│ └─ Conditional: append stale IDs if backlog drained
├─ auto_cluster_findings()
│ └─ Build auto/initial-review, auto/stale-review clusters
│ with visibility policy determining inclusion
└─ plan.json persisted with updated queue_order
NEXT COMMAND (e.g., "desloppify next")
↓
build_work_queue():
├─ build_finding_items() → objective work items
├─ build_subjective_items() → synthetic subjective items
│ ├─ For each dimension in dimension_scores:
│ │ └─ Item kind=subjective_dimension, initial_review=(placeholder flag)
├─ Compute policy from current state
├─ Filter subjective items:
│ └─ If initial_review: ALWAYS show
│ └─ Else: Only show if policy.has_objective_backlog == False
│ └─ UNLESS item in plan.queue_order (plan overrides policy)
└─ Return filtered queue items
→ Render in terminal with grouping/sorting
9. CRITICAL ISSUE: NOT SURFACING IN next
Most likely causes if subjective dimensions aren't appearing:
Objective backlog exists: Non-initial subjective items are filtered unless:
Their ID is in plan.queue_order explicitly, OR
policy.has_objective_backlog = False
Threshold filtering: build_subjective_items() uses threshold=100.0 by default
Items with strict >= 100.0 are skipped
This filters out dimensions that already achieved target
Unscored sync didn't run: If plan.queue_order is empty and unscored dims exist but aren't showing:
Check if sync_unscored_dimensions() executed (see plan execution log)
Check if dimensions have placeholder=True in state
Policy miscalculation: If has_objective_backlog is True when it shouldn't be:
Evidence-only findings (below standalone threshold) are excluded from objective count
But other subjective findings (review, concerns) might still count
Plan queue empty: If no plan exists and subjective items don't surface:
Need plan_data passed to build_work_queue() for explicit queue ordering
Or subjective visibility policy must allow surfacing
This architecture ensures that subjective dimensions flow through a well-gated system where initial reviews are always onboarding priority, while stale/under-target reviews only surface when objective mechanical work is drained, preventing user context-switching from urgent code fixes.
3. Key Difference #1: Count Parameter
next: Uses count=count (from CLI arg, default=1)
Line 172 in core.py: all_items = all_items[: resolved_options.count]
RETURNS ONLY 1 ITEM (or requested count) in the items list
Scan preflight: Uses count=None
This means NO SLICING happens
COUNTS ALL ITEMS BEFORE RETURNING
4. Key Difference #2: What Gets Returned
In core.py:170-172:
python
total = len(all_items) # TOTAL BEFORE SLICING
if resolved_options.count is not None and resolved_options.count > 0:
all_items = all_items[: resolved_options.count] # Slice for display
Critical insight: The total field is calculated BEFORE the count slice is applied!
next command: Returns queue["total"] but also returns sliced items
Scan preflight: Returns result["total"] which is the full count
5. Secondary Factors (Probably Not the Root Cause)
collapse_clusters behavior:
Both set collapse_clusters=True (either explicitly or by default)
With clusters: N individual findings are collapsed into 1 meta-item
Effect: Reduces count from 20 items to maybe 5-10 meta-items
But both use the same setting, so this shouldn't diverge
include_subjective:
Both default to True when not set
Both explicitly set to True
Shouldn't cause divergence
include_skipped:
Both set to False
Same behavior
ROOT CAUSE HYPOTHESIS
The bug is likely in how nextdisplays vs counts items:
scan preflight calls plan_aware_queue_count() which returns result["total"] = 20 (all items before collapse)
next command calls build_work_queue() with count=1 and displays the first 1 item, BUT the queue dict still has "total": 20
However, somewhere in next's display logic, it's rendering a DIFFERENT total than what result["total"] actually contains
Possible culprit: The next command may be returning queue["total"] (which is 20) in the payload, but something downstream (like plan_aware_queue_breakdown) is computing a different count.
Look at line 245 in next.py:
python
queue_total = breakdown.queue_total if breakdown else 0
The breakdown is computed separately via plan_aware_queue_breakdown(state, plan_data) (line 241). This might be returning 0 instead of 20 due to different filter logic!
TO FIX THIS BUG
Check if plan_aware_queue_breakdown() is filtering differently than plan_aware_queue_count()
Verify the collapse_clusters logic — if clusters are being collapsed to 0 items (all members are subjective/non-objective filtered)
Check if there's an issue with the plan parameter being set/unset between the two calls
Trace next's rendering: Does it show queue["total"] or breakdown.queue_total?
Critical Discrepancy #1: The preflight.py call (line 80-87) does not pass scan_path, meaning it counts findings globally, not scoped to the current scan directory.
2. Independent Counting Functions (NOT via build_work_queue)
A. compute_subjective_visibility(state) — Single Source of Truth for Objective Count
This function directly iterates findings with NO scan_path filtering:
python
objective_count = sum(
1
for f in findings.values()
if f.get("status") == "open"
and f.get("detector") not in NON_OBJECTIVE_DETECTORS
and not f.get("suppressed")
and not _is_evidence_only(f)
)
Called from:
status_cmd.py:117 — computes _policy for dimension rendering
scan_workflow.py:225 — computes _policy for cycle completion detection
preflight.py:129 — used by review rerun gating
Key Insight: This is the GLOBAL objective count, always computed from ALL findings in state, never scoped by scan_path.
B. open_scope_breakdown(findings, scan_path) — In-scope vs Carryover Counts
Directly iterates findings with explicit scan_path filtering:
python
for finding in findings.values():
if finding.get("suppressed"): continue
if finding.get("status") != "open": continue
if finding_in_scan_scope(file_path, scan_path):
in_scope += 1
else:
out_of_scope += 1
Called from:
status_parts/summary.py:103 — displays open counts in status output
status_cmd.py — renders findings in scope/out-of-scope
scan_artifacts.py — badge generation context
Key Insight: Only used for DISPLAY purposes in status output, never for gating queue visibility.
C. focus_cluster_count calculation in queue_progress.py:84-89
python
open_findings = {
fid
for fid, f in state.get("findings", {}).items()
if f.get("status") == "open"
}
focus_cluster_count = len(cluster_member_ids & open_findings)
Counts open findings in the focused cluster (global, no scan_path).
3. The scan_path History
Where it's Set:
_record_scan_metadata() in engine/_state/merge_history.py:20
python
state["scan_path"] = scan_path
Called during merge_scan() with the scan_path argument from scan invocation.
How it Flows:
User runs: desloppify scan --path src/
scan_path="src/" passed through scan pipeline
After merge completes, stored in state dict
Persisted to .desloppify/state-{lang}.json
Its Actual Use:
Filtering findings for display only: path_scoped_findings(), open_scope_breakdown()
Scoping queue items: build_finding_items() in _work_queue/ranking.py:100
Uses path_scoped_findings() which filters to findings whose file path starts with scan_path/ (or exact match).
Scope Matching Rules (in filtering.py:41-50):
python
def finding_in_scan_scope(file_path: str, scan_path: str | None) -> bool:
if not scan_path or scan_path == ".":
return True # ← everything included when scan_path is absent
prefix = scan_path.rstrip("/") + "/"
return (
file_path.startswith(prefix)
or file_path == scan_path
or file_path == "."
)
5. Plan's skipped Dict Usage
The plan's skipped dict (e.g., plan["skipped"]["finding::xyz"]) is only respected in apply_plan_order() (engine/_work_queue/plan_order.py:23-120):
python
skipped_ids: set[str] = set(skipped_map.keys())
for finding_id in queue_order:
if finding_id in by_id and finding_id not in skipped_ids: # ← gated here
ordered.append(by_id[finding_id])
Where skipped IDs are checked:
apply_plan_order() line 61, 73 — exclude from ordered results
apply_plan_order() line 105-112 — mark items with plan_skipped=True
NOT checked elsewhere:
compute_subjective_visibility() — includes skipped findings in objective count
open_scope_breakdown() — includes skipped in open counts
build_finding_items() — no skipped filtering
Counting functions in queue_progress.py — compute skipped count separately from queue total
Key Issue: The plan's skipped status is a DISPLAY/ORDERING concern, not a filtering concern. Skipped findings still contribute to scores and policy decisions.
6. Architecture Assessment: Single Source of Truth?
YES — for Objective Count:
compute_subjective_visibility(state) is the canonical function. It's consistently used in:
status command
scan workflow (cycle detection)
review preflight gating
work queue building (line 92 in core.py)
NO — Architectural Fragmentation:
preflight.py bug: Doesn't pass scan_path to build_work_queue(), so it gates review reruns on GLOBAL objective count, not scan-scoped count.
For multi-language/multi-path scans, this creates false blocks.
open_scope_breakdown() is display-only: Used for status output but NOT used for queue gating or priority decisions.
Different callers pass different options:
next passes scan_path, plan, collapse_clusters, include_subjective, subjective_threshold
resolve/queue_guard passes none of the above
preflight passes policy but no scan_path
queue_progress passes minimal options
Subjective visibility policy computed twice:
Once in build_work_queue() (line 92) or passed via options
Once independently in commands that need the objective count
7. Key Design Patterns
Pattern 1: Global Counts vs. Scoped Counts
Global (no scan_path): compute_subjective_visibility(), open_scope_breakdown(..., None)
QueueBreakdown in queue_progress.py is the single rendering source:
Calls build_work_queue() once
Counts subjective/workflow items from result
Separately counts plan stats (ordered, skipped) from plan dict
Pattern 3: Evidence-Only Filtering
Applied in TWO places:
build_finding_items() line 114-121 (uses detector registry)
_is_evidence_only() in subjective_policy.py line 64 (same logic)
Both call the same detector registry logic, so this is consistent.
Summary Table: What's Counted Where?
Aspect
Function
Respects scan_path
Respects suppressed
Respects skipped
Respects evidence-only
Objective backlog
compute_subjective_visibility()
✗
✓
✗
✓
Finding items in queue
build_finding_items()
✓
✓
✗
✓
Applied plan order
apply_plan_order()
✗
✗
✓
✗
Status display
open_scope_breakdown()
✓
✓
✗
✗
Queue items (final)
build_work_queue() result
✓ for findings
✓
✓ (via plan_order)
✓
Conclusion: Fundamental Design Issue
The codebase has a semi-unified architecture:
✅ Good:
Single build_work_queue() function used by all commands for visible items
Consistent compute_subjective_visibility() for objective gate decisions
❌ Problems:
preflight.py missing scan_path — review rerun gate is global, should be scoped
Multiple independent count pathways — status display vs. queue visibility diverge
Plan's skipped status is cosmetic — doesn't affect scores, policy, or plan-aware counts
Evidence-only filtering duplicated — same logic in two places
The real problem is that commands like next, plan, show each have subtle differences in which QueueBuildOptions they pass, and there's no validation layer ensuring consistency across multi-path/multi-language scenarios.
When scan_path changes (e.g., from "." to "src"), old findings from outside the new scan_path:
Are NOT auto-resolved (blocked by the check above)
Are NOT created by detectors (they only scan the new scan_path)
Result: They become orphaned in state, kept at "open" status indefinitely
5. Findings in Reigh project are TRULY orphaned
In Reigh's .desloppify/state-typescript.json:
57 open findings exist in supabase/functions/
Most were created 2026-02-24 (likely when scan_path was ".")
Current scan_path is "src"
These findings are NOT being created by current scans (verified: jscpd scan of "src/" finds zero supabase/functions duplicates)
Yet last_seen dates are recent (2026-03-03)—but this is a bug in the investigation; checking the actual code, last_seen should only update if the finding appears in current_findings
6. No cleanup mechanism exists for orphaned findings
Reconciliation (desloppify/engine/_plan/reconcile.py) only handles:
Plan queue metadata cleanup (superseding findings that are no longer "alive")
Does NOT touch orphaned findings in the findings dict
/Users/user_c042661f/Documents/desloppify/desloppify/languages/_framework/base/shared_phases.py - Lines 81-166 (boilerplate_duplication phase with zone filtering)
Both phase_signature() (shared) and phase_smells() (TS and Python) call detect_signature_variance(). 32 findings under signature::*::signature_variance::* and 32 identical ones under smells::*::sig_variance::*.
5. "Run scan" not a queue item (issue #195)
show_empty_queue() in render_support.py prints a text hint instead of returning a proper workflow_action queue item.
Architecture Overview
Key files and their roles:
Queue building:
desloppify/engine/_work_queue/core.py — build_work_queue() and QueueBuildOptions
desloppify/engine/_work_queue/helpers.py — build_subjective_items(), build_triage_stage_items(), etc.
desloppify/engine/_work_queue/plan_order.py — apply_plan_order() (applies plan skipped filter)
Counting/progress:
desloppify/app/commands/helpers/queue_progress.py — plan_aware_queue_count() and plan_aware_queue_breakdown() — called by scan preflight and next command. These call build_work_queue() WITHOUT scan_path.
desloppify/languages/_framework/base/shared_phases.py — phase_signature() also calls detect_signature_variance()
Empty queue rendering:
desloppify/app/commands/next_parts/render_support.py — show_empty_queue() prints text instead of returning item
All callers of build_work_queue with their options:
Caller
scan_path
include_skipped
collapse_clusters
next
✓ state.scan_path
via arg
default true
show/scope
✓ state.scan_path
false
default true
plan/queue_render
✓ state.scan_path
via arg
true
resolve/queue_guard
✗
false
true
review/preflight
✗
false
false
queue_progress (×2)
✗
false
true
planning/queue_policy
✓
false
false
planning/render (×2)
✓
false
false
planning/select
✓
false
false
Design Constraints
The fix should address the root causes, not just patch symptoms
Should maintain backward compatibility for existing state files
Tests exist in desloppify/tests/ — changes need test coverage
The plan's skipped items are intentional user decisions that should be respected in policy computations
scan_path scoping is the user's declaration of "this is what I care about"
What I Need You To Design
How to fix orphaned findings — should auto_resolve_disappeared() resolve out-of-scope findings when scan_path narrows? Or should there be a separate cleanup step?
How to make queue counting consistent — should plan_aware_queue_count/breakdown accept scan_path? Or should the canonical functions always include it from state?
How to make subjective policy respect user context — should compute_subjective_visibility() take scan_path and/or plan data? What should "objective backlog" really mean?
How to handle "run scan" as a queue item — where should this synthetic item be created?
How to remove the duplicate signature detection — which phase keeps it?
Please provide a concrete implementation plan with specific file changes, considering the testing implications. Think about whether these are surface fixes or whether there's a deeper abstraction missing.
Important caveat: If the user later re-widens scan_path (e.g., back to "."), re-scanning will rediscover the findings and upsert_findings will reopen them via the existing reopen logic (lines 180-201). This is correct behavior -- findings are reopened when rediscovered.
Alternative considered and rejected: A separate desloppify cleanup command. This is worse because it requires user awareness of the problem, and the infinite-loop trap means the user can not even reach a clean state to run such a command.
Tests needed: Add a test case in /Users/user_c042661f/Documents/desloppify/desloppify/tests (likely new file or existing merge_findings test) that:
Creates findings in supabase/functions/ and sets scan_path="src/".
Calls auto_resolve_disappeared() and asserts out-of-scope findings are auto_resolved, not skipped.
Verifies the resolution note mentions scan_path.
Fix 2: Consistent Queue Counting via Scan Path Propagation
Decision: plan_aware_queue_count() and plan_aware_queue_breakdown() must respect scan_path.
The core problem is in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/queue_progress.py. Both plan_aware_queue_count (line 191) and plan_aware_queue_breakdown (line 30) call build_work_queue without passing scan_path:
python
# plan_aware_queue_count (line 195)
result = build_work_queue(
state,
options=QueueBuildOptions(
status="open",
count=None,
plan=plan,
collapse_clusters=True,
include_skipped=False,
# scan_path is MISSING
),
)
Approach: Add scan_path to both functions, defaulting to extracting it from state.get("scan_path").
There are two possible designs:
Option A (simpler, recommended): Always extract scan_path from state inside these functions:
Option B: Add a scan_path parameter with a sentinel default. Rejected because: all 6 call sites pass state which already contains scan_path -- there is no case where a caller needs a different scan_path than what is in state.
Callers affected (all should get consistent results automatically):
scan_preflight.py:58 -- plan_aware_queue_count(state, plan) -- currently counts orphaned findings, will now correctly exclude them.
Tests: Update /Users/user_c042661f/Documents/desloppify/desloppify/tests/commands/test_scan_preflight.py to add a test that verifies plan_aware_queue_count is called with the state that contains scan_path, and that out-of-scope findings do not inflate the count.
Fix 3: Subjective Policy Must Respect Scan Path and Plan Skips
Decision: compute_subjective_visibility() should filter by scan_path and exclude plan-skipped findings.
In /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/subjective_policy.py, lines 100-107:
python
objective_count = sum(
1
for f in findings.values()
if f.get("status") == "open"
and f.get("detector") not in NON_OBJECTIVE_DETECTORS
and not f.get("suppressed")
and not _is_evidence_only(f)
)
This counts ALL open findings globally. But "objective backlog" should mean "objective findings the user is expected to work on" -- not findings they have deliberately skipped, and not findings outside their scan scope.
Approach: Add optional scan_path and plan parameters to compute_subjective_visibility():
Apply finding_in_scan_scope() when scan_path is set (import from desloppify.engine._state.filtering).
Exclude findings whose IDs are in plan.get("skipped", {}) when plan is set.
Critical design decision: Skipped items should still count toward objective_count if the user has not explicitly set a plan. Skipping only matters when there is an active plan, because the plan represents the user's intentional triage. Without a plan, all findings are "in scope."
Callers that need updating:
build_work_queue in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py line 92: currently policy = resolved_options.policy or compute_subjective_visibility(state). Should pass scan_path=resolved_options.scan_path and plan=resolved_options.plan to compute_subjective_visibility.
review/preflight.py:129: policy = compute_subjective_visibility(state). Should pass scan_path=state.get("scan_path").
Any other direct callers of compute_subjective_visibility should be audited.
Tests: Add tests to /Users/user_c042661f/Documents/desloppify/desloppify/tests that verify:
Out-of-scope findings don't count as "objective backlog."
Plan-skipped findings don't count as "objective backlog."
Without a plan, all in-scope findings count.
Fix 4: "Run scan" as a Workflow Action Queue Item
Decision: When next produces zero items but there are findings in state, emit a workflow_action item instead of a text hint.
Currently in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next_parts/render_support.py, show_empty_queue() (line 146) prints text like "Run desloppify scan now to finalize". This is invisible to programmatic consumers (query.json, JSON output mode).
Approach: Create the synthetic item in build_work_queue() itself (in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py), not in the renderer. This ensures all consumers see it.
After the impact-floor filtering and plan-order application (around line 168), add:
python
# If queue is empty and plan_start_scores exist, inject "run scan" workflow action
if not all_items and resolved_options.plan:
plan_scores = resolved_options.plan.get("plan_start_scores", {})
if plan_scores.get("strict") is not None:
all_items.append({
"id": "workflow::run_scan",
"kind": "workflow_action",
"summary": "Queue cleared -- run `desloppify scan` to finalize scores.",
"primary_command": "desloppify scan",
"file": "",
"detector": "",
"confidence": "high",
})
Then update show_empty_queue() in render_support.py to recognize this item and render it appropriately (or let the normal item renderer handle it). The show_empty_queue function would then only fire when there are truly zero items AND no workflow action.
Tests: Add a test that verifies build_work_queue returns a workflow::run_scan item when the queue is empty but plan_start_scores exist.
Fix 5: Remove Duplicate Signature Detection
Current state: After checking the working tree, detect_signature_variance is only called in one place in production code: phase_signature() in /Users/user_c042661f/Documents/desloppify/desloppify/languages/_framework/base/shared_phases.py:425. The old sig_variance smell entries in phase_smells() appear to have already been removed (no sig_variance or detect_signature_variance references in the smells detectors or finding factories).
However, the user reports 32 findings under signature::*::signature_variance::* and 32 under smells::*::sig_variance::*, which means the orphaned smells::sig_variance findings are from a previous scan and were never auto-resolved.
If the duplicate detection code has already been removed: The fix is simply Fix 1 (orphan resolution). Once out-of-scope findings are properly auto-resolved, the stale smells::sig_variance findings will be cleaned up on the next scan. No code changes needed for this issue.
If the duplicate detection code still exists in working tree (per user's report): Need to verify by checking git stash or the committed version. The user's description says "Both phase_signature() (shared) and phase_smells() (TS and Python) call detect_signature_variance()." If this is about the committed code on main (not the WIP branch), then:
Remove the detect_signature_variance() call from phase_smells() in both:
Keep it only in phase_signature() in /Users/user_c042661f/Documents/desloppify/desloppify/languages/_framework/base/shared_phases.py.
Rationale: phase_signature is the shared, backend-agnostic phase. All languages include it via detector_phase_signature(). Having smells also detect signature variance creates duplicates under different detector prefixes (signature:: vs smells::sig_variance::).
Migration for existing state files: The stale smells::sig_variance findings in existing state files will auto-resolve on the next scan because the smells detector will no longer emit them, and auto_resolve_disappeared will mark them resolved.
Implementation Order and Dependencies
Fix 1 (orphaned findings) -- Independent. Do this first because it eliminates the data-layer problem.
Fix 2 (queue counting consistency) -- Independent from Fix 1 but complementary. Together they eliminate the immediate infinite-loop bug.
Fix 3 (subjective policy) -- Depends on understanding Fix 2's design. Uses the same scan_path propagation pattern.
Fix 5 (duplicate signatures) -- Independent. May already be resolved by WIP changes.
Fix 4 (run-scan queue item) -- Depends on Fixes 1+2 being correct first, since it only matters when the queue is genuinely empty.
Potential Risks
Fix 1 could auto-resolve findings the user cares about if they accidentally narrow scan_path. Mitigation: the note clearly says "Out of scope" and the findings will reopen if scan_path is widened again.
Fix 2 could change queue counts in unexpected places (like status_cmd output). This is intentional -- the counts should have been consistent all along.
Fix 3 interacts with plan reconciliation (_reconcile_plan_post_scan in scan_workflow.py). The reconciliation injects stale dimensions and calls compute_subjective_visibility -- make sure the new parameters are threaded through.
Updated Caller Table After Fixes
After these changes, all callers of build_work_queue should have consistent scan_path behavior:
Caller
scan_path
Source
next
state.scan_path
explicit
show/scope
state.scan_path
explicit
plan/queue_render
state.scan_path
explicit
resolve/queue_guard
state.scan_path
NEW (currently missing)
review/preflight
state.scan_path
NEW (currently missing)
queue_progress (x2)
state.scan_path
NEW via state auto-extract
planning/queue_policy
state.scan_path
explicit (already has it)
planning/render (x2)
state.scan_path
explicit (already has it)
planning/select
scan_path param
explicit (already has it)
Note: resolve/queue_guard also needs scan_path added (line 26-33 in queue_guard.py). This is a secondary fix but important for full consistency.
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/merge_findings.py - Fix 1: Change auto_resolve_disappeared() to resolve out-of-scope findings instead of skipping them
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/queue_progress.py - Fix 2: Add scan_path to plan_aware_queue_count() and plan_aware_queue_breakdown()
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/subjective_policy.py - Fix 3: Add scan_path and plan parameters to compute_subjective_visibility()
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next_parts/render_support.py - Fix 4: Update show_empty_queue() to handle the workflow_action item from the queue
This investigation shows that all 4 main synthetic item kinds ARE properly integrated, but there are minor visual/UX gaps around subjective dimension headers and missing "rescan" queue item. The end-to-end flow works correctly.