I need to understand how subjective dimension reviews flow through the queue system in this codebase. The goal: when there are unassessed subjective dimensions, they should appear at the TOP of the work queue, and all other items should be hidden until they're completed.
Please find and read these key files/functions thoroughly:
desloppify/engine/_work_queue/core.py — especially build_work_queue() and any subjective-related logic
desloppify/engine/_work_queue/helpers.py — especially build_subjective_items() and scorecard_subjective_entries()
desloppify/engine/_work_queue/ranking.py — cluster sort order, especially how manual_fix is ranked
desloppify/engine/_plan/stale_dimensions.py — especially sync_unscored_dimensions() and the "stale reviews only after queue clear" logic
desloppify/engine/_plan/auto_cluster.py — especially auto_cluster_findings() and how auto/initial-review cluster is built
desloppify/intelligence/narrative/dimensions.py — especially scorecard_subjective_entries() and how unassessed placeholders are filtered
desloppify/engine/planning/queue_policy.py — any queue gating/policy logic
desloppify/core/subjective_dimensions.py — the subjective dimensions definitions
For each file, read the FULL content. I need to understand:
How subjective dimensions are defined and tracked
How they enter (or fail to enter) the queue
How the queue is sorted/gated
Where the "initial review" blocking behavior is supposed to happen
Be very thorough - read every relevant file completely.
Assistant
I'll read all these files in parallel to understand the full flow.
Assistant
Now let me read the remaining key files that are referenced by these: the scorecard_subjective_entries function (imported from scorecard_projection), the unassessed_subjective_dimensions function from intelligence/integrity, and the scorecard_subjective_entries in narrative/dimensions.py (which seems to be in scorecard_projection now).
Assistant
Now let me read the scorecard_dimension_rows function which is the core of scorecard_subjective_entries, and also check how the plan reconciliation calls these sync functions.
Assistant
Now let me check the reconcile module to see how sync functions are called during scan, and the _plan/reconcile.py file.
Assistant
Now let me also check the _apply_subjective_interleave_guardrail behavior and look at how the next command uses the queue, specifically looking for any "initial review blocking" or gating logic.
Assistant
Now let me check the review preflight which is the gating mechanism for reviews, and the guardrails.py file which may contain additional queue gating.
Assistant
Now I have a complete picture. Let me also quickly check the scorecard_policy.py file that was mentioned and is referenced for queue gating — it's already been read above. Let me also read the _filtering.py file since it was modified and check if there's any filtering logic related to subjective items.
Assistant
User
Read the file desloppify/app/output/scorecard_parts/dimensions.py completely. I need to understand why prepare_scorecard_dimensions() only returns 5 mechanical dimension rows and does NOT include subjective dimensions (like "Naming quality", "Logic clarity", etc.) even though they exist in dimension_scores. Check if it filters them out intentionally. Be quick - read the whole file.
Assistant
I found it. The function prepare_scorecard_dimensions()does NOT intentionally filter out subjective dimensions. Here's what actually happens:
The filtering logic (lines 218-222):
python
active_dims = [
(name, data)
for name, data in all_dims
if data.get("checks", 0) > 0 and not is_unassessed_subjective_placeholder(data)
]
This excludes dimensions if:
checks count is 0 or missing (line 221: data.get("checks", 0) > 0)
They are unassessed subjective placeholders (line 221: not is_unassessed_subjective_placeholder(data))
User
I need to understand how the desloppify queue surfaces handle phased prompting and coaching. Please read these files thoroughly:
desloppify/engine/_work_queue/core.py — the full file, especially build_work_queue() and its return type WorkQueueResult
desloppify/app/commands/next.py — how does the next command consume the queue result and display it?
desloppify/app/commands/next_parts/render.py — rendering for next command
desloppify/app/commands/status_cmd.py — how status command uses the queue
desloppify/app/commands/status_parts/render.py — status rendering
desloppify/engine/_plan/stale_dimensions.py — the sync_stale_dimensions function, specifically the "no objective items remain" check at line ~200
I need to understand:
What data build_work_queue returns and how consumers use it
How/where coaching messages are shown (e.g. "run a scan", nudges)
How the stale dimension "only after queue clears" logic works
Where would be the cleanest place to add phase-gating behavior
Be very thorough.
Assistant
I'll read all the requested files in parallel to get a comprehensive understanding.
Assistant
Now let me also read the supporting files that are referenced to understand the full coaching/nudge pipeline.
Assistant
Now let me also look at the rendering helper and the build_finding_items function in ranking.py to understand how objective items are built.
Assistant
User
Assistant
I'll explore the codebase thoroughly to understand the current architecture before designing the plan.
Assistant
Now let me read the rendering and command files to understand how the queue is consumed.
Assistant
Now let me look at a few more key files: the plan command, the queue progress helpers, and the status render module.
Assistant
Let me also look at the scan workflow to understand where reconciliation happens, and check the status render module and the _plan/schema.py.
Assistant
Now let me look at the remaining parts of the scan workflow (the reconciliation portion) and a few more supporting files.
Assistant
Let me check the _work_queue/ranking.py to understand the sort key logic and how initial_review items sort, and also look at the next_parts/output.py.
Assistant
Now let me check how _current_unscored_ids is used in the existing codebase, and look at the intelligence/integrity module to understand unassessed_subjective_dimensions.
Assistant
Let me also check the auto-cluster code since it already creates an auto/initial-review cluster, and look at the existing test for this.
Assistant
Excellent. Now I have a thorough understanding of the codebase. Let me check one more thing -- the _state/filtering.py which is modified on the branch and may contain relevant phase logic.
Assistant
Good. There is no existing QueuePhase concept. This is a completely new feature. I now have a complete picture. Let me also check what WorkQueueResult currently contains to understand what fields are already flowed through.
Assistant
Now I have a thorough understanding of the complete flow. Here is my analysis:
Subjective dimensions are defined via a metadata system. The canonical list lives in DISPLAY_NAMES (lines 20-44), mapping internal keys like "cross_module_architecture" to display labels like "Cross-module arch". There are roughly 20 dimensions covering holistic concerns (architecture, elegance, test strategy, etc.) and per-file concerns (naming quality, logic clarity, type safety, contracts).
Each dimension has metadata including:
display_name (human-readable label)
weight (for score aggregation, from _LEGACY_SUBJECTIVE_WEIGHTS_BY_DISPLAY)
enabled_by_default (whether it's active without explicit opt-in)
reset_on_scan (whether scores get reset when a new scan runs)
The metadata is loaded from prompt files via _load_dimensions_payload() and _load_dimensions_payload_for_lang(), with legacy hardcoded fallbacks. The load_subjective_dimension_metadata() function merges shared + per-language metadata with LRU caching.
2. How Subjective Dimensions Are Tracked in State
Subjective dimension scores live in two places in state:
state["dimension_scores"] — the full scorecard, with entries like {"score": 75.0, "strict": 72.0, "issues": 3, "checks": 10, "detectors": {"subjective_assessment": {...}}}
state["subjective_assessments"] — raw assessment records per dimension key, where payload.get("placeholder") marks dimensions that have never been reviewed
An "unassessed" dimension is one where either:
The subjective_assessment detector metadata has "placeholder": True, OR
The strict score is 0.0 and there are 0 issues (line 109-111 of integrity.py)
File: /Users/user_c042661f/Documents/desloppify/desloppify/intelligence/integrity.py, function unassessed_subjective_dimensions() (lines 95-115):
python
def unassessed_subjective_dimensions(dim_scores: dict | None) -> list[str]:
"""Return subjective dimension display names that are still 0% placeholders."""
for name, info in dim_scores.items():
detectors = info.get("detectors", {})
if "subjective_assessment" not in detectors:
continue
assessment_meta = detectors.get("subjective_assessment", {})
if isinstance(assessment_meta, dict) and assessment_meta.get("placeholder"):
unassessed.append(name)
continue
strict_val = float(info.get("strict", info.get("score", 100.0)))
issues = int(info.get("issues", 0))
if strict_val <= 0.0 and issues == 0:
unassessed.append(name)
3. How Subjective Dimensions Enter the Queue
There are two parallel paths for getting subjective items into the work queue:
During scan workflow (scan_workflow.py, lines 196-206), three sync functions run in sequence:
sync_unscored_dimensions(plan, state) (lines 124-162) — This is the "initial review" path:
Looks up state["subjective_assessments"] for entries with "placeholder": True
Generates IDs like subjective::design_coherence
Prunes any subjective::* IDs from queue_order that are no longer unscored AND not stale
Prepends unscored IDs to the front of queue_order (after any promoted items)
This ensures unscored dimensions appear first in plan ordering
sync_stale_dimensions(plan, state) (lines 169-208) — This is the "re-review" path:
Looks up scorecard_subjective_entries() for entries with "stale": True (the needs_review_refresh flag)
Only injects stale IDs when no objective items remain in the queue (line 200: has_real_items = any(fid for fid in order if not fid.startswith(SUBJECTIVE_PREFIX)))
The function build_subjective_items() (lines 239-352) creates synthetic queue items at build time:
Calls scorecard_subjective_entries() to get all subjective dimension data
Calls unassessed_subjective_dimensions() to identify placeholders
For each subjective entry below the threshold score:
Determines if it's is_unassessed (placeholder, or in unassessed_dims, or score=0 with 0 issues)
Determines if it's is_stale (needs_review_refresh flag)
Sets is_backlog_gated = open_review == 0 and not is_unassessed — meaning unassessed items are NEVER backlog-gated, but re-review items with no existing review findings ARE gated
Creates items with kind: "subjective_dimension" and IDs like subjective::design_coherence
This is the canonical source for which dimensions are "subjective" and their current scores:
python
def scorecard_subjective_entries(state, *, dim_scores=None):
rows = scorecard_dimension_rows(state, dim_scores=dim_scores)
# ...
for name, data in rows:
is_subjective = ("subjective_assessment" in detectors
or lowered_name in subjective_display_names)
if not is_subjective:
continue
placeholder = bool(
assessment_meta.get("placeholder")
or (data.get("score", 0) == 0
and data.get("issues", 0) == 0
and data.get("checks", 0) == 0)
)
Critical detail: The placeholder flag is set when either the detector metadata says so, or when score/issues/checks are all zero. The stale flag is set when assessments[dim_key].get("needs_review_refresh") is truthy.
The item_sort_key() function (lines 83-119) determines the mechanical sort order:
python
def item_sort_key(item):
if item.get("kind") == "synthesis_needed":
return (-1, 0, 0, ...) # Always first
if item.get("kind") == "cluster":
return (0, action_priority, -member_count, ...) # Second
if item.get("kind") == "subjective_dimension" or item.get("is_subjective"):
return (1, 1, subjective_score_value, ...) # After mechanical findings
# Regular findings:
return (1, 0, confidence_order, ...) # Before subjective at same level
Key insight: In the mechanical sort, subjective items sort AFTER regular findings. The tuple (1, 1, ...) sorts after (1, 0, ...). This means by default, all mechanical/objective findings appear before any subjective work.
Build finding items (mechanical findings from state)
Build subjective items (synthetic items from build_subjective_items())
Backlog gating (lines 343-345): Items with backlog_gated=True are suppressed when has_objective_backlog is true. But unassessed items are never backlog_gated (see helpers.py line 307: is_backlog_gated = open_review == 0 and not is_unassessed).
Sort by item_sort_key — puts subjective items after mechanical items
Apply plan order via _apply_plan_order() — this reorders items based on plan["queue_order"], which has unscored IDs prepended to the front by sync_unscored_dimensions()
Collapse clusters — may merge subjective items into auto/initial-review cluster
Interleave via _apply_subjective_interleave_guardrail() — alternates 3 objective, 1 subjective to prevent starvation
The auto_cluster_findings() function creates two special clusters:
auto/initial-review (cluster_key: subjective::unscored) — groups ALL unscored subjective dimensions. Minimum size is 1 (not 2 like other clusters). These are the "never reviewed" dimensions.
auto/stale-review (cluster_key: subjective::stale) — groups stale (previously scored but outdated) dimensions. Minimum size is 2.
8. Where the "Initial Review Blocking" Behavior Should Happen (and the Gap)
The design intent is clear from the code:
Intent: Unscored (placeholder) subjective dimensions should appear at the TOP of the work queue.
How it's implemented:
sync_unscored_dimensions()prepends unscored IDs to plan["queue_order"] — this puts them first in the plan ordering
_apply_plan_order() in core.py reorders items so that anything in queue_order appears first, in order
Unassessed items are never backlog_gated — they always pass through
The auto/initial-review cluster groups them for a single action
However, there is NO explicit "hide all other items" behavior. Here is the gap:
The interleave guardrail (_apply_subjective_interleave_guardrail) actually works in the opposite direction — it intersperses objective items between subjective items (3 objective, then 1 subjective). This would dilute the "initial review first" intent.
When collapse_clusters is active and there's an auto/initial-review cluster, the cluster item goes through item_sort_key() which gives clusters sort key (0, ...) — meaning clusters sort before individual findings (1, ...). So the auto/initial-review cluster would appear first.
But if clusters are NOT collapsed (e.g., when drilling into a specific cluster, or when the plan order is applied), individual subjective_dimension items sort with key (1, 1, ...) which is AFTER mechanical findings (1, 0, ...).
The plan order (_apply_plan_order()) overrides the mechanical sort for items in queue_order, so unscored items prepended to the front DO appear first. But the interleave guardrail runs AFTER plan ordering and can shuffle them.
Summary of the current behavior:
Scenario
Unscored items position
Other items hidden?
With plan + cluster collapse
auto/initial-review cluster sorts first (key (0, ...))
No, other items visible below
With plan, no cluster collapse
Plan order puts them first, but interleave may shuffle
No
Without plan
Mechanical sort puts them AFTER objective findings
No
count=1 (default next)
First item from the sorted/ordered list
Yes, by virtue of count=1
The "hide all other items until completed" behavior does NOT currently exist. The closest mechanism is:
Plan ordering prepends unscored to front
count=1 in the default next command means only the top item shows
The auto/initial-review cluster collapses them into a single meta-item that sorts before individual findings
But if you ask for count=10 or use status or plan queue, all items are visible. There is no queue-level gating that suppresses non-subjective items when unassessed dimensions exist. The backlog_gated mechanism works in the reverse direction — it suppresses stale subjective re-review items while objective backlog exists, not the other way around.
The placeholder check (lines 66-71):
python
def is_unassessed_subjective_placeholder(data: dict) -> bool:
return (
"subjective_assessment" in data.get("detectors", {})
and data.get("score", 0) == 0
and data.get("issues", 0) == 0
)
The reason you're only seeing 5 mechanical rows: Subjective dimensions like "Naming quality" and "Logic clarity" are likely being filtered out because:
They don't have checks > 0, OR
They match the placeholder condition (score=0, issues=0, has subjective_assessment detector)
Then, limit_scorecard_dimensions() (lines 146-195) applies a hard cap (default 5 rows from SCORECARD_MAX_DIMENSIONS) that prioritizes mechanical dimensions first (lines 156-167), only including subjective dimensions if there's room in the budget.
Bottom line: It's intentional filtering, but it's data-driven, not name-driven. Subjective dimensions are included IF they have real data (checks > 0) and pass the placeholder check, then they compete for the remaining slots after mechanical dimensions are included.
Now I have a thorough understanding of all the files. Here is my comprehensive analysis:
Comprehensive Analysis: Queue Surfaces, Coaching, and Phase-Gating
The new_ids field (a set[str]) is present in the return value but is not declared in WorkQueueResult. This is a TypedDict discrepancy (not a runtime problem since it's a dict).
Item kinds in the queue:
There are four distinct kind values that can appear in items:
"finding" -- regular mechanical findings, built by build_finding_items() in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/ranking.py (line 28-77)
"subjective_dimension" -- synthetic items for subjective dimensions below the threshold, built by build_subjective_items() in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/helpers.py (line 274-402)
"synthesis_needed" -- a synthetic T1 blocking item for synthesis::pending, built by build_synthesis_item() in helpers.py (line 171-209)
"cluster" -- meta-items that collapse auto-clusters, built by _collapse_clusters() in core.py (line 217-296)
Pipeline within build_work_queue (line 299-402):
Build finding items from state (build_finding_items)
Record has_objective_backlog = whether any finding items exist (line 325)
If subjective is included and status is open/all, build subjective items; suppress backlog_gated ones while objective backlog exists (line 343)
Inject synthesis item if plan demands it (line 349-352)
Sort all items by item_sort_key (line 354)
Apply plan ordering if plan exists (line 357-366)
Collapse auto-clusters into meta-items (line 368-376)
Computes narrative via compute_narrative() (line 222-224)
Builds the JSON payload and writes to query.json (line 225-232)
If non-terminal output requested (JSON, markdown, file), emits and returns (line 234-235)
Extracts frozen plan-start score and queue breakdown (line 238-242)
Renders the queue header (line 244): render_queue_header shows "Queue: N items"
Checks for empty queue (line 246-252): show_empty_queue prints "Queue cleared!" with before/after comparison if plan_start_strict is available, or "Nothing to do!" otherwise
Renders items (line 261-265): render_terminal_items renders the actual cards
Resolution hint (line 266): render_single_item_resolution_hint
Follow-up nudges (line 267-276): render_followup_nudges -- the main coaching block
3. Where Coaching Messages Are Shown
Coaching is layered across multiple locations. Here is the complete map:
A. Pre-Command Banners (shown before queue content)
print_synthesis_guardrail_info() (line 51-72): Yellow info banner showing "N new review findings not yet triaged" and the synthesis phase banner. Called at the top of both cmd_next (line 88) and cmd_status (line 106).
require_synthesis_current_or_exit() (line 75-117): Hard blocker that exits with code 1 if synthesis is stale and not bypassed. This is the strictest phase gate -- used by resolve/done commands (not next/status).
Tool/skill/config staleness -- Both cmd_next (lines 78-86) and cmd_status (lines 83-91) print yellow warnings for stale tools, stale SKILL.md, or stale config.
When queue is empty and plan_start_strict is available: "Queue cleared!" with frozen-start vs. live-estimate comparison, plus "Run desloppify scan now to finalize"
When queue is empty without plan context: "Nothing to do!" with strict score
This is the richest coaching surface. It contains these coaching layers in order:
Frozen score + queue progress block (lines 494-517): When plan_start_strict is available and queue is not empty, shows the frozen score and queue breakdown with "Score will not update until the queue is clear and you run desloppify scan."
North star score gap (lines 518-533): When no frozen score, shows "strict X/100 -> target Y (+Z needed)" or "meets target"
Queue block without frozen score (lines 535-538): Shows format_queue_block when breakdown exists but no frozen score
Subjective bottleneck banner (lines 540-573): Only shown when _objective_remaining <= 0. This is a key phase-gating behavior. When the objective queue is clear, it computes whether subjective drag exceeds mechanical drag, and if so, surfaces "Subjective dimensions are the main bottleneck" with the review re-run command. The comment on line 542 explicitly states the design intent: "While objective items remain, the queue is the single authority on what to work on next; no need to distract with subjective advice."
Integrity lines (lines 576-577): Always shown (anti-gaming safeguard, must remain visible per code comment).
Rescan nudge (lines 580-585): When queue_total > 10, shows tip about rescanning after structural fixes.
Collapsed subjective summary (lines 587-612): Shows "Subjective: N dimensions below target, N stale, N unassessed..." with pointer to desloppify show subjective.
_render_dimension_legend() (line 290-324): Shows stale rerun command only when objective_backlog <= 0 (line 315). Same phase-gating pattern.
show_subjective_followup() (line 445-468): Delegates to print_subjective_followup() which gates quality nudges behind objective_backlog <= 0 (see subjective.py line 36).
4. The Stale Dimension "Only After Queue Clears" Logic
def sync_stale_dimensions(plan, state):
# Step 1: Prune resolved subjective IDs (no longer stale AND not unscored)
to_remove = [
fid for fid in order
if fid.startswith(SUBJECTIVE_PREFIX)
and fid not in stale_ids
and fid not in unscored_ids
]
# ... removes them ...
# Step 2: Inject only when no objective items remain
has_real_items = any(fid for fid in order if not fid.startswith(SUBJECTIVE_PREFIX))
if not has_real_items and stale_ids:
# ... append stale IDs to end of queue ...
The critical check is on line 223: has_real_items = any(fid for fid in order if not fid.startswith(SUBJECTIVE_PREFIX)). This checks the plan's queue_order list, not the live state. It considers any item in queue_order that does NOT have the subjective:: prefix to be a "real" (objective) item.
Only when has_real_items is False (meaning the queue_order contains zero non-subjective items) does the function inject stale dimension IDs. The stale IDs are appended to the end of queue_order (line 228: order.append(sid)).
Contrast with sync_unscored_dimensions() (line 147-185): Unscored dimensions are injected unconditionally at the front of the queue (after promoted items), regardless of whether objective items remain. This is because initial reviews are onboarding priority.
When is sync_stale_dimensions called? It would be called during reconciliation (after scan save, referenced in the architecture notes as scan_workflow.py).
5. Phase-Gating Behavior Across the Codebase
There are three distinct phase-gating mechanisms:
Gate
Where
Condition
Effect
Subjective suppression in queue builder
core.py:343
has_objective_backlog and item.get("backlog_gated")
Backlog-gated subjective items (those whose only action is --force-review-rerun) are excluded from queue
Subjective nudge suppression in next render
render.py:547
_objective_remaining <= 0
Subjective bottleneck banner only shown after all objective items cleared
Subjective followup gating in status
subjective.py:36
objective_backlog <= 0
Quality nudges suppressed while objective backlog exists
Stale dimension injection in plan sync
stale_dimensions.py:223
not has_real_items
Stale dimensions only injected into plan queue after all non-subjective items cleared
Stale rerun command in status dimension legend
status_parts/render.py:315
objective_backlog <= 0
Stale rerun command only shown when no objective backlog
Synthesis hard gate
guardrails.py:75-117
is_synthesis_stale(plan, state)
Blocks resolve/done commands entirely if synthesis is stale
6. Where Would Be the Cleanest Place to Add Phase-Gating Behavior
Based on this analysis, the architecture already has a clear pattern for phase-gating. Here are the cleanest insertion points, depending on what you want to gate:
A. If you want to gate what items appear in the queue itself:
The cleanest place is in build_work_queue() in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py, between the item collection step and the sort/plan-order step (around lines 324-354). This is where the existing has_objective_backlog suppression lives (line 343). Any new phase gate that decides "don't show item type X until condition Y" belongs here. The QueueBuildOptions dataclass (line 26-41) is the natural place to add new gating configuration.
B. If you want to gate what coaching/nudges are shown in the terminal:
The render_followup_nudges() function in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next_parts/render.py (line 467-613) is the single richest coaching surface. The existing _objective_remaining variable at line 543 already computes the objective backlog, and the subjective bottleneck banner at lines 547-573 demonstrates the pattern: check a condition, render coaching text. Adding a new coaching phase here follows the established pattern cleanly. The equivalent for status is show_subjective_followup() in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/status_parts/render.py (line 445-468) with its objective_backlog parameter.
C. If you want to gate what items the plan itself tracks:
The sync_stale_dimensions() function in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/stale_dimensions.py (line 192-231) is the model for plan-level phase gates. The pattern is: check a condition against queue_order contents, then conditionally inject/prune IDs. You'd add a sibling sync_* function following the same dataclass-result pattern (StaleDimensionSyncResult).
D. If you want a hard gate that blocks commands:
The require_synthesis_current_or_exit() pattern in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/guardrails.py (line 75-117) is the template. It checks a condition, prints a structured error, and calls sys.exit(1). New hard gates should live in this file as sibling functions.
E. If you want the phase information to flow through to query.json for LLM consumption:
The build_query_payload() function in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next_parts/output.py (line 64-107) builds the structured payload. A new "phase" or "phase_gate" key could be added here, derived from the same conditions used for terminal rendering. The _build_next_payload() wrapper in next.py (line 106-127) is where state-derived fields like scores and dimensions are merged in.
My recommendation for the cleanest single insertion point: The QueueBreakdown dataclass in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/queue_progress.py (line 16-27) is already computed by both next and status, and it already carries queue_total and subjective counts. Adding a phase field (or objective_remaining field) to QueueBreakdown would make phase information available to all consumers without changing the queue builder itself. Both render_followup_nudges and show_subjective_followup already receive the breakdown object, so they could branch on the phase field naturally. The format_queue_block function already uses the breakdown for display, so phase-specific messaging would flow through the same path.
Design an implementation plan for a phased onboarding flow in the desloppify work queue. Here's the context:
Problem
The work queue needs to enforce a phased progression:
Initial review phase: When unassessed subjective dimensions exist (placeholders), ONLY show those items. Hide everything else until all initial reviews are complete.
Plan-needed phase: Once all initial reviews are done, nudge the user to run desloppify plan to build their prioritized queue.
Working phase: Normal queue — show everything.
Stale review: Only prompt to redo stale subjective dimensions AFTER the user has gone through all queue items (queue clears). This already works via existing code.
Status command: desloppify/app/commands/status_cmd.py
Uses build_work_queue() for queue breakdown
Has its own coaching surfaces that gate stale dimension nudges behind objective_backlog <= 0
Requirements
The initial_review gate should ONLY apply when dimensions haven't been done yet (all placeholders). NOT when they're stale.
After initial reviews complete, prompt to run desloppify plan (the user needs to plan before seeing the full queue)
Stale review prompts only appear after queue clears — this already works
Should be "elegantly engineered" — clean phase detection, not scattered conditionals
Design Questions to Address
Where should phase detection live? (queue builder vs. rendering vs. separate function)
Should plan_needed phase also gate the queue (hide items) or just show a nudge?
How to detect "plan needed" — e.g., no unassessed dims AND queue_order has no non-subjective items AND objective findings exist?
How to flow phase info to all consumers (next, status, plan commands)?
Should there be a queue_phase field in the return dict?
Please design a concrete implementation plan with specific file changes, function signatures, and code structure.
Now I have a comprehensive understanding of the entire system. Let me design the implementation plan.
Implementation Plan: Phased Onboarding Flow in the Work Queue
Architecture Overview
The core idea is to introduce a QueuePhase enum that represents the current onboarding state, compute it once in a pure function, flow it through the existing WorkQueueResult TypedDict, and let the queue builder and rendering layers both react to it. This keeps phase detection centralized and avoids scattered conditionals.
Phase Definitions
python
# New enum
class QueuePhase(str, Enum):
INITIAL_REVIEW = "initial_review" # Unassessed subjective dims exist
PLAN_NEEDED = "plan_needed" # Reviews done, no plan built yet
WORKING = "working" # Normal queue with plan
STALE_REVIEW = "stale_review" # Queue cleared, stale dims surfaced
Design Decisions (Answering the Questions)
1. Where should phase detection live?
In a new pure function detect_queue_phase() inside /Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py. It belongs in the queue engine layer -- not in rendering, not in commands. The function takes state, plan, and has_objective_findings as inputs and returns a QueuePhase. This keeps the logic testable, centralized, and available to all consumers.
2. Should plan_needed phase gate the queue (hide items) or just show a nudge?
Just a nudge. The INITIAL_REVIEW phase should actively filter the queue to show only subjective review items. But PLAN_NEEDED should not hide items -- the user can still use next without a plan; we just strongly encourage planning. Hiding items at the plan_needed stage would be hostile to users who want to jump in. The gate only applies to the initial review phase where the user truly has no context yet.
3. How to detect "plan needed"?
The condition is:
No unassessed (placeholder) subjective dimensions exist (initial reviews are complete)
AND the plan has no meaningful queue_order (no non-subjective IDs in queue_order)
AND objective findings exist (there is work to plan)
AND no plan_start_scores are set (no plan cycle has begun)
This detects the gap between "you finished your initial reviews" and "you ran desloppify plan to build your prioritized queue."
4. How to flow phase info to all consumers?
Add a phase key to WorkQueueResult. Since WorkQueueResult is a TypedDict, adding phase: str is straightforward. The phase string is then available everywhere the queue result is used -- next, status, plan, query.json.
5. Should there be a queue_phase field in the return dict?
Yes, as phase in WorkQueueResult. Also propagate into the query.json payload so external tools (SKILL.md, agent integrations) can react to the phase.
Step-by-Step Implementation
Step 1: Add QueuePhase enum and detect_queue_phase() function
from enum import Enum
class QueuePhase(str, Enum):
"""Onboarding phase of the work queue."""
INITIAL_REVIEW = "initial_review"
PLAN_NEEDED = "plan_needed"
WORKING = "working"
STALE_REVIEW = "stale_review"
Add the detection function (pure, no side effects):
python
def detect_queue_phase(
*,
has_unassessed: bool,
has_objective_findings: bool,
plan: dict | None,
) -> QueuePhase:
"""Determine the current onboarding phase of the work queue.
Phase progression:
1. INITIAL_REVIEW — unassessed subjective dimensions exist (placeholders).
The queue is gated to show only those items.
2. PLAN_NEEDED — initial reviews complete, but no plan built yet.
Show a nudge to run ``desloppify plan``.
3. WORKING — normal queue operation.
4. STALE_REVIEW — queue cleared, stale dimensions surfaced.
(Already handled by existing stale_dimensions sync; included for completeness.)
"""
if has_unassessed:
return QueuePhase.INITIAL_REVIEW
if has_objective_findings and plan is not None:
queue_order = plan.get("queue_order", [])
has_plan_content = any(
fid for fid in queue_order
if not fid.startswith("subjective::")
and not fid.startswith("synthesis::")
)
has_plan_cycle = bool(plan.get("plan_start_scores"))
if not has_plan_content and not has_plan_cycle:
return QueuePhase.PLAN_NEEDED
# Check for stale review: no objective findings left, only subjective stale items
if not has_objective_findings and plan is not None:
queue_order = plan.get("queue_order", [])
only_stale_subjective = (
bool(queue_order)
and all(fid.startswith("subjective::") for fid in queue_order)
)
if only_stale_subjective:
return QueuePhase.STALE_REVIEW
return QueuePhase.WORKING
The key inputs are:
has_unassessed: derived from the subjective items built in build_work_queue() (check item.get("initial_review"))
has_objective_findings: the existing has_objective_backlog bool (line 325 of core.py)
plan: the plan dict already passed via QueueBuildOptions
Step 2: Update WorkQueueResult and build_work_queue()
class WorkQueueResult(TypedDict):
"""Typed shape of the dict returned by :func:`build_work_queue`."""
items: list[dict]
total: int
grouped: dict[str, list[dict]]
suppressed_count: int
new_ids: set[str] # already present in practice
phase: str # NEW: QueuePhase value
In build_work_queue(), after building subjective items and before the final return:
python
# Detect phase
has_unassessed = any(
item.get("initial_review") for item in all_items
if item.get("kind") == "subjective_dimension"
)
phase = detect_queue_phase(
has_unassessed=has_unassessed,
has_objective_findings=has_objective_backlog,
plan=resolved_options.plan,
)
# Gate: in INITIAL_REVIEW phase, filter queue to only show initial_review items
if phase == QueuePhase.INITIAL_REVIEW:
initial_items = [
item for item in all_items
if item.get("initial_review")
or item.get("kind") == "cluster" and item.get("id") == "auto/initial-review"
]
if initial_items:
all_items = initial_items
This filtering happens after the plan ordering and cluster collapsing, so if the auto/initial-review cluster is present, it gets shown. If not (no plan yet), the individual initial_review=True items show through.
@dataclass(frozen=True)
class QueueBreakdown:
queue_total: int = 0
plan_ordered: int = 0
skipped: int = 0
subjective: int = 0
suppressed: int = 0
focus_cluster: str | None = None
focus_cluster_count: int = 0
focus_cluster_total: int = 0
phase: str = "working" # NEW
In plan_aware_queue_breakdown(), capture the phase from the result:
def render_phase_banner(phase: str, queue_total: int) -> bool:
"""Render an onboarding phase banner above the queue. Returns True if shown."""
if phase == "initial_review":
print(colorize(
"\n INITIAL REVIEW — complete subjective assessments before seeing the full queue.",
"yellow",
))
print(colorize(
" These dimensions need your human judgment to calibrate the scoring model.",
"dim",
))
return True
if phase == "plan_needed":
print(colorize(
"\n Initial reviews complete. Run `desloppify plan` to build your prioritized queue.",
"cyan",
))
print(colorize(
" Planning organizes findings into clusters and lets you skip/defer items.",
"dim",
))
return True
return False
Update show_empty_queue() to handle the plan_needed phase when the queue appears empty (because everything was filtered out). Actually, the queue will not be empty in plan_needed -- objective items are still shown. But we need the banner to appear before the item list.
if _breakdown is not None:
if _breakdown.phase == "initial_review":
print(colorize(
"\n ACTION NEEDED: Complete initial subjective reviews before planning.",
"yellow",
))
print(colorize(
" Run: `desloppify next` to see what needs review.",
"dim",
))
elif _breakdown.phase == "plan_needed":
print(colorize(
"\n Initial reviews done! Run `desloppify plan` to build your prioritized queue.",
"cyan",
))
Step 6: Include phase in query.json and output payloads
Backward compatibility of WorkQueueResult: Since it is a TypedDict, adding a new key is safe -- callers using .get("phase", "working") will get a default. All existing code that destructures the result via dict access continues to work.
Interaction with cluster collapsing: When in INITIAL_REVIEW phase, the auto/initial-review cluster might be the collapsed form of the individual initial review items. The filter needs to accept both the cluster and individual items. The check item.get("id") == "auto/initial-review" handles the cluster case, and item.get("initial_review") handles uncollapsed items.
Interaction with scope/cluster filtering: If the user explicitly passes --scope or --cluster, the phase gate should NOT override their explicit filter. Add a guard: only apply the INITIAL_REVIEW filter when scope and cluster are both None.
Phase detection when no plan exists: If plan is None (no plan file), we cannot determine PLAN_NEEDED because we have no queue_order to inspect. When plan is None and there are unassessed dims, it is INITIAL_REVIEW. When plan is None and no unassessed but objective findings exist, it should be PLAN_NEEDED (the user has never created a plan). Adjust the detection:
python
if has_objective_findings and not has_unassessed:
if plan is None:
return QueuePhase.PLAN_NEEDED
# plan exists but is empty
has_plan_content = any(...)
has_plan_cycle = bool(plan.get("plan_start_scores"))
if not has_plan_content and not has_plan_cycle:
return QueuePhase.PLAN_NEEDED
Rendering consistency: The status command computes its own _breakdown via plan_aware_queue_breakdown(). Since we are adding phase to QueueBreakdown, it will be available there. But status also builds its own subjective display logic (show_subjective_followup, show_dimension_table). We should make sure the INITIAL_REVIEW phase banner does not duplicate with those existing displays.
Dependency Ordering
QueuePhase enum and detect_queue_phase() -- no dependencies
Update WorkQueueResult TypedDict and build_work_queue() -- depends on step 1
Update QueueBreakdown -- depends on step 2
Render functions -- depends on steps 2-3
Command modules -- depends on step 4
Output/payload -- depends on step 2
Tests -- depends on all above
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py - Core location for QueuePhase enum, detect_queue_phase() function, and the INITIAL_REVIEW gate in build_work_queue()
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next_parts/render.py - New render_phase_banner() function and integration into the rendering pipeline
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next.py - Wire phase through _get_items() to control banner rendering before queue items
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/status_cmd.py - Phase-aware banners in the status dashboard