Fix 4a: render_queue_header for workflow-only items
Fix 6: queue_guard passes scan_path
2. test_scan_preflight.py
Full Path:/Users/user_c042661f/Documents/desloppify/desloppify/tests/commands/scan/test_scan_preflight.py
This file tests the scan queue preflight guard (queue-cycle gating) with test cases for:
CI profile bypass
No plan scenarios
Queue clear allowing scans
Queue remaining blocking scans
Workflow items only allowing scans
--force-rescan validation and behavior
3. test_plan_reconcile.py
Full Path:/Users/user_c042661f/Documents/desloppify/desloppify/tests/commands/scan/test_plan_reconcile.py
This file tests scan plan reconciliation orchestration covering:
_plan_has_user_content checks
_seed_plan_start_scores logic
_apply_plan_reconciliation for superseding issues
_sync_unscored_dimensions and _sync_stale_dimensions
_sync_plan_start_scores_and_log full orchestration
reconcile_plan_post_scan end-to-end tests
4. Test File for _print_score_section
Found in:/Users/user_c042661f/Documents/desloppify/desloppify/tests/commands/test_queue_progress.py
This file contains tests for queue progress and frozen score display helpers. No direct test of _print_score_section was found by grep search, but the file tests related functions like print_frozen_score_with_queue_context, print_execution_or_reveal, and show_score_with_plan_context.
Found in:/Users/user_c042661f/Documents/desloppify/desloppify/tests/commands/test_queue_progress.py
Location: Line 369 in the file above
This test verifies that when objective items are drained but subjective work remains, the system shows live scores + phase-transition banner instead of frozen scores.
All files have been read and their full contents are displayed above.
User
Find the plan show command implementation. The user reports that plan show says "Queue: 0 items" because it reads raw plan["queue_order"] length instead of the dynamic queue. Find the file and the specific line where the queue count is displayed in plan show. Search in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/. Look for "queue_order" usage that counts items for display, and also look at cmd.py lines around 84 and 102.
Assistant
I'll search for the plan show command implementation and locate where the queue count is being displayed.
Assistant
Now let me look at the cmd.py file around lines 84 and 102 as mentioned:
Assistant
Perfect! I found it. Now let me search for how the dynamic queue should be retrieved to understand what the correct approach should be:
Assistant
Let me check the queue operations module and the planning module to understand how to get the dynamic queue:
Assistant
Now let me check how queue_render.py works to see how it properly gets the dynamic queue:
Assistant
Perfect! Now I can see the issue clearly. Let me verify by checking the _work_queue/core.py to understand the build_work_queue function better:
Assistant
Let me continue reading that file to understand how plan integration works:
Assistant
Perfect! Now I have a clear understanding of the issue. Let me create a comprehensive summary report:
Summary
I found the bug in the plan show command. Here are the key findings:
This line reads the raw queue_order list length directly from the plan, which gives a static count of items in the stored queue_order field. However, this doesn't account for:
Skipped items - Items marked as skipped should not be counted in the active queue
Dynamic queue filtering - The actual queue shown to the user is computed dynamically through build_work_queue() which applies multiple filters and enrichments
Line 102 in the same function:
python
print(f" Queue: {ordered} items prioritized")
This uses the incorrectly counted value to display the queue size.
The Correct Approach
Looking at cmd_plan_queue() in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/queue_render.py (lines 47-49), the proper way to count queue items is:
python
queue_order = plan.get("queue_order", [])
skipped_ids = set(plan.get("skipped", {}).keys())
plan_ordered = sum(1 for fid in queue_order if fid not in skipped_ids)
This filters out skipped items from the queue_order count.
Better Solution
The ideal fix would use build_work_queue() (like the queue_render command does) to get the dynamically computed queue with all filters and enrichments applied. This would give the true count of items that will be shown to the user in the actual queue display.
User
Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
Before providing your final summary, wrap your analysis in tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
The user's explicit requests and intents
Your approach to addressing the user's requests
Key decisions, technical concepts and code patterns
Specific details like:
file names
full code snippets
function signatures
file edits
Errors that you ran into and how you fixed them
Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
Double-check for technical accuracy and completeness, addressing each required element thoroughly.
Your summary should include the following sections:
Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
Assistant
Initial Request: User asked to implement a plan to fix queue inconsistency when only subjective items remain. The plan had 5 changes across multiple files.
First Implementation: I made changes to:
Added objective_actionable property to QueueBreakdown
Fixed _print_score_section in status/cmd.py
Fixed _clear_plan_start_scores_if_queue_empty in plan_reconcile.py
Fixed post-scan nudge in plan_nudge.py
Updated tests
User asked about workflow: "so it will be? scan -> subjective review -> score -> plan, right?" - I confirmed.
User asked "is it well-engineered now?": I reviewed and found issues - inline arithmetic duplicating objective_actionable logic, private function imported cross-module. Fixed these.
User confirmed still broken: Provided detailed trace showing the bug was still happening in 5+ places. I then identified that the core problem was the same frozen/live decision being made independently in 5 places.
User asked "is there confusion or complexity here?": I explained the root cause - three semantics of "empty" using one queue_total field.
User said "still broken, refactor to simplify": I introduced ScoreDisplayMode enum and score_display_mode() function as single source of truth. Updated all 5 call sites (status, scan reveal, plan reconcile, plan nudge, next render_nudges).
User asked "does this apply to both pre-loop and post-loop?": I mapped the plan cycle and confirmed all paths covered except preflight (intentionally different).
User reported it's still broken in Reigh: The scan preflight was blocking with 20 subjective items. I confirmed assessments existed but items persisted.
User clarified intended workflow: "scan -> subjective review -> review score -> plan" - subjective items shouldn't block rescanning. I changed preflight to use score_display_mode instead of breakdown.actionable.
User asked "is this elegantly engineered?": I found dead code - actionable property no longer used, duplicate frozen-score renderers, tautological checks.
User
Find the code that renders the plan queue output — specifically the table that shows items with columns like #, Confidence, Detector, Summary, and Cluster. I need to understand the current rendering format and where cluster information is displayed. Look in:
desloppify/app/commands/plan/queue_render.py
desloppify/app/commands/next/output.py
Any related rendering helpers
Also look for how the "Queue: 1 item (20 planned)" headline is formatted. Show me the relevant code sections.
Assistant
I'll search for the plan queue output rendering code and the headline formatting.
Assistant
Let me use proper glob patterns:
Assistant
Now let me read the queue_render.py and output.py files:
Assistant
Perfect! Now let me look at the queue progress helpers to see the headline formatting:
Assistant
Now let me check the collapse_clusters function to understand how clusters are displayed:
Assistant
Perfect! Now let me also check the rendering helper to see if there are other rendering utilities:
Assistant
Perfect! Now let me check the print_table function to understand the table rendering:
Assistant
Excellent! Now let me also look at the next command's render to see the full context:
Assistant
Perfect! Now let me create a comprehensive summary document with all the key rendering code sections:
Summary: Plan Queue Output Rendering
I've found all the code that renders the plan queue output. Here's a complete breakdown:
1. Main Table Renderer (/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/queue_render.py)
The table is built in the _build_rows() function (lines 84-125) with these columns:
# (position index)
Confidence (confidence level or "—" for special items)
Detector (detector name or special type)
Summary (truncated to 48 chars, with asterisk prefix for new items and "[skip]" suffix)
Cluster (cluster name if the item belongs to a plan cluster)
I need to understand an ordering bug in the queue lifecycle. The intended sequence after scan is: scan → subjective review → score → triage. But triage can get injected before subjective review due to three code paths:
Post-scan reconcile ordering — plan_reconcile.py around lines 326-330: triage sync runs before score/create-plan sync
Triage stage injection — stale_dimensions.py around line 216: triage stages inserted at front of planned flow
Queue ranking priority — ranking.py around lines 43, 197, 204: triage stages get higher priority than workflow actions
Please read and show me:
desloppify/app/commands/scan/plan_reconcile.py — the full reconcile function that calls triage sync, score sync, and create-plan sync (around lines 310-340)
desloppify/intelligence/review/stale_dimensions.py — around line 216, where triage stages are inserted
desloppify/engine/_work_queue/ranking.py — around lines 40-50 (kind priority ordering) and lines 190-210 (sort key logic for triage vs workflow)
desloppify/engine/_work_queue/synthetic.py — the build_triage_stage_items function to understand what triage items look like
desloppify/engine/_work_queue/core.py — the _gather_workflow_items function and _apply_lifecycle_filter to understand how triage items interact with the lifecycle filter
Be thorough — I need the actual code to understand the ordering.
Assistant
I'll read these files to understand the ordering bug in the queue lifecycle. Let me start by reading all the critical files.
Assistant
Let me search for the correct file paths and read them individually.
Assistant
The stale_dimensions.py file doesn't exist in intelligence. Let me check what intelligence files exist and look more broadly.
Assistant
Let me search for where triage stages are being inserted:
Assistant
Let me search more specifically for where stages are being inserted at the front:
Assistant
Good! Now let me read the key files:
Assistant
Perfect! I now have all the files needed. Let me search for one more file to get the complete picture of how the lifecycle filter works:
Assistant
Now let me compile my detailed findings with code snippets for the user:
Ordering Bug Analysis: Three Code Paths That Inject Triage Before Subjective Review
I've read all the critical files. Here's what I found:
The reconcile function executes syncs in this order:
python
def reconcile_plan_post_scan(runtime: Any) -> None:
"""Reconcile plan queue metadata and stale subjective review dimensions."""
# ... loading ...
# Line 305-306: Sync unscored dimensions (initial reviews)
if _sync_unscored_and_log(plan, runtime.state):
dirty = True
# Lines 312-318: Sync stale dimensions (refreshed reviews)
if _sync_stale_and_log(
plan,
runtime.state,
policy=policy,
cycle_just_completed=cycle_just_completed,
):
dirty = True
# ... auto_cluster sync ...
# Line 329: **PROBLEM PATH 1** — Triage sync runs BEFORE score/create-plan
if _sync_triage_and_log(plan, runtime.state):
dirty = True
# Line 331: Score communication sync
if _sync_communicate_score_and_log(plan, runtime.state, policy=policy):
dirty = True
# Line 333: **Create plan sync runs LAST**
if _sync_create_plan_and_log(plan, runtime.state, policy=policy):
dirty = True
Issue: Triage sync (line 329) executes before the subjective review completion syncs. When sync_triage_needed() detects new review issues, it injects triage stages at the front of the queue (via _inject_pending_triage_stages) before score communication and create-plan workflows have been evaluated.
User
I need to understand how plan-aware sort keys interact with triage stages and workflow actions. Read these specific sections:
desloppify/engine/_work_queue/ranking.py — the item_sort_key function and _plan_aware_sort_key function. I need to see how plan position overrides natural ranking.
desloppify/engine/_work_queue/plan_order.py — the stamp_plan_sort_keys function. How does it stamp sort keys for items that are in queue_order? Does it treat triage stage IDs and workflow action IDs differently?
desloppify/engine/_plan/stale_dimensions.py — the promoted_insertion_index function. Where exactly in queue_order does it insert triage stages?
desloppify/engine/_work_queue/ranking.py — the full _natural_sort_key function to see all cases.
Show me the actual code for each.
Assistant
I'll read these specific sections for you. Let me fetch all four locations in parallel.
Assistant
Now let me read the promoted_ids.py file to find the promoted_insertion_index function:
Assistant
Perfect. Now I have all the code you requested. Let me compile a comprehensive overview:
Analysis: Plan-Aware Sort Keys and Triage/Workflow Interaction
Here's the actual code from all four locations:
1. _natural_sort_key() function (lines 189-238 in ranking.py)
Here's an example of how your output should be structured:
Key Technical Concepts:
[Concept 1]
[Concept 2]
[...]
Files and Code Sections:
[File Name 1]
[Summary of why this file is important]
[Summary of the changes made to this file, if any]
[Important Code Snippet]
[File Name 2]
[Important Code Snippet]
[...]
Errors and fixes:
[Detailed description of error 1]:
[How you fixed the error]
[User feedback on the error if any]
[...]
Problem Solving:
[Description of solved problems and ongoing troubleshooting]
All user messages:
[Detailed non tool use user message]
[...]
Pending Tasks:
[Task 1]
[Task 2]
[...]
Current Work:
[Precise description of current work]
Optional Next Step:
[Optional Next step to take]
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.
There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
Compact Instructions
When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
IMPORTANT: Do NOT use any tools. You MUST respond with ONLY the ... block as your text output.
User said "clean it up": I removed actionable property, simplified print_frozen_score_with_queue_context signature, replaced _render_frozen_queue_status body with single call to shared function, removed _objective_remaining helper.
User reported crash in Reigh: _render_frozen_queue_status called with old queue_total kwarg. Already fixed in working copy. Also plan show showing 0 items when queue had 20 subjective. Fixed _cmd_plan_show to use plan_aware_queue_breakdown.
User asked why not all subjective reviews show after initial scan: I traced through lifecycle filter - _apply_lifecycle_filter was letting initial reviews through but not hiding objective items. User said: "it should show all subjective reviews and only show them other items after they're all done / they should be in a cluster"
Most recent work: Modified _apply_lifecycle_filter in core.py to add Phase 1 gating - when initial reviews exist, hide objective items. Updated test. Was about to run tests when summary was requested.
desloppify/engine/_work_queue/core.py — Work queue lifecycle filter. MOST RECENT CHANGE — NOT YET TESTED
Added _has_initial_reviews() helper
Modified _apply_lifecycle_filter to enforce phase ordering: when initial reviews exist, hide objective items
python
def _apply_lifecycle_filter(items: list[WorkQueueItem]) -> list[WorkQueueItem]:
if _has_initial_reviews(items):
# Phase 1: only initial reviews + workflow items visible
return [
i for i in items
if (i.get("kind") == "subjective_dimension" and i.get("initial_review"))
or i.get("kind") in ("workflow_stage", "workflow_action")
]
if not _has_objective_items(items):
return items # endgame: everything visible
return [i for i in items if not _is_endgame_only(i)]
Test files modified:
desloppify/tests/commands/test_queue_progress.py — Added score_display_mode tests (7 tests), objective_actionable tests, updated print_frozen_score_with_queue_context tests for new signature, removed actionable tests
desloppify/tests/commands/scan/test_plan_reconcile.py — Updated mocks to use objective_actionable + queue_total, added test for clearing when only subjective remain
Inline arithmetic duplication: Multiple call sites computed queue_remaining - breakdown.subjective - breakdown.workflow instead of using objective_actionable. Fixed by using the property.
Private function imported cross-module: _print_objective_drained_banner was underscore-prefixed but imported into status/cmd.py. Fixed by renaming to print_objective_drained_banner and adding to __all__.
Missed call site in next command: _render_frozen_queue_status in render_nudges.py still used queue_total <= 0 or plan_start_strict is None without objective/subjective distinction. This was the bug the user was still seeing. Fixed by using score_display_mode.
Scan preflight blocking subjective items: breakdown.actionable included subjective items, blocking rescan after reviews were done. User feedback: "they completed subjective review, and haven't gotten score". Fixed by using score_display_mode — only FROZEN mode blocks.
plan show count mismatch: Showed "Queue: 0 items" when 20 subjective items existed because it read raw queue_order length. Fixed by using plan_aware_queue_breakdown.
_render_frozen_queue_status signature mismatch: After cleanup removed queue_total param, but installed version was stale. Not a code bug — user needed to reinstall.
Dead actionable property: After all call sites switched to score_display_mode, actionable was only used in tests. Removed.
Dead code branch: _render_frozen_queue_status had a breakdown is None fallback that was unreachable since score_display_mode returns LIVE when breakdown is None. Removed by replacing entire body with print_frozen_score_with_queue_context call.
Problem Solving:
Core architectural problem: The frozen/live score decision was made independently in 6 call sites with different logic. Solved by extracting ScoreDisplayMode enum and score_display_mode() function.
Three meanings of "empty": queue_total (all items), actionable (excludes workflow), objective_actionable (excludes subjective + workflow). Simplified to just objective_actionable used inside score_display_mode, with actionable removed entirely.
Phase ordering for new users: Initial subjective reviews should come before objective work. Solved by adding Phase 1 gating in _apply_lifecycle_filter. This change has NOT been tested yet.
All user messages:
"Implement the following plan: Fix: Queue inconsistency when only subjective items remain" (detailed plan with 5 changes)
"so it will be? scan -> subjective review -> score -> plan, right?"
"can you confirm: so it will be? scan -> subjective review -> score -> plan, right?"
"is it well-engineered now?"
[Provided detailed trace of still-broken behavior with 8 numbered points]
"is there confusion or complexity here? why is this so complicated?"
"CaIt's still broken, how can you fix? How can you fix the underlying reason for the confusion/complexity?"
"will this feed into all the commands that pull the list?"
"Does this stuff apply to both the pre-loop and post-loop sequence?"
"still seems to be happening in documents/reigh - they completed subjective review, and haven't gotten score" (with detailed agent output showing 20 subjective items blocking scan)
"preflight was already working, why was that?" (I explained actionable excluded workflow but not subjective)
"is this well-engineered now?"
"is this elegantly engineered now?"
"Please clean it up"
"can you fix these issues, maybe related?" (crash in render_nudges + plan show count mismatch, with detailed bug packet)
"Why for a new user is it not showing all subjective reviews in the queue after initial scan?" (with queue output showing only 1 subjective item at top)
"it isn't, it should show all subjective reviews and only show them other items after they're all done / they should be in a cluster"
Pending Tasks:
Run tests after _apply_lifecycle_filter change — The lifecycle filter change in core.py and the test update in work_queue_cases.py have NOT been tested yet
Verify no other tests break from the lifecycle filter change (many tests may assume objective items are visible alongside initial reviews)
Consider whether the clustering behavior needs updating — User mentioned "they should be in a cluster" but the current change only handles visibility gating, not explicit clustering of initial reviews
Current Work:
Most recently modified _apply_lifecycle_filter in desloppify/engine/_work_queue/core.py to add Phase 1 gating: when _has_initial_reviews(items) is true, only show initial-review subjective items and workflow items, hiding objective items. Updated test_unassessed_subjective_visible_with_objective_backlog in work_queue_cases.py from asserting 5 items (4 objective + 1 review) to 1 item (review only). Tests have NOT been run yet.
Optional Next Step:
Run the full test suite to verify the lifecycle filter change doesn't break other tests:
code
python -m pytest desloppify/tests/ -q
The user's most recent request was: "it should show all subjective reviews and only show them other items after they're all done / they should be in a cluster". The lifecycle gating change addresses "only show them other items after they're all done" but the clustering aspect ("they should be in a cluster") may need additional work if the auto/initial-review cluster isn't automatically created for new users. After tests pass, verify the clustering behavior works correctly for the initial-review case.
def print_table(
headers: list[str], rows: list[list[str]], widths: list[int] | None = None
) -> None:
if not rows:
return
if not widths:
widths = [
max(len(str(h)), *(len(str(r[i])) for r in rows))
for i, h in enumerate(headers)
]
header_line = " ".join(h.ljust(w) for h, w in zip(headers, widths, strict=False))
print(colorize(header_line, "bold"))
print(colorize("─" * (sum(widths) + 2 * (len(widths) - 1)), "dim"))
for row in rows:
print(" ".join(str(v).ljust(w) for v, w in zip(row, widths, strict=False)))
This creates a formatted table with bold headers and a dim separator line.
Key Takeaways
Cluster column in the queue table shows the plan cluster name for individual items (line 119 in queue_render.py)
Cluster meta-items replace collapsed cluster members with kind="cluster" and show [N items] in the Summary column
Headline format uses bullet separator (·) to list plan counts: Queue: N items (M planned · K skipped)
Focus display shows active cluster in cyan when set via plan.get("active_cluster")
Cluster details in next command show description, total items, and action steps
2. Triage Stage Insertion at Front (stale_dimensions.py lines 207-224)
The function _inject_pending_triage_stagesunconditionally inserts triage stages at the front:
python
def _inject_pending_triage_stages(
order: list[str],
plan: PlanModel,
confirmed: set[str],
) -> bool:
"""Inject triage stages for pending (unconfirmed) items.
Returns True if any stages were injected.
"""
insert_at = promoted_insertion_index(order, plan) # Line 216
stage_names = ("observe", "reflect", "organize", "commit")
existing = set(order)
injected_count = 0
for sid, name in zip(TRIAGE_STAGE_IDS, stage_names, strict=False):
if name not in confirmed and sid not in existing:
order.insert(insert_at + injected_count, sid) # Line 222
injected_count += 1
return injected_count > 0
And the function sync_triage_needed calls this when review issues change (lines 341-399):
python
def sync_triage_needed(
plan: PlanModel,
state: StateModel,
) -> TriageSyncResult:
"""Inject 4 triage stage IDs at front of queue when review issues change.
Only injects stages not already confirmed in ``epic_triage_meta``.
...
"""
# Lines 386-393
if current_hash and current_hash != last_hash:
new_since_triage = _new_review_ids_since_triage(state, meta)
if new_since_triage:
# New review issues appeared — re-triage needed
result.injected = _inject_pending_triage_stages(order, plan, confirmed)
Issue: This uses promoted_insertion_index() to find where to insert, which places triage after any "promoted" items but before any unscored subjective dimensions that were already prepended. This means if unscored dimensions were just prepended by sync_unscored_dimensions, triage stages get inserted between them and the rest of the queue.
The _natural_sort_key function (lines 189-238) applies these ranks:
python
def _natural_sort_key(item: WorkQueueItem) -> tuple:
"""Compute natural (non-plan-aware) ranking for queue items."""
kind = item.get("kind", "issue")
# Initial-review subjective items: highest priority
if kind == "subjective_dimension" and item.get("initial_review"):
return (_RANK_INITIAL_REVIEW, 0, subjective_score_value(item), item.get("id", ""))
# **PROBLEM PATH 3** — Triage stage items: get -2 ranking (higher than workflow!)
if kind == "workflow_stage":
blocked_penalty = 1 if item.get("is_blocked") else 0
stage_index = _workflow_stage_index(item)
return (_RANK_TRIAGE_STAGE, blocked_penalty, stage_index, item.get("id", ""))
# Workflow action items (e.g. create-plan) get -1 ranking
if kind == "workflow_action":
return (_RANK_WORKFLOW, 0, 0, item.get("id", ""))
Issue: Triage stages get _RANK_TRIAGE_STAGE = -2, while workflow actions (score checkpoint, communicate-score, create-plan) get _RANK_WORKFLOW = -1. Lower numbers sort first, so triage stages sort higher priority than all workflow actions, even though the intended lifecycle is: initial review → subjective review → score → create-plan → triage.
The lifecycle filter governs what's visible at each phase (lines 299-319):
python
def _apply_lifecycle_filter(items: list[WorkQueueItem]) -> list[WorkQueueItem]:
"""Enforce lifecycle visibility rules.
The queue enforces a phase order: scan → initial review → objective work.
1. **Initial reviews pending** → only show initial-review subjective items.
The user must complete first-time reviews before working objective items.
2. **Objective work remains** → show objective items, hide endgame-only
subjective reassessments (stale re-reviews).
3. **Objective drained** → everything visible (endgame).
"""
if _has_initial_reviews(items):
# **KEY ISSUE** — Phase 1: only initial reviews + workflow items visible
return [
i for i in items
if (i.get("kind") == "subjective_dimension" and i.get("initial_review"))
or i.get("kind") in ("workflow_stage", "workflow_action") # <-- triage allowed!
]
if not _has_objective_items(items):
return items # endgame: everything visible
return [i for i in items if not _is_endgame_only(i)]
Issue: The lifecycle filter at line 315 allows both workflow_stage and workflow_action items to pass through during Phase 1 (initial reviews pending). This means triage stages are not gated by the lifecycle—they're treated as workflow actions, which are allowed during any phase.
6. Build Work Queue Pipeline (core.py lines 90-145)
The pipeline that assembles the queue (lines 90-145):
python
def build_work_queue(
state: StateModel,
*,
options: QueueBuildOptions | None = None,
) -> WorkQueueResult:
"""Build a ranked work queue from state issues.
Pipeline:
1. Gather — issue items, subjective dimensions, workflow stages
2. Score — estimate impact from dimension headroom, apply floor
3. Presort — stamp plan positions, separate skipped items
4. Lifecycle — filter endgame-only items when objective work remains
5. Sort — rank by impact/confidence, apply plan order
6. Limit — truncate to count, optionally add explain metadata
"""
opts = options or QueueBuildOptions()
plan, scan_path, status, threshold = _resolve_inputs(opts, state)
# 1. Gather
items = build_issue_items(...)
items += _gather_subjective_items(state, opts, threshold)
items += _gather_workflow_items(state, plan, status) # <-- triage gathered here
# 2. Score & filter
enrich_with_impact(items, state.get("dimension_scores", {}))
items = [i for i in items if _passes_impact_floor(i)]
# 3. Plan-aware ordering (part 1: separate skipped items)
new_ids, skipped = _plan_presort(items, state, plan)
# 4. Lifecycle filter — endgame-only items filtered when objective work remains
items = _apply_lifecycle_filter(items) # <-- triage NOT filtered
# 5. Sort & plan post-processing
items.sort(key=item_sort_key) # <-- triage gets -2 rank, sorts highest
_plan_postsort(items, skipped, plan, opts)
# 6. Finalize
The _gather_workflow_items function (lines 202-221) calls build_triage_stage_items first:
python
def _gather_workflow_items(
state: StateModel, plan: dict | None, status: str,
) -> list[WorkQueueItem]:
"""Inject triage stages, checkpoints, and create-plan when plan is active."""
if not plan or status not in {"open", "all"}:
return []
items: list[WorkQueueItem] = list(build_triage_stage_items(plan, state)) # Line 209
for builder in (
build_score_checkpoint_item,
build_import_scores_item,
build_communicate_score_item,
):
item = builder(plan, state)
if item is not None:
items.append(item)
plan_item = build_create_plan_item(plan)
if plan_item is not None:
items.append(plan_item)
return items
Summary: The Three Ordering Bug Vectors
Reconcile order (plan_reconcile.py): sync_triage_needed() is called at line 329, beforesync_communicate_score_needed() (line 331) and sync_create_plan_needed() (line 333). This means triage stages get injected into the queue before workflow actions have been queued.
Insertion position (stale_dimensions.py): The function _inject_pending_triage_stages() inserts at promoted_insertion_index() (line 216), placing triage stages after any promoted items but at the front of the normal queue, potentially before unscored subjective dimensions if they're being prepended in the same pass.
Ranking priority (ranking.py): Triage stages get _RANK_TRIAGE_STAGE = -2, while all workflow actions (score checkpoint, communicate-score, create-plan) get _RANK_WORKFLOW = -1. Since lower numbers sort first, triage always sorts before workflow actions in the final queue, even though the intended lifecycle is review → score → create-plan → triage.
The lifecycle filter (core.py lines 299-319) doesn't gate triage stages; they pass through during all phases because they're tagged as workflow_stage and the filter allows both workflow_stage and workflow_action during initial reviews.
Key insight: Triage stages (workflow_stage kind) have their own natural rank (-2) and sort by blocked-before-unblocked, then by stage index (observe → reflect → organize → commit).
2. item_sort_key() function (lines 241-264 in ranking.py)
python
def item_sort_key(item: WorkQueueItem) -> tuple:
"""Unified sort key: plan position first, then natural ranking.
When ``_plan_position`` is stamped (by :func:`stamp_plan_sort_keys`),
planned items sort first in plan order, then existing items by natural
ranking, then newly-discovered items by natural ranking.
When no plan fields are stamped, falls back to pure natural ranking.
"""
plan_pos = item.get("_plan_position")
if plan_pos is not None:
kind = item.get("kind", "issue")
# Triage stages: even when explicitly planned, maintain the
# blocked-before-unblocked invariant for correctness.
if kind == "workflow_stage":
blocked = 1 if item.get("is_blocked") else 0
stage_idx = _workflow_stage_index(item)
return (_TIER_PLANNED, blocked, stage_idx, item.get("id", ""))
return (_TIER_PLANNED, 0, plan_pos, item.get("id", ""))
is_new = item.get("_is_new", False)
group = _TIER_NEW if is_new else _TIER_EXISTING
return (group, *_natural_sort_key(item))
Plan tier constants:
python
_TIER_PLANNED = 0 # Items with explicit plan position
_TIER_EXISTING = 1 # Known items, natural ranking
_TIER_NEW = 2 # Newly discovered items
Critical observation: Even when planned (_plan_position is not None), triage stages get special treatment. They ignore the plan position and sort by (_TIER_PLANNED, blocked, stage_idx, id) instead of (_TIER_PLANNED, 0, plan_pos, id). This maintains the blocked-before-unblocked invariant regardless of plan position.
3. stamp_plan_sort_keys() function (lines 56-78 in plan_order.py)
python
def stamp_plan_sort_keys(
items: list[WorkQueueItem],
plan: dict,
new_ids: set[str],
) -> None:
"""Stamp ``_plan_position`` and ``_is_new`` on each item.
These fields are consumed by :func:`item_sort_key` in ``ranking.py``
to produce the correct final ordering in a single sort pass.
"""
queue_order: list[str] = plan.get("queue_order", [])
skipped_ids: set[str] = set(plan.get("skipped", {}).keys())
position_map: dict[str, int] = {}
for idx, issue_id in enumerate(queue_order):
if issue_id not in skipped_ids:
position_map[issue_id] = idx
for item in items:
item_id = item["id"]
pos = position_map.get(item_id)
item["_plan_position"] = pos # None if not in queue_order
item["_is_new"] = item_id in new_ids
Builds a position map, skipping items that are in the skipped dict
Both triage stage IDs (e.g., "triage::observe") and workflow action IDs (e.g., "workflow::create-plan") are treated identically here
The function doesn't differentiate; it just stamps _plan_position with their index in queue_order
Items not in queue_order get _plan_position = None
4. promoted_insertion_index() function (lines 37-46 in promoted_ids.py)
python
def promoted_insertion_index(order: list[str], plan: dict[str, Any]) -> int:
"""Return insertion index immediately after the last promoted item."""
promoted = set(_promoted_ids(plan))
if not promoted:
return 0
last_idx = -1
for idx, issue_id in enumerate(order):
if issue_id in promoted:
last_idx = idx
return last_idx + 1 if last_idx >= 0 else 0
Behavior:
Scans through order (the queue_order list) to find the last item that appears in promoted_ids
Returns insertion index immediately after that last promoted item
If no promoted items exist, returns 0 (insert at front)
If promoted items exist but aren't in the current order, returns 0
Where it's used in stale_dimensions.py:
Line 164: _inject_subjective_ids() calls it to find where to insert unscored dimensions (at the front, after promoted)
Line 216: _inject_pending_triage_stages() calls it to find where to insert triage stages (at the front, after promoted)
Summary: How They Interact
Component
Behavior
promoted_insertion_index()
Finds the insertion point at the front of queue_order, after any user-promoted items
Triage stage injection
Uses promoted_insertion_index() to insert triage::observe, reflect, organize, commit at the front
Workflow action injection
Uses similar front-of-queue insertion for workflow::create-plan, workflow::score-checkpoint, etc.
stamp_plan_sort_keys()
Treats triage stages and workflow actions identically — both get _plan_position based on their index in queue_order
item_sort_key()
Exception for triage stages: Even with a plan position, they sort by blocked-before-unblocked + stage order, NOT by plan position
Workflow actions (non-stages)
No exception — they respect plan position like regular issues
The critical asymmetry: Triage stages (kind == "workflow_stage") have a correctness constraint that overrides plan position, while workflow actions (kind == "workflow_action") fully respect the plan order.