Look at the local git diff (unstaged changes) in this repo. Focus on understanding the feature where, when the work queue reaches the end of a batch and there are subjective items that need review or are stale, the system updates them or adds them to the next queue.
Key files to examine via git diff:
desloppify/engine/_work_queue/core.py and ranking.py — work queue logic
desloppify/engine/_plan/stale_dimensions.py — stale dimension detection
desloppify/app/commands/next.py and next_parts/output.py and next_parts/render.py — the next command
desloppify/app/commands/next_parts/render.py — rendering, especially empty-state handling
desloppify/engine/_work_queue/core.py — build_work_queue, especially how it handles empty queues
desloppify/engine/_plan/stale_dimensions.py — the full file, especially sync_stale_dimensions and _current_stale_ids and the SUBJECTIVE_PREFIX constant
desloppify/engine/_plan/auto_cluster.py — the full file, especially how stale clusters are created
desloppify/engine/_state/scoring.py — how dimension_scores work, especially subjective entries
desloppify/app/commands/scan/scan_workflow.py — where sync_stale and auto_cluster are called
Assistant
I'll read all the requested files in parallel.
Assistant
Now let me also look at the key helper functions to understand the "no scan" vs "everything resolved" detection, and how subjective entries are determined.
Assistant
Now let me look at the scorecard_subjective_entries function to understand how "stale" is determined.
Assistant
User
Read the following files in full and report back their complete contents and structure. I need to understand the exact implementation details for planning a similar feature.
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/stale_dimensions.py — full file
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/auto_cluster.py — full file
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_workflow.py — focus on the plan reconciliation section (where sync_stale_dimensions and auto_cluster_findings are called), and the merge_scan_results function signature
Report:
The exact function signatures and their parameters
The exact logic of _current_stale_ids and how it uses scorecard_subjective_entries
The exact condition for injection in sync_stale_dimensions
How auto_cluster_findings handles the stale-review cluster specifically
The exact call order in scan_workflow.py
Any constants like SUBJECTIVE_PREFIX, _STALE_KEY, _STALE_NAME, _MIN_CLUSTER_SIZE
Assistant
I'll read these files to understand the implementation details for your planning.
User
Read the following files in full and report their complete contents and structure. I need to understand how the next command works and how subjective scorecard entries are computed.
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next.py — the full file, especially cmd_next and what happens at each stage
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next_parts/render.py — the full file, especially show_empty_queue and _render_cluster_item
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next_parts/output.py — full file
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py — full file, especially build_work_queue and _collapse_clusters
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/ranking.py — full file, especially how clusters are sorted
Also search for and read the function — find where it's defined and read it. This function is used by and I need to know what fields each entry has (especially , , ).
Assistant
I'll help you understand the next command flow and how subjective scorecard entries are computed. Let me read the files you specified.
Assistant
Now let me search for the scorecard_subjective_entries function definition:
Assistant
Now let me read that file:
Assistant
Perfect! Now I need to understand build_subjective_items to see how subjective_dimension items are created. Let me search for that:
Assistant
Let me read that file:
Assistant
Perfect! Now let me check the scorecard_dimension_rows function to understand the complete data flow:
Assistant
Assistant
User
Assistant
I'll start by thoroughly exploring the relevant files to understand the current implementation before designing the plan.
Assistant
Now let me explore the remaining critical files.
Assistant
Now let me look at the scorecard_subjective_entries function to understand the placeholder field, and the helpers used for subjective items.
Assistant
Now let me look at scorecard_subjective_entries to understand the placeholder and stale fields.
Assistant
Now let me look at the existing test file for stale_dimensions to understand test patterns.
Assistant
Now let me check the reconcile module to understand how synthetic IDs are handled there.
Assistant
I now have a thorough understanding of the entire flow. Let me verify one more thing -- how SUBJECTIVE_PREFIX is used for both stale and unscored dimensions, and what the _current_stale_ids function specifically filters on.
Assistant
Now I have a comprehensive picture. Here is my summary:
Summary of the "End-of-Batch Stale/Subjective Refresh" Feature
Overview
This diff implements a system where, when the user works through the prioritized work queue and resolves all the objective (mechanical/detector-based) findings, the system automatically detects that the batch is "done" and injects stale subjective dimensions (review-based quality assessments that have gone out of date) into the queue as the next work items. These stale items are also automatically grouped into clusters for easier batch processing.
1. How "End of Batch" / "All Objective Items Done" Is Detected
The key logic lives in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/stale_dimensions.py, in the sync_stale_dimensions() function.
Old behavior: Stale subjective dimensions were only injected when the queue was completely empty (if not order and stale_ids).
New behavior: The condition was relaxed. Instead of requiring a totally empty queue, the system now checks whether any objective (non-subjective) items remain:
python
has_real_items = any(fid for fid in order if not fid.startswith(SUBJECTIVE_PREFIX))
if not has_real_items and stale_ids:
This means injection happens when:
There are zero objective finding IDs left in queue_order, AND
There are stale subjective dimensions that need refreshing
The queue can still contain leftover subjective::* IDs from a previous round -- the system no longer requires the queue to be literally empty. It only cares that the "real" (objective/detector-based) work is done.
2. How Stale/Subjective Items Are Identified
The _current_stale_ids() function in stale_dimensions.py determines which subjective dimensions are currently stale:
python
def _current_stale_ids(state: StateModel) -> set[str]:
dim_scores = state.get("dimension_scores", {}) or {}
stale: set[str] = set()
for entry in scorecard_subjective_entries(state, dim_scores=dim_scores):
if not entry.get("stale"):
continue
dim_key = entry.get("dimension_key", "")
if dim_key:
stale.add(f"{SUBJECTIVE_PREFIX}{slugify(dim_key)}")
return stale
It calls scorecard_subjective_entries() which examines each subjective dimension in the scorecard (things like "design_coherence", "error_consistency", "abstraction_fitness"). A dimension is "stale" when needs_review_refresh is true in the state's subjective_assessments -- meaning the codebase has changed mechanically since the last time that dimension was reviewed, so the review score is outdated.
Each stale dimension gets a synthetic ID like subjective::design_coherence.
3. How They Are Queued for Refresh
The flow is a two-stage pipeline that runs during merge_scan_results in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_workflow.py:
Stage 1: Sync stale dimensions (sync_stale_dimensions):
Cleanup: Removes any subjective::* IDs from queue_order that are no longer stale (the user refreshed them or mechanical evidence changed).
Inject: If no objective items remain in the queue, appends all currently-stale dimension IDs to queue_order.
Stage 2: Auto-cluster (auto_cluster_findings in the new /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/auto_cluster.py):
After stale dimensions are injected into the queue, the auto-clustering pass runs.
It scans queue_order for IDs starting with subjective::. If there are 2 or more (_MIN_CLUSTER_SIZE = 2), it creates a special cluster named auto/stale-review with cluster_key = "subjective::stale".
The cluster's description is like "Re-review 3 stale subjective dimensions" and its action is a CLI command: desloppify review --prepare --dimensions design_coherence,error_consistency,...
If the stale set changes (dimensions get refreshed or new ones become stale), the cluster membership is updated. If all stale dimensions are refreshed and the queue empties, the stale cluster is deleted.
4. Auto-Clustering of All Findings (Not Just Stale)
The auto_cluster_findings function does much more than just stale dimensions. It groups all open findings into clusters by computing a grouping key:
Review findings group by dimension (review::abstraction_fitness)
Structural/responsibility findings group by file (file::structural::big_file.py)
Findings with subtypes group by detector+subtype (typed::dict_keys::phantom_read)
Pure auto-fix detectors group all by detector (auto::unused)
Everything else groups by detector name
Each cluster gets:
A generated description ("Fix 5 phantom_read issues")
An action command (e.g., desloppify fix unused-imports --dry-run for auto-fixable, or guidance text)
An action_type classification: auto_fix, reorganize, refactor, or manual_fix
5. Cluster Presentation in the Work Queue
In /Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py, a new _collapse_clusters function replaces individual cluster member items with single "cluster meta-items" before they are shown to the user. This happens when:
collapse_clusters is True (default)
A plan exists with clusters
The user is NOT already drilling into a specific cluster
The meta-items carry kind: "cluster" and contain the members, summary, primary command, and action type.
Sorting (in ranking.py): Cluster meta-items sort before all individual findings, ordered by action type priority (auto_fix first, then reorganize, refactor, manual_fix), then by size (bigger clusters first).
Tier counting: When counting findings per tier, cluster members are expanded so each member counts at its own tier.
Rendering (in render.py): A dedicated _render_cluster_item function renders cluster task cards showing:
Action type label and count ("Auto-fixable batch, 12 findings")
File distribution
Sample finding IDs
Primary action command
Resolution hints (resolve all, drill in, skip cluster)
6. Resolve Command: Cluster-Aware Resolution
In /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/resolve/apply.py, a new _try_expand_cluster function was added. When a user runs desloppify resolve fixed "auto/stale-review", the system checks if the pattern matches a cluster name and expands it to all member finding IDs, resolving them in batch.
7. Suppressed Findings Excluded from Scoring
Three files got the same fix -- suppressed findings are now filtered out early:
Additionally, the old behavior where suppressing a finding would reset its status to "open" (for "score integrity") was removed from both remove_ignored_findings and upsert_findings. Suppressed findings are now simply invisible to scoring.
8. Other Supporting Changes
"Deferred" terminology removed: The old deferred list in the plan is fully replaced by the skipped map. The include_deferred parameter was renamed to include_skipped. Backward-compat shims for plan_deferred and total_deferred were removed.
Schema changes: The Cluster TypedDict gained four new fields: auto, cluster_key, action, and user_modified, with defaults applied in ensure_plan_defaults.
needs_rescan flag: When ignoring a pattern, config["needs_rescan"] = True is set, and cleared after the next scan merge.
Subjective dimension source: Scoring now uses load_dimensions_for_lang() from the data module instead of HOLISTIC_DIMENSIONS_BY_LANG, so the full scorecard dimensions (not just the hardcoded per-language list) generate 0-score placeholders.
Overall Flow
code
User runs scan
-> merge_scan_results()
-> Scoring recomputed (suppressed findings excluded)
-> reconcile_plan_after_scan() removes resolved findings
-> sync_stale_dimensions():
1. Prune subjective IDs no longer stale
2. If no objective items left -> inject stale dimension IDs
-> auto_cluster_findings():
- Group all open findings into auto-clusters
- Create/update/delete auto/stale-review cluster for stale dims
-> save_plan()
User runs next
-> build_work_queue()
-> _apply_plan_order() reorders by plan queue
-> _collapse_clusters() replaces member items with cluster meta-items
-> Filter by tier (cluster members expanded for tier matching)
-> Render: cluster cards shown with action type, file breakdown, commands
The net effect: once a user resolves all the concrete, mechanically-detected findings, the system seamlessly transitions to surfacing the stale subjective review dimensions as the next body of work, grouped into a reviewable cluster with a ready-made CLI command.
Focus on:
What does next show when the queue is empty?
How does it currently detect "no scan has been run" vs "scan was run but everything resolved"?
What are subjective dimensions? How is their "never scored" vs "stale" state tracked?
How does the stale_dimensions sync decide what to inject?
How does auto_cluster create the stale-review cluster?
Read the full files, don't just look at diffs.
Here is the comprehensive summary of the flow you asked about.
Summary of the next Command Flow, Subjective Dimensions, and Scoring
def show_empty_queue(queue: dict, tier: int | None, strict: float | None) -> bool:
if queue.get("items"):
return False
suffix = f" Strict score: {strict:.1f}/100" if strict is not None else ""
print(colorize(f"\n Nothing to do!{suffix}", "green"))
if tier is not None:
print(colorize(f" Requested tier: T{tier}", "dim"))
available = queue.get("available_tiers", [])
if available:
commands = " | ".join(
f"desloppify next --tier {tier_num}" for tier_num in available
)
print(colorize(f" Try: {commands}", "dim"))
return True
It simply prints "Nothing to do!" in green, plus the strict score. If a specific tier was requested that has 0 items, it shows the available tiers. There is no distinction in the empty message between "you're truly done" vs "you have stale subjective dimensions that need re-review" -- it's the same green "Nothing to do!" message in all cases.
2. "No scan has been run" vs "scan was run but everything resolved"
def require_completed_scan(state: dict) -> bool:
has_completed_scan = bool(state.get("last_scan"))
if not has_completed_scan:
print(colorize("No scans yet. Run: desloppify scan", "yellow"))
return has_completed_scan
This is called at the top of cmd_next (line 66-67 of next.py). It checks for the presence of state["last_scan"]. If that key is falsy (missing or empty), it prints "No scans yet" in yellow and returns early. If a scan was completed (last_scan is set) but all findings are resolved, the flow continues through to show_empty_queue which prints the green "Nothing to do!" message.
So the detection is straightforward:
No scan:state["last_scan"] is falsy --> yellow warning, early return
Everything resolved:build_work_queue returns empty items --> green "Nothing to do!" with score
3. What are subjective dimensions? How is "never scored" vs "stale" tracked?
Subjective dimensions are scorecard dimensions whose scores come from human review assessments (via desloppify review) rather than from mechanical detectors. They live in state["subjective_assessments"] as a dict keyed by dimension slug.
"Never scored" (placeholder):
In /Users/user_c042661f/Documents/desloppify/desloppify/engine/planning/scorecard_projection.py, lines 94-101:
python
placeholder = bool(
assessment_meta.get("placeholder")
or (
data.get("score", 0) == 0
and data.get("issues", 0) == 0
and data.get("checks", 0) == 0
)
)
A dimension is a "placeholder" (never meaningfully scored) when either:
The assessment metadata explicitly has placeholder: true (set by scan_reset_subjective or manual_override_expired)
The dimension has score=0, issues=0, checks=0 (no data at all)
"Stale":
Lines 103-107:
python
stale = bool(
dim_key
and isinstance(assessments.get(dim_key), dict)
and assessments[dim_key].get("needs_review_refresh")
)
A dimension is "stale" when its assessment payload has needs_review_refresh set to a truthy value. This flag is set when the codebase has changed enough that a previously-valid review score may no longer be accurate.
4. How does sync_stale_dimensions decide what to inject?
The function _current_stale_ids (lines 30-48) computes the set of currently-stale subjective dimension IDs by:
Getting dimension_scores from state
Calling scorecard_subjective_entries() to get all subjective scorecard entries
Filtering to only entries where entry.get("stale") is truthy
Converting each to a plan ID using the format "subjective::<slugified_dim_key>"
The main function sync_stale_dimensions (lines 51-85) then does two things:
Cleanup (always runs): Remove any subjective::* IDs from plan["queue_order"] that are no longer in the stale set (i.e., the dimension was refreshed).
Injection (conditional): Only inject stale dimension IDs if there are no objective (non-subjective) items remaining in the queue after cleanup. The check is:
python
has_real_items = any(fid for fid in order if not fid.startswith(SUBJECTIVE_PREFIX))
if not has_real_items and stale_ids:
# inject missing stale IDs
This means stale subjective dimensions only get added to the plan queue when all mechanical/objective work is done. The intention is that mechanical fixes take priority.
5. How does auto_cluster create the stale-review cluster?
The cluster_key is "subjective::stale" (constant _STALE_KEY)
It strips the subjective:: prefix from IDs to get the CLI dimension keys
If an existing auto/stale-review cluster exists (matched by cluster_key), it updates it if the member IDs, description, or action changed. Otherwise it creates a new one.
Overrides are also set so each subjective ID gets cluster: "auto/stale-review".
Like all auto-clusters, if the stale-review cluster's key is no longer in the active set (no stale dimensions left), it gets deleted in the cleanup sweep at lines 384-413.
After merging scan results and saving state, the scan workflow does plan reconciliation in a try/except (best-effort):
Load plan from plan.json
Standard reconciliation (reconcile_plan_after_scan) -- only if plan has user content (queue_order, overrides, clusters, skipped)
Stale dimension sync (sync_stale_dimensions) -- always runs, handles both cleanup of refreshed dimensions and injection when no objective items remain
Auto-cluster (auto_cluster_findings) -- always runs, groups findings into task clusters including the stale-review cluster
Save plan if any changes occurred
The order matters: stale sync runs before auto-cluster, so auto-cluster can see any newly-injected subjective IDs in queue_order when deciding whether to create the auto/stale-review cluster.
Key architectural insight
The subjective dimension lifecycle is:
Unassessed/placeholder: score=0, no checks, placeholder: true -- shown as a T4 item in the work queue with command desloppify review --prepare
Assessed: has a real score from a review run
Stale: codebase changes triggered needs_review_refresh on the assessment -- shown with a [stale -- re-review] tag
Injected into plan: when all objective items are resolved, stale dimension IDs get added to queue_order, and if 2+ exist they get grouped into the auto/stale-review cluster
scorecard_subjective_entries
_current_stale_ids
stale
placeholder
dimension_key
Report:
The full flow of cmd_next from start to finish
How build_work_queue constructs items and handles clusters
How clusters are ranked/sorted
How _render_cluster_item renders cluster items
The full signature and return shape of scorecard_subjective_entries
What fields are on each subjective entry (especially stale vs placeholder)
I have the complete contents of all three files. Here's my comprehensive analysis:
Complete Implementation Details Report
1. Function Signatures
stale_dimensions.py:
_current_stale_ids(state: StateModel) -> set[str]
Extracts stale dimensions from state and returns them as subjective::<slug> IDs
def _current_stale_ids(state: StateModel) -> set[str]:
from desloppify.engine._work_queue.helpers import slugify
from desloppify.engine.planning.scorecard_projection import (
scorecard_subjective_entries,
)
dim_scores = state.get("dimension_scores", {}) or {}
if not dim_scores:
return set()
stale: set[str] = set()
for entry in scorecard_subjective_entries(state, dim_scores=dim_scores):
if not entry.get("stale"):
continue
dim_key = entry.get("dimension_key", "")
if dim_key:
stale.add(f"{SUBJECTIVE_PREFIX}{slugify(dim_key)}")
return stale
Key details:
Gets dimension_scores from state; returns empty set if missing
Calls scorecard_subjective_entries(state, dim_scores=dim_scores) — this is the critical function that filters entries
Only includes entries where entry.get("stale") is truthy
Slugifies the dimension key and prefixes it with "subjective::"
Returns a sorted set of these IDs
3. Injection Condition in sync_stale_dimensions
python
has_real_items = any(fid for fid in order if not fid.startswith(SUBJECTIVE_PREFIX))
if not has_real_items and stale_ids:
existing = set(order)
for sid in sorted(stale_ids):
if sid not in existing:
order.append(sid)
result.injected.append(sid)
Exact condition for injection:
has_real_items must be False — there are NO items in queue that don't start with "subjective::"
stale_ids must be non-empty — there are currently stale dimensions to inject
Only appends IDs not already in the queue (checks if sid not in existing)
Sorted order — for sid in sorted(stale_ids)
4. Auto-clustering for Stale-Review Cluster
Lines 337–383 in auto_cluster.py handle the stale-review cluster separately from regular findings grouping:
python
# --- Stale subjective dimension cluster --------------------------------
subjective_ids = sorted(
fid for fid in plan.get("queue_order", [])
if fid.startswith(SUBJECTIVE_PREFIX)
)
if len(subjective_ids) >= _MIN_CLUSTER_SIZE: # _MIN_CLUSTER_SIZE = 2
active_auto_keys.add(_STALE_KEY)
cli_keys = [fid.removeprefix(SUBJECTIVE_PREFIX) for fid in subjective_ids]
description = f"Re-review {len(subjective_ids)} stale subjective dimensions"
action = f"desloppify review --prepare --dimensions {','.join(cli_keys)}"
existing_name = existing_by_key.get(_STALE_KEY)
if existing_name and existing_name in clusters:
# Update existing cluster
cluster = clusters[existing_name]
old_ids = set(cluster.get("finding_ids", []))
new_ids = set(subjective_ids)
if old_ids != new_ids or cluster.get("description") != description or cluster.get("action") != action:
cluster["finding_ids"] = subjective_ids
cluster["description"] = description
cluster["action"] = action
cluster["updated_at"] = now
changes += 1
else:
# Create new cluster
clusters[_STALE_NAME] = {
"name": _STALE_NAME,
"description": description,
"finding_ids": subjective_ids,
"created_at": now,
"updated_at": now,
"auto": True,
"cluster_key": _STALE_KEY,
"action": action,
"user_modified": False,
}
existing_by_key[_STALE_KEY] = _STALE_NAME
changes += 1
# Track cluster membership in overrides
overrides = plan.get("overrides", {})
current_name = existing_by_key.get(_STALE_KEY, _STALE_NAME)
for fid in subjective_ids:
if fid not in overrides:
overrides[fid] = {"finding_id": fid, "created_at": now}
overrides[fid]["cluster"] = current_name
overrides[fid]["updated_at"] = now
Key specifics:
Cluster is created only if len(subjective_ids) >= _MIN_CLUSTER_SIZE (≥ 2)
Finds all subjective::* IDs from plan["queue_order"]
Uses _STALE_KEY as cluster_key to track it in existing_by_key mapping
Sets user_modified: False so updates replace membership wholesale (not merge)
Updates overrides[fid]["cluster"] for every subjective ID to tie it to the cluster
5. Exact Call Order in scan_workflow.py (merge_scan_results)
Lines 426–480 show the exact sequence:
python
# Reconcile living plan + sync stale subjective dimensions
try:
from desloppify.engine.plan import (
load_plan,
reconcile_plan_after_scan,
save_plan,
sync_stale_dimensions,
)
plan_path = runtime.state_path.parent / "plan.json"
plan = load_plan(plan_path)
dirty = False
# 1. RECONCILIATION (optional, only if plan has user content)
if (
plan.get("queue_order")
or plan.get("overrides")
or plan.get("clusters")
or plan.get("skipped")
):
recon = reconcile_plan_after_scan(plan, runtime.state)
if recon.changes:
dirty = True
if recon.resurfaced:
print(...)
# 2. STALE DIMENSION SYNC (always runs)
dim_sync = sync_stale_dimensions(plan, runtime.state)
if dim_sync.changes:
dirty = True
if dim_sync.pruned:
print(...)
if dim_sync.injected:
print(...)
# 3. AUTO-CLUSTERING (always runs)
from desloppify.engine._plan.auto_cluster import auto_cluster_findings
ac_changes = auto_cluster_findings(plan, runtime.state)
if ac_changes:
dirty = True
if dirty:
save_plan(plan, plan_path)
except Exception:
pass # Plan reconciliation is best-effort
Call order is rigid:
reconcile_plan_after_scan(plan, state) — if plan has user content
List of review --dimensions CLI keys for this scorecard entry
Important: Each entry is derived from scorecard_dimension_rows(state, dim_scores=dim_scores), which are rows where the detector includes subjective_assessment.
6. What Fields Are on Each Subjective Entry
Detailed field breakdown:
name — Display name from scorecard (e.g., "Elegance (combined)", "Abstraction fit")
stale (lines 103-107)
Computed as: dim_key and isinstance(assessments.get(dim_key), dict) and assessments[dim_key].get("needs_review_refresh")
Set to True if the dimension's assessment is marked for refresh
Used in build_subjective_items to tag summary with "[stale — re-review]" and set command to desloppify review --prepare --dimensions <keys>
placeholder (lines 94-101)
Computed as: assessment_meta.get("placeholder") or (score==0 and issues==0 and checks==0)
Set to True if:
Explicitly marked as placeholder in detector metadata, OR
Score/issues/checks are all zero (no assessment data exists)
Used in build_subjective_items to set command to desloppify review --prepare (initial assessment)
dimension_key (line 102)
Canonical key from detector's subjective_assessment metadata
Maps scorecard display names to dimension keys used in CLI (--dimensions)
Other fields — straightforward scores and metadata passed through from scorecard_dimension_rows
These synthetic items are added to the work queue if include_subjective=True and strict_score < subjective_threshold.
Summary Table: Key Distinctions
Aspect
Cluster
Subjective Dimension
Regular Finding
kind
"cluster"
"subjective_dimension"
"finding"
tier
Varies by members
Always 4
T1–T4
effective_tier
Varies by members
Always 4
Actual tier
detector
Original detector
"subjective_assessment"
Actual detector
Sort priority
0 (clusters first)
Within T4, after mechanical (1)
Within tier, before subjective (0)
Rendering
Special cluster card
Subjective dimension item
Standard item
Built from
Plan's auto-clusters
scorecard_subjective_entries
State's findings
I need to design an implementation plan for adding "initial subjective review" support to the desloppify tool. Here's the context:
Current system (stale reviews at end of batch)
stale_dimensions.py has _current_stale_ids(state) which finds dimensions where entry.get("stale") is True via scorecard_subjective_entries()
sync_stale_dimensions(plan, state) appends stale dimension IDs (prefixed subjective::) to the BACK of plan["queue_order"] ONLY when no objective items remain
auto_cluster.py groups all subjective::* IDs from queue_order into an auto/stale-review cluster
After a scan, if there are subjective dimensions that have NEVER been scored (placeholder=True), they should be injected at the FRONT of the queue so they appear as the user's first priority. This is distinct from stale (which stays at the back, end-of-batch only).
Key requirements:
Unscored dimensions go to FRONT of queue (highest priority after scan)
Stale dimensions stay at BACK (only when no objective items left) — unchanged
A dimension is "unscored" when scorecard_subjective_entries returns placeholder=True for it
A dimension CANNOT be both unscored and stale (disjoint sets)
Auto-cluster should create auto/initial-review for unscored dims, separate from auto/stale-review
The injection is unconditional (not gated on "no objective items remaining")
Files involved
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/stale_dimensions.py — existing stale sync
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/auto_cluster.py — auto clustering, constants: _STALE_KEY="subjective::stale", _STALE_NAME="auto/stale-review", _MIN_CLUSTER_SIZE=2
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next_parts/render.py — _render_cluster_item maps action_type to labels
Design questions I want you to address:
Should sync_unscored_dimensions be a separate function or should we extend sync_stale_dimensions?
How should auto_cluster_findings distinguish unscored vs stale IDs (they both use subjective:: prefix)?
Should we add a new action_type for the initial-review cluster, or reuse existing ones?
What's the right call order in scan_workflow.py?
What about _MIN_CLUSTER_SIZE for initial review — should 1 unscored dimension create a cluster?
How does the queue ordering work end-to-end: unscored prepended → plan ordering → cluster collapse → rendering?
What edge cases matter? (partial reviews, re-scans, language with no subjective dims, etc.)
Please provide a concrete, detailed implementation plan with specific changes per file.
Good. I now have a complete picture. Let me deliver the implementation plan.
Implementation Plan: Initial Subjective Review Support
Design Decisions (Answering Your 7 Questions)
1. Should sync_unscored_dimensions be a separate function or extend sync_stale_dimensions?
Separate function. The two operations have fundamentally different semantics:
Unscored: unconditional injection to the FRONT of the queue. Runs every scan.
Stale: conditional injection to the BACK, only when no objective items remain.
Mixing them into one function would create confusing branching and make the distinct behaviors harder to test. The existing sync_stale_dimensions has a clean contract (cleanup + conditional back-injection), and adding front-injection with different gating would muddy it. A separate sync_unscored_dimensions function in the same file (stale_dimensions.py) keeps them co-located since they share the same helpers (scorecard_subjective_entries, SUBJECTIVE_PREFIX, slugify) and data model.
2. How should auto_cluster_findings distinguish unscored vs stale IDs?
Both use the same subjective::<slug> ID format in queue_order, which is correct -- they ARE the same synthetic IDs, just in different states. The distinction is made at clustering time by checking the underlying state. The implementation:
After collecting all subjective::* IDs from queue_order, partition them into two sets by re-querying scorecard_subjective_entries:
IDs where entry.get("placeholder") is True go into the auto/initial-review cluster.
IDs where entry.get("stale") is True go into the auto/stale-review cluster.
Since requirement 4 says they are disjoint sets, there is no overlap concern.
Use a new constant _UNSCORED_KEY = "subjective::unscored" and _UNSCORED_NAME = "auto/initial-review" (parallel to the existing _STALE_KEY / _STALE_NAME).
3. Should we add a new action_type for the initial-review cluster, or reuse existing ones?
No new action_type. The existing action_type values (auto_fix, reorganize, refactor, manual_fix) are detector-oriented. The initial-review cluster is a subjective-review batch -- it does not fit cleanly into any of those, but manual_fix is the correct semantic match (requires human judgment). The cluster rendering in _render_cluster_item already maps manual_fix to "Grouped task", which is acceptable for initial review.
However, we should add a special-case label in _ACTION_TYPE_LABELS lookup or in _render_cluster_item to detect the cluster name auto/initial-review and display "Initial subjective review" instead of the generic "Grouped task". This is a rendering-only concern and does not require a schema change.
4. What is the right call order in scan_workflow.py?
The current order in merge_scan_results (lines 427-478) is:
Unscored sync prepends IDs to the FRONT of queue_order.
Stale sync appends IDs to the BACK (when no objective items remain).
Running unscored first means the cleanup pass of sync_stale_dimensions will correctly skip unscored IDs (they would not be in _current_stale_ids because placeholder=True dimensions are not stale -- requirement 4).
Both must run before auto_cluster_findings because the cluster algorithm reads queue_order to find subjective::* IDs.
5. What about _MIN_CLUSTER_SIZE for initial review?
Yes, 1 unscored dimension should create a cluster. The rationale: the initial review is a special onboarding step. Even a single unscored dimension represents actionable work the user needs to do before their scorecard is meaningful. The _MIN_CLUSTER_SIZE = 2 threshold exists for objective findings (where singletons are better shown individually), but initial review is semantically a batch operation regardless of count.
Implementation: use _MIN_UNSCORED_CLUSTER_SIZE = 1 as a separate constant, applied only to the auto/initial-review cluster logic in auto_cluster_findings.
6. How does queue ordering work end-to-end?
Full flow after scan:
sync_unscored_dimensions(plan, state) -- Finds dimensions where placeholder=True via scorecard_subjective_entries. Generates subjective::<slug> IDs. Prepends them to queue_order[0:0] (front). Prunes any subjective::* IDs that are no longer unscored (user reviewed them). Returns UnscoredDimensionSyncResult with injected and pruned lists.
sync_stale_dimensions(plan, state) -- Existing logic unchanged. Finds dimensions where stale=True. Since unscored IDs are NOT stale (disjoint, requirement 4), _current_stale_ids will not return them. The cleanup pass removes any subjective::* ID not in the stale set AND not in the unscored set (we need a small adjustment: the cleanup pass currently removes any subjective::* not in stale_ids, but after this change we must also exclude unscored IDs from pruning).
Wait -- this is a subtle interaction. The existing cleanup in sync_stale_dimensions at line 68-74 removes subjective::* IDs that are NOT in stale_ids. If an unscored ID was just prepended by sync_unscored_dimensions, the stale cleanup would prune it because it is not in stale_ids.
Fix:sync_stale_dimensions needs to know which IDs are unscored so it does not prune them. Options:
(A) Pass the unscored set explicitly.
(B) Have sync_stale_dimensions also compute the unscored set and exclude those from pruning.
(C) Refactor to have one function that computes both sets and handles cleanup holistically.
Best approach: (B). Have sync_stale_dimensions call a helper _current_unscored_ids(state) and exclude those from the prune set. This keeps the two sync functions independent (no parameter coupling) while preventing the prune-collision. Since _current_unscored_ids is cheap (same scorecard_subjective_entries call, just filtering on placeholder instead of stale), the duplication is minimal.
auto_cluster_findings(plan, state) -- Partitions subjective::* IDs from queue_order into unscored vs stale by checking state. Creates auto/initial-review cluster for unscored (min size 1), for stale (min size 2).
7. Edge cases:
Partial reviews: If the user reviews 2 of 5 unscored dimensions, the next scan's sync_unscored_dimensions will only inject the remaining 3 (those still placeholder=True). The reviewed ones get pruned.
Re-scans: Each scan is idempotent. sync_unscored_dimensions prunes already-reviewed IDs and only injects those still unscored. No duplicate injection because existing IDs are checked before prepending.
Language with no subjective dims: scorecard_subjective_entries returns an empty list. Both sync functions return changes=0. No cluster created. No-op.
First scan ever (no prior state): All subjective dimensions start as placeholder=True. All get injected at front. This is the primary use case.
--reset-subjective flag: This explicitly sets placeholder=True on all dimensions (see _reset_subjective_assessments_for_scan_reset at line 176 of scan_workflow.py). After reset, all dims would be unscored again, which is correct -- the user asked for a fresh start.
Stale + unscored collision (should not happen by requirement 4): A dimension cannot be both placeholder=True and stale=True simultaneously. The stale field requires needs_review_refresh=True on the assessment, which is only set for previously-scored dimensions. placeholder=True means never scored. So they are truly disjoint by data model.
User manually moves a subjective::* ID to a different queue position or skips it: The sync functions respect existing IDs (they check existing = set(order) before inserting). If the ID is already in queue_order, it will not be re-added. If it is in skipped, it stays skipped and is not re-injected. This is correct -- user intent overrides automatic placement.
Add _current_unscored_ids function (parallel to _current_stale_ids):
python
def _current_unscored_ids(state: StateModel) -> set[str]:
"""Return the set of ``subjective::<slug>`` IDs that are currently unscored (placeholder)."""
from desloppify.engine._work_queue.helpers import slugify
from desloppify.engine.planning.scorecard_projection import (
scorecard_subjective_entries,
)
dim_scores = state.get("dimension_scores", {}) or {}
if not dim_scores:
return set()
unscored: set[str] = set()
for entry in scorecard_subjective_entries(state, dim_scores=dim_scores):
if not entry.get("placeholder"):
continue
dim_key = entry.get("dimension_key", "")
if dim_key:
unscored.add(f"{SUBJECTIVE_PREFIX}{slugify(dim_key)}")
return unscored
Add UnscoredDimensionSyncResult dataclass (parallel to StaleDimensionSyncResult):
python
@dataclass
class UnscoredDimensionSyncResult:
"""What changed during an unscored-dimension sync."""
injected: list[str] = field(default_factory=list)
pruned: list[str] = field(default_factory=list)
@property
def changes(self) -> int:
return len(self.injected) + len(self.pruned)
Add sync_unscored_dimensions function:
python
def sync_unscored_dimensions(
plan: PlanModel,
state: StateModel,
) -> UnscoredDimensionSyncResult:
"""Sync unscored (placeholder) subjective dimensions into the plan queue.
1. Remove ``subjective::*`` IDs from queue_order that are no longer unscored.
2. Prepend any currently-unscored dimension IDs to the FRONT of queue_order.
Unlike stale sync, injection is unconditional (not gated on queue emptiness).
"""
ensure_plan_defaults(plan)
result = UnscoredDimensionSyncResult()
unscored_ids = _current_unscored_ids(state)
stale_ids = _current_stale_ids(state) # Need this to avoid pruning stale IDs
order: list[str] = plan["queue_order"]
# --- Cleanup: prune subjective IDs that are no longer unscored AND not stale
# (Don't prune stale IDs here -- that's sync_stale_dimensions' job)
to_remove: list[str] = [
fid for fid in order
if fid.startswith(SUBJECTIVE_PREFIX)
and fid not in unscored_ids
and fid not in stale_ids
]
for fid in to_remove:
order.remove(fid)
result.pruned.append(fid)
# --- Inject: prepend unscored IDs to front of queue
existing = set(order)
to_inject = sorted(uid for uid in unscored_ids if uid not in existing)
for uid in reversed(to_inject): # reversed so first alphabetically ends up at index 0
order.insert(0, uid)
result.injected.append(uid)
return result
Modify sync_stale_dimensions: Update the cleanup logic to not prune unscored IDs. Change line 68-71 from:
python
to_remove: list[str] = [
fid for fid in order
if fid.startswith(SUBJECTIVE_PREFIX) and fid not in stale_ids
]
to:
python
unscored_ids = _current_unscored_ids(state)
to_remove: list[str] = [
fid for fid in order
if fid.startswith(SUBJECTIVE_PREFIX)
and fid not in stale_ids
and fid not in unscored_ids
]
Add unscored cluster logic in auto_cluster_findings, immediately after the stale cluster block (line 337-383). The new block:
python
# --- Unscored (initial review) subjective dimension cluster ---------------
# Partition subjective IDs into unscored vs stale using state
from desloppify.engine._plan.stale_dimensions import _current_unscored_ids
unscored_state_ids = _current_unscored_ids(state)
unscored_queue_ids = sorted(
fid for fid in plan.get("queue_order", [])
if fid.startswith(SUBJECTIVE_PREFIX) and fid in unscored_state_ids
)
if len(unscored_queue_ids) >= _MIN_UNSCORED_CLUSTER_SIZE:
active_auto_keys.add(_UNSCORED_KEY)
cli_keys = [fid.removeprefix(SUBJECTIVE_PREFIX) for fid in unscored_queue_ids]
description = f"Initial review of {len(unscored_queue_ids)} unscored subjective dimension{'s' if len(unscored_queue_ids) != 1 else ''}"
action = f"desloppify review --prepare --dimensions {','.join(cli_keys)}"
existing_name = existing_by_key.get(_UNSCORED_KEY)
if existing_name and existing_name in clusters:
cluster = clusters[existing_name]
old_ids = set(cluster.get("finding_ids", []))
new_ids = set(unscored_queue_ids)
if old_ids != new_ids or cluster.get("description") != description or cluster.get("action") != action:
cluster["finding_ids"] = unscored_queue_ids
cluster["description"] = description
cluster["action"] = action
cluster["updated_at"] = now
changes += 1
else:
clusters[_UNSCORED_NAME] = {
"name": _UNSCORED_NAME,
"description": description,
"finding_ids": unscored_queue_ids,
"created_at": now,
"updated_at": now,
"auto": True,
"cluster_key": _UNSCORED_KEY,
"action": action,
"user_modified": False,
}
existing_by_key[_UNSCORED_KEY] = _UNSCORED_NAME
changes += 1
# Track cluster membership in overrides
overrides = plan.get("overrides", {})
current_name = existing_by_key.get(_UNSCORED_KEY, _UNSCORED_NAME)
for fid in unscored_queue_ids:
if fid not in overrides:
overrides[fid] = {"finding_id": fid, "created_at": now}
overrides[fid]["cluster"] = current_name
overrides[fid]["updated_at"] = now
Modify the stale cluster block: Filter OUT unscored IDs from the stale set. Change line 338-341:
python
subjective_ids = sorted(
fid for fid in plan.get("queue_order", [])
if fid.startswith(SUBJECTIVE_PREFIX)
)
to:
python
# Exclude unscored IDs from stale cluster (they go in auto/initial-review)
stale_subjective_ids = sorted(
fid for fid in plan.get("queue_order", [])
if fid.startswith(SUBJECTIVE_PREFIX) and fid not in unscored_state_ids
)
And update all references from subjective_ids to stale_subjective_ids in the stale block.
Note on ordering: The unscored cluster block must execute BEFORE the stale block, because we need unscored_state_ids to be computed for the stale block to exclude them.
# --- stale dimensions -------------------------------------------------------
from desloppify.engine._plan.stale_dimensions import (
StaleDimensionSyncResult,
UnscoredDimensionSyncResult, # NEW
sync_stale_dimensions,
sync_unscored_dimensions, # NEW
)
Update __all__:
python
# stale dimensions
"StaleDimensionSyncResult",
"UnscoredDimensionSyncResult", # NEW
"sync_stale_dimensions",
"sync_unscored_dimensions", # NEW
def test_initial_review_cluster_created():
"""Unscored dims in queue create an auto/initial-review cluster."""
from desloppify.engine._plan.auto_cluster import auto_cluster_findings
plan = empty_plan()
plan["queue_order"] = ["subjective::design_coherence", "subjective::error_consistency"]
# State with placeholder=True (unscored)
state = {
"findings": {},
"scan_count": 1,
"dimension_scores": {
"design_coherence": {"score": 0, "strict": 0, "checks": 0, "issues": 0,
"detectors": {"subjective_assessment": {"[REDACTED], "placeholder": True}}},
"error_consistency": {"score": 0, "strict": 0, "checks": 0, "issues": 0,
"detectors": {"subjective_assessment": {"[REDACTED], "placeholder": True}}},
},
"subjective_assessments": {
"design_coherence": {"score": 0, "placeholder": True},
"error_consistency": {"score": 0, "placeholder": True},
},
}
changes = auto_cluster_findings(plan, state)
assert changes >= 1
assert "auto/initial-review" in plan["clusters"]
cluster = plan["clusters"]["auto/initial-review"]
assert cluster["auto"] is True
assert cluster["cluster_key"] == "subjective::unscored"
assert "Initial review" in cluster["description"]
def test_single_unscored_dim_creates_cluster():
"""Even 1 unscored dim creates a cluster (unlike stale which needs 2)."""
from desloppify.engine._plan.auto_cluster import auto_cluster_findings
plan = empty_plan()
plan["queue_order"] = ["subjective::design_coherence"]
state = {
"findings": {},
"scan_count": 1,
"dimension_scores": {
"design_coherence": {"score": 0, "strict": 0, "checks": 0, "issues": 0,
"detectors": {"subjective_assessment": {"[REDACTED], "placeholder": True}}},
},
"subjective_assessments": {"design_coherence": {"score": 0, "placeholder": True}},
}
changes = auto_cluster_findings(plan, state)
assert "auto/initial-review" in plan["clusters"]
Summary of Call Sequence After Implementation
code
merge_scan_results
|
+-- reconcile_plan_after_scan(plan, state)
| Removes dead finding IDs from plan. Skips subjective:: IDs.
|
+-- sync_unscored_dimensions(plan, state) # NEW
| Prunes reviewed dims. Prepends unscored dims to queue FRONT.
|
+-- sync_stale_dimensions(plan, state)
| Prunes refreshed stale dims (excluding unscored).
| Appends stale dims to queue BACK (only if no objective items).
|
+-- auto_cluster_findings(plan, state)
Partitions subjective::* IDs into unscored vs stale.
Creates auto/initial-review (min 1) and auto/stale-review (min 2).
Creates auto-clusters for objective findings.
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/stale_dimensions.py - Core logic: add _current_unscored_ids, sync_unscored_dimensions, and modify sync_stale_dimensions cleanup to exclude unscored IDs
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/auto_cluster.py - Add auto/initial-review cluster logic, partition subjective IDs into unscored vs stale sets
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_workflow.py - Orchestration: add sync_unscored_dimensions call in the correct position between reconcile and stale sync
/Users/user_c042661f/Documents/desloppify/desloppify/engine/plan.py - Facade: re-export new types and function
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next_parts/render.py - Rendering: add special label for auto/initial-review cluster
Computes tier_counts(all_items) — count of items at each tier
If specific tier requested but has 0 items:
Tries to fall back to nearest non-empty tier via choose_fallback_tier
Sets fallback_reason message
Otherwise, filters to requested tier
Limit count and add explanations (lines 346-352)
Slices to count items
If explain=True, adds explain dict to each item via item_explain(item)
Return WorkQueueResult (lines 354-364)
Returns dict with:
items — the filtered/sorted items
total — total items before count limit
tier_counts — counts at each tier
requested_tier, selected_tier, fallback_reason
available_tiers — tiers with non-zero count
grouped — items grouped for alternate output modes
auto/stale-review
_apply_plan_order(items, plan) in core.py -- At build_work_queue time: items in queue_order appear first. Since unscored IDs are at the front of queue_order, they get position 1, 2, etc.
_collapse_clusters(items, plan) -- Replaces individual subjective items belonging to auto/initial-review with a single cluster meta-item. The sort key for clusters is (0, action_priority, ...), so all clusters sort before all individual findings.
Rendering in next -- _render_cluster_item displays the cluster with its label. For auto/initial-review, we override the label to "Initial subjective review" instead of "Grouped task".
# Helper for unscored state
def _state_with_unscored_dimensions(*dim_keys: str) -> dict:
"""Build a minimal state with unscored (placeholder) subjective dimensions."""
dim_scores: dict = {}
assessments: dict = {}
for dim_key in dim_keys:
dim_scores[dim_key] = {
"score": 0.0,
"strict": 0.0,
"checks": 0,
"issues": 0,
"detectors": {
"subjective_assessment": {
"dimension_key": dim_key,
"placeholder": True,
}
},
}
assessments[dim_key] = {
"score": 0.0,
"source": "scan_reset_subjective",
"placeholder": True,
}
return {
"findings": {},
"scan_count": 1,
"dimension_scores": dim_scores,
"subjective_assessments": assessments,
}
def test_unscored_injected_at_front():
plan = _plan_with_queue("some_finding::file.py::abc123")
state = _state_with_unscored_dimensions("design_coherence", "error_consistency")
result = sync_unscored_dimensions(plan, state)
assert len(result.injected) == 2
# Unscored IDs at FRONT, existing finding at back
assert plan["queue_order"][-1] == "some_finding::file.py::abc123"
assert plan["queue_order"][0].startswith("subjective::")
assert plan["queue_order"][1].startswith("subjective::")
def test_unscored_injection_unconditional():
"""Unlike stale, unscored injects even when objective items exist."""
plan = _plan_with_queue("real_finding::x.py::abc")
state = _state_with_unscored_dimensions("design_coherence")
result = sync_unscored_dimensions(plan, state)
assert len(result.injected) == 1
assert "subjective::design_coherence" in plan["queue_order"]
def test_unscored_pruned_after_review():
plan = _plan_with_queue("subjective::design_coherence")
# State no longer has placeholder=True for design_coherence
state = _state_with_stale_dimensions() # empty stale set
state["dimension_scores"] = {} # no unscored either
result = sync_unscored_dimensions(plan, state)
assert "subjective::design_coherence" in result.pruned
def test_stale_sync_does_not_prune_unscored_ids():
"""sync_stale_dimensions must not prune IDs that are unscored."""
plan = _plan_with_queue("subjective::design_coherence")
state = _state_with_unscored_dimensions("design_coherence")
result = sync_stale_dimensions(plan, state)
assert "subjective::design_coherence" not in result.pruned
assert "subjective::design_coherence" in plan["queue_order"]
def test_unscored_and_stale_are_disjoint():
"""A dimension cannot be both unscored and stale."""
plan = _plan_with_queue()
# Build state with one unscored AND one stale
dim_scores = {}
assessments = {}
# Unscored dimension
dim_scores["design_coherence"] = {
"score": 0.0, "strict": 0.0, "checks": 0, "issues": 0,
"detectors": {"subjective_assessment": {"[REDACTED], "placeholder": True}},
}
assessments["design_coherence"] = {"score": 0.0, "placeholder": True}
# Stale dimension
dim_scores["error_consistency"] = {
"score": 50.0, "strict": 50.0, "checks": 1, "issues": 0,
"detectors": {"subjective_assessment": {"[REDACTED], "placeholder": False}},
}
assessments["error_consistency"] = {"score": 50.0, "needs_review_refresh": True}
state = {"findings": {}, "scan_count": 5, "dimension_scores": dim_scores, "subjective_assessments": assessments}
# Run both syncs in correct order
r1 = sync_unscored_dimensions(plan, state)
r2 = sync_stale_dimensions(plan, state)
# design_coherence should be at front (unscored), error_consistency should not be injected (has_real_items is False BUT only subjective in queue)
assert "subjective::design_coherence" in r1.injected
# Note: stale injection only happens when no real items exist, and "subjective::design_coherence" is not a "real" item