I need to understand how the planning/queue system works in this codebase, specifically:
How items get prioritized and moved up in the queue (the "move" operations)
How new items enter the queue after a scan (reconciliation)
How clusters work and how new clusters are added
How _apply_plan_order() reorders items per plan
Please explore these files thoroughly:
desloppify/engine/_plan/schema.py - the plan data model
desloppify/engine/_plan/operations.py - plan operations (move, etc.)
desloppify/engine/_plan/reconcile.py - reconciliation after scan
desloppify/engine/plan.py - the facade
desloppify/engine/_plan/auto_cluster.py - auto clustering
Any work queue code that applies plan ordering (look for _apply_plan_order)
For each file, tell me:
The key data structures
How items are ordered in the queue
How "moved up" / prioritized items are tracked
How new items from a scan get inserted into the queue
Whether there's any protection to ensure manually-prioritized items stay above newly-added items
Be very thorough - read full file contents.
Assistant
I'll explore the planning/queue system thoroughly. Let me start by reading the key files.
Assistant
Now let me search for the _apply_plan_order() function to understand how plan ordering is applied:
Assistant
Now let me search for where reconciliation and auto-clustering are called in the scan workflow:
Assistant
Now let me look for how new findings get added to the queue initially (look at merge_scan in state.py):
Assistant
Let me check the stale_dimensions file which handles adding findings to the plan:
Assistant
Perfect! Now let me check the persistence module to understand how plan is saved/loaded:
Assistant
User
Assistant
I'll thoroughly explore the codebase to validate your design and produce a precise implementation plan. Let me start by reading all the relevant files.
Assistant
Now let me read the stale_dimensions.py file and the relevant test files.
Assistant
Now let me check the scan workflow to see where reconciliation is called, and look at the _plan package's __init__.py and the facade.
Assistant
Let me also look at the scan workflow where reconciliation is called, and the epic synthesis tests to understand the synthesis::pending injection testing.
Assistant
Let me also check whether _supersede_id removes from promoted_ids already, and look at any other place that clears plan lists to see what else might need cleanup.
Assistant
Now let me check if there's a validate_plan that would need updating, and look at the persistence layer and any serialization issues.
Assistant
Now I have a thorough understanding of the codebase. Let me also check move_cluster since it delegates to move_items -- confirming that the promoted_ids tracking in move_items would also cover cluster moves.
Assistant
Excellent! Now I have a comprehensive understanding. Let me create a detailed report for the user.
Comprehensive Analysis: Desloppify Planning/Queue System
Based on my thorough exploration of the codebase, here's how the planning and queue system works:
1. KEY DATA STRUCTURES
Plan Schema (desloppify/engine/_plan/schema.py):
queue_order: list[str] — Ordered list of finding IDs, determines priority/display order
skipped: dict[str, SkipEntry] — Finding IDs removed from active work (temporary/permanent/false_positive)
Regenerates automatic clusters from open, non-suppressed findings
Groups by deterministic keys (detector, dimension, file, subtype)
Preserves user-modified auto-clusters — adds new findings but doesn't replace manual edits
Deletes stale auto-clusters — clusters with no living members
Updates overrides to track cluster membership
Handles special cases: auto/initial-review (unscored dimensions) and auto/stale-review
Step E: sync_synthesis_needed()
Injects synthesis::pending at front of queue when review findings change
Never auto-prunes — only explicit completion removes it
Protection for Manually-Prioritized Items:
✅ Reconciliation happens first, clearing dead findings
✅ New subjective items prepend to front (unscored) or append to back (stale, conditional)
✅ Auto-clustering operates on open findings only, doesn't reorder existing queue
✅ Existing queue_order items stay in their current positions after reconciliation (reconciliation only removes dead IDs)
❌ NO EXPLICIT PROTECTION — if user hasn't moved items yet, new findings could still appear in ranking order between manually-prioritized items after _apply_plan_order() applies the ordering
4. HOW CLUSTERS WORK & ARE ADDED
Cluster Types:
Manual clusters (user_modified: False) — created by user
Auto clusters (auto: True, name starts with auto/) — regenerated every scan
auto/* — groups of open findings by detector/dimension/file
ordered — items in queue_order not in skipped (in that order)
remaining — items not in queue_order and not skipped (mechanical sort preserved)
skipped_items — items in skipped dict
Concatenate: ordered + remaining [+ skipped_items if include_skipped]
Assign queue positions starting at 1
Mark skipped items with plan_skipped: True, plan_skip_kind, reason
Filter to cluster if requested (keep only cluster members)
Key Invariant:
Items in queue_order appear first in that exact order
Remaining items keep their mechanical ranking (tier, dimension health, etc.)
queue_order acts as a "priority override" — anything there jumps ahead of automatic ranking
6. FLOW: SCAN → PLAN UPDATES → QUEUE RENDERING
code
User runs: desloppify scan
↓
1. Run detectors → findings list
2. state_mod.merge_scan() → persist findings to state
3. _reconcile_plan_post_scan(runtime):
a. reconcile_plan_after_scan() — remove dead IDs
b. sync_unscored_dimensions() — prepend to front
c. sync_stale_dimensions() — append to back (conditional)
d. auto_cluster_findings() — regenerate auto-clusters
e. sync_synthesis_needed() — inject synthesis if needed
f. save_plan()
↓
User runs: desloppify next / desloppify show / desloppify plan
↓
4. build_work_queue() → build_finding_items() + build_subjective_items()
5. sort by mechanical ranking (tier, dimension, etc.)
6. _apply_plan_order() → reorder per queue_order, annotate metadata
7. _collapse_clusters() → group auto-cluster members into meta-items
8. _apply_subjective_interleave_guardrail() → interleave objective/subjective 3:1
↓
9. Render queue with plan metadata
7. PROTECTION MECHANISMS FOR MANUALLY-PRIORITIZED ITEMS
Strong Protections:
✅ queue_order items appear first, in that order
✅ Reconciliation removes only dead IDs, doesn't reorder
✅ Moving items manually stays via move_items() → persisted to disk
Potential Issues:
⚠️ New findings not yet in queue_order will be ranked mechanically (could appear before some manually-prioritized items in the "remaining" group)
⚠️ If a manually-prioritized finding disappears (e.g., detector fix), it moves to superseded and is removed from queue
⚠️ Auto-clusters are regenerated every scan — if a user-modified auto-cluster has all members removed, the cluster is deleted
Summary Table
Operation
File
Effect on queue_order
When
move_items()
operations.py
Remove, then insert at position
User command
skip_items()
operations.py
Remove from queue, add to skipped
User command
unskip_items()
operations.py
Remove from skipped, append to queue_order
User command
reconcile_plan_after_scan()
reconcile.py
Remove dead IDs to superseded
Every scan
sync_unscored_dimensions()
stale_dimensions.py
Prepend to front
Every scan
sync_stale_dimensions()
stale_dimensions.py
Append to back (conditional)
Every scan
auto_cluster_findings()
auto_cluster.py
Regenerate clusters only, no queue reorder
Every scan
_apply_plan_order()
_work_queue/core.py
Display reordering only (non-destructive)
Queue rendering
Based on my thorough exploration of the desloppify planning/queue system, I need to design a solution for the following problem:
Problem
When a scan runs, reconciliation can insert new items at position 0 of queue_order, jumping ahead of items the user has explicitly moved to the top. There are exactly 2 offending code paths:
sync_unscored_dimensions() in desloppify/engine/_plan/stale_dimensions.py line 138: order.insert(0, uid) — prepends unscored subjective dimensions to front
sync_synthesis_needed() in desloppify/engine/_plan/stale_dimensions.py line 241: order.insert(0, SYNTHESIS_ID) — prepends synthesis::pending to front
Other reconciliation paths are fine: resurface_stale_skips() appends to end, sync_stale_dimensions() appends to end, auto_cluster_findings() doesn't touch queue_order.
How the queue works
queue_order: list[str] is the persisted ordering in plan.json
_apply_plan_order() in _work_queue/core.py renders: queue_order items first + remaining items (not in queue) in mechanical sort
move_items() in operations.py removes IDs from current position and inserts at specified position (top/bottom/before/after/up/down)
move_items() is only called from user-initiated CLI commands; system operations manipulate queue_order directly
Proposed Solution: promoted_ids tracking
Add a promoted_ids set to the plan that tracks IDs the user has explicitly positioned via move_items(). During reconciliation, system insertions go after the last promoted item instead of at position 0.
Schema (schema.py)
Add promoted_ids: list[str] to PlanModel TypedDict
Add to empty_plan(): "promoted_ids": []
Add to ensure_plan_defaults() / _ensure_container_types(): ensure it's a list
Operations (operations.py)
move_items(): after moving, add all finding_ids to promoted_ids (deduplicated)
skip_items(): remove from promoted_ids
reset_plan(): already cleared by empty_plan()
purge_ids(): remove from promoted_ids
Reconciliation (reconcile.py)
_supersede_id(): remove from promoted_ids
Stale dimensions (stale_dimensions.py)
Add helper:
python
def _after_promoted(order: list[str], plan: PlanModel) -> int:
"""Find insertion index after the last user-promoted item in queue_order."""
promoted = set(plan.get("promoted_ids", []))
if not promoted:
return 0
last_idx = -1
for i, fid in enumerate(order):
if fid in promoted:
last_idx = i
return last_idx + 1
sync_unscored_dimensions(): change order.insert(0, uid) to order.insert(_after_promoted(order, plan), uid) — but actually we need to re-compute the index each time since we're inserting multiple items. Each insertion should go at _after_promoted(order, plan) or we should collect all new IDs and batch-insert them.
sync_synthesis_needed(): change order.insert(0, SYNTHESIS_ID) to order.insert(_after_promoted(order, plan), SYNTHESIS_ID)
Edge cases
No promotions yet (fresh plan or no user moves): promoted_ids is empty, _after_promoted returns 0 → same as current behavior (insert at front)
Promoted items get superseded: removed from promoted_ids → insertion point moves correctly
User moves item DOWN (to bottom): still added to promoted_ids, but since _after_promoted finds the last promoted index, other promoted items at the top still protect the top positions correctly
Multiple inserts in one sync: need to be careful about index shifting — if we insert at position N, the next insert should go at N+1
Tests
Update test_unscored_injected_at_front — when there are promoted items, unscored should go after them
Add new test: test_unscored_respects_promoted_items — user moves item to top, scan injects unscored after it
Add new test: test_synthesis_respects_promoted_items — synthesis::pending goes after promoted items
Add new test: test_no_promoted_preserves_current_behavior — when no items are promoted, behavior is unchanged
Please review this design and provide a detailed implementation plan with specific code changes for each file.
Good -- move_cluster delegates to move_items at line 431, so promoted tracking in move_items covers cluster moves automatically.
Now I have enough context. Here is my detailed implementation plan.
Implementation Plan: promoted_ids tracking to protect user-positioned items
Problem Summary
When a scan runs, sync_unscored_dimensions() and sync_synthesis_needed() in stale_dimensions.py insert items at position 0 of queue_order, displacing items the user has explicitly moved to the top via plan move ... top. The fix introduces a promoted_ids set that tracks user-promoted items, causing system insertions to go after the last promoted item rather than at the absolute front.
Design Validation
After reading all the code, the proposed design is sound with a few refinements:
move_cluster delegates to move_items (line 431 in operations.py), so promoted tracking in move_items automatically covers cluster moves. No separate handling needed in move_cluster.
The reversed(sorted(...)) loop in sync_unscored_dimensions (line 136) inserts multiple items one-by-one at position 0. With the new helper, each insert goes at _after_promoted(order, plan). Since _after_promoted re-scans the list each call, and the newly inserted items are NOT in promoted_ids, the helper returns the same index each time. This means all unscored items cluster together right after the promoted block, which is the desired behavior. But the iteration order matters: reversed(sorted(...)) with insert(idx, ...) will produce items in sorted() order at that position, which is correct.
The _supersede_id function in reconcile.py removes items from queue_order, skipped, and clusters, but does NOT currently touch any other plan fields. It needs to also remove from promoted_ids.
validate_plan does not need changes since promoted_ids has no cross-field invariants worth enforcing (it is advisory/optimization only).
File-by-File Changes
1. desloppify/engine/_plan/schema.py
PlanModel TypedDict (line 74-87): Add field:
python
promoted_ids: list[str] # user-positioned queue items (protected from system insert-at-front)
empty_plan() (line 90-107): Add to the returned dict:
python
"promoted_ids": [],
_ensure_container_types() (line 110-128): Add:
python
if not isinstance(plan.get("promoted_ids"), list):
plan["promoted_ids"] = []
validate_plan() (lines 228-249): Add a validation that promoted_ids is a subset of queue_order (hygiene check):
python
# promoted_ids should be a subset of queue_order (stale IDs are harmless but noisy)
promoted = set(plan.get("promoted_ids", []))
queue_set = set(plan["queue_order"])
# Don't raise — just silently clean stale IDs, since this can happen during normal
# reconciliation races. Actually, skip validation — promoted_ids is advisory.
Actually, on reflection, do NOT add validation for promoted_ids in validate_plan(). Promoted IDs that are no longer in queue_order are harmless (they simply won't be found by _after_promoted and won't affect the insertion index). Adding validation would mean any cleanup race between reconcile and promote tracking could cause plan corruption errors. Keep it simple.
2. desloppify/engine/_plan/operations.py
move_items() (lines 151-179): After the insertion loop (line 177), add promoted tracking:
python
# Track user-promoted items
promoted: list[str] = plan.get("promoted_ids", [])
promoted_set = set(promoted)
for fid in finding_ids:
if fid not in promoted_set:
promoted.append(fid)
promoted_set.add(fid)
plan["promoted_ids"] = promoted
Note: This adds ALL moved items to promoted, regardless of position (top/bottom/before/after). This is intentional. Even a "move to bottom" represents user intent, and the system should respect it. The _after_promoted helper finds the LAST promoted item in queue_order, so a bottom-promoted item doesn't interfere with top-promoted items -- it merely prevents system inserts from going before it if it happens to be the last promoted item in the queue.
skip_items() (lines 186-215): After _remove_id_from_lists(plan, fid) (line 203), also remove from promoted:
python
promoted = plan.get("promoted_ids", [])
if fid in promoted:
promoted.remove(fid)
Or more efficiently, do it after the loop:
python
# Remove skipped items from promoted tracking
promoted = plan.get("promoted_ids", [])
promoted_ids_set = set(finding_ids)
plan["promoted_ids"] = [p for p in promoted if p not in promoted_ids_set]
purge_ids() (lines 465-498): After the existing cleanup loop, add:
python
# Remove purged IDs from promoted tracking
promoted = plan.get("promoted_ids", [])
purge_set = set(finding_ids)
plan["promoted_ids"] = [p for p in promoted if p not in purge_set]
reset_plan() (lines 456-462): Already handled because plan.clear() + empty_plan() will produce "promoted_ids": [].
3. desloppify/engine/_plan/reconcile.py
_supersede_id() (lines 47-102): After removing from queue_order/skipped/clusters (lines 86-94), add:
python
# Remove from promoted tracking
promoted = plan.get("promoted_ids", [])
if finding_id in promoted:
promoted.remove(finding_id)
4. desloppify/engine/_plan/stale_dimensions.py
Add helper function (after the _current_unscored_ids function, around line 98):
python
def _after_promoted(order: list[str], plan: PlanModel) -> int:
"""Return the insertion index just after the last user-promoted item.
When no promoted items exist (or none are in ``order``), returns 0 to
preserve the current insert-at-front behavior.
"""
promoted = set(plan.get("promoted_ids", []))
if not promoted:
return 0
last_idx = -1
for i, fid in enumerate(order):
if fid in promoted:
last_idx = i
return last_idx + 1
sync_unscored_dimensions() (lines 104-141): Change line 138 from:
python
order.insert(0, uid)
to:
python
order.insert(_after_promoted(order, plan), uid)
Important note on the loop: The existing code uses reversed(sorted(unscored_ids)) and inserts each at position 0. With the new code, each insertion at _after_promoted(order, plan) will go at the same index (since newly inserted items are NOT promoted), so each successive insert pushes the previous one right by one slot. With reversed(sorted(...)), this produces the items in ascending sorted order at the insertion point, which matches the existing behavior (items end up in sorted() order at the front). This is correct.
sync_synthesis_needed() (lines 222-246): Change line 241 from:
Update test_unscored_injected_at_front() (line 100-110): This test should still pass as-is because the plan has no promoted_ids, so _after_promoted returns 0. No changes needed to this test, but consider adding a comment clarifying the empty-promoted case.
Add new tests:
python
def test_unscored_respects_promoted_items():
"""Unscored dims go after user-promoted items, not at absolute front."""
plan = _plan_with_queue("user_moved_item::file.py::abc123")
plan["promoted_ids"] = ["user_moved_item::file.py::abc123"]
state = _state_with_unscored_dimensions("design_coherence")
result = sync_unscored_dimensions(plan, state)
assert len(result.injected) == 1
# User-promoted item stays at position 0
assert plan["queue_order"][0] == "user_moved_item::file.py::abc123"
# Unscored dim goes after promoted item
assert plan["queue_order"][1] == "subjective::design_coherence"
def test_unscored_multiple_promoted_items():
"""Multiple promoted items all stay ahead of system-injected dims."""
plan = _plan_with_queue("item_a", "item_b", "item_c")
plan["promoted_ids"] = ["item_a", "item_b"]
state = _state_with_unscored_dimensions("design_coherence")
result = sync_unscored_dimensions(plan, state)
assert plan["queue_order"][:2] == ["item_a", "item_b"]
assert plan["queue_order"][2] == "subjective::design_coherence"
assert plan["queue_order"][3] == "item_c"
def test_no_promoted_preserves_front_insertion():
"""When no items are promoted, unscored dims go to front (same as before)."""
plan = _plan_with_queue("some_finding::file.py::abc123")
# No promoted_ids set
state = _state_with_unscored_dimensions("design_coherence")
result = sync_unscored_dimensions(plan, state)
assert plan["queue_order"][0] == "subjective::design_coherence"
assert plan["queue_order"][1] == "some_finding::file.py::abc123"
6. desloppify/tests/plan/test_epic_synthesis.py
Update test_injects_at_front() (line 179-184): This test still passes because the plan has no promoted_ids. Add a companion test:
python
def test_injects_after_promoted(self):
"""synthesis::pending goes after user-promoted items."""
plan = empty_plan()
plan["queue_order"] = ["user_item"]
plan["promoted_ids"] = ["user_item"]
state = _state_with_review_findings("r1")
sync_synthesis_needed(plan, state)
assert plan["queue_order"][0] == "user_item"
assert plan["queue_order"][1] == SYNTHESIS_ID
Operations (operations.py) -- add promoted tracking to move_items, skip_items, purge_ids
Reconcile (reconcile.py) -- add promoted cleanup in _supersede_id
Stale dimensions (stale_dimensions.py) -- add _after_promoted helper, update two order.insert(0, ...) calls
Tests (test_stale_dimensions.py, test_epic_synthesis.py) -- add new tests, verify existing pass
Edge Cases Addressed
Fresh plans / migration: ensure_plan_defaults and _ensure_container_types ensure promoted_ids always exists as a list, even for plans saved before this change.
Promoted item gets superseded: _supersede_id removes it from promoted_ids, so the insertion index adjusts correctly.
Promoted item gets skipped: skip_items removes it from promoted_ids.
Promoted item gets purged: purge_ids removes it from promoted_ids.
Plan reset: reset_plan clears everything via empty_plan().
Multiple system inserts in one sync: Each insert calls _after_promoted which re-scans the order. Since newly inserted items are not promoted, the function returns the same index, and successive inserts stack up correctly after the promoted block.
Stale promoted IDs (in promoted_ids but no longer in queue_order): Harmless -- _after_promoted only looks at items actually in order, so stale entries in the set are ignored. They get cleaned up naturally when the finding is superseded/skipped/purged.
What This Does NOT Change
sync_stale_dimensions -- already appends to end, no fix needed
resurface_stale_skips -- already appends to end, no fix needed
auto_cluster_findings -- does not touch queue_order, no fix needed
_apply_plan_order in core.py -- only reads queue_order, no change needed
validate_plan -- no new invariants to enforce
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/schema.py - Add promoted_ids field to PlanModel, empty_plan, and ensure_defaults
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/operations.py - Track promoted IDs in move_items, skip_items, purge_ids
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/stale_dimensions.py - Add _after_promoted helper, change both insert(0, ...) calls
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/reconcile.py - Remove superseded IDs from promoted_ids in _supersede_id
/Users/user_c042661f/Documents/desloppify/desloppify/tests/plan/test_stale_dimensions.py - Add tests for promoted-aware insertion behavior