I need to understand how the desloppify tool handles triage and prioritization of findings. Look at:
How findings are prioritized (tiers, scoring, dimensions)
The next command - what it recommends and how
The plan command - how it builds the prioritized breakdown
Any existing complexity/simplicity heuristics in detectors or scoring
The narrative/actions system - how it decides what to recommend
Focus on the decision-making logic, not implementation details. Search broadly across engine/, intelligence/, and commands/. Thoroughness: medium.
Assistant
I'll systematically explore the desloppify tool's prioritization and triage logic. Let me start with broad searches to understand the decision-making architecture.
Assistant
Now let me search for the specific commands and core narrative logic:
Assistant
Let me correct the path:
Assistant
Now let me read the plan command and key narrative files:
Assistant
Let me find the correct actions file and explore scoring:
Assistant
Let me dig deeper into the dimension scoring and planning modules:
Assistant
Now let me look at the work queue and queue policy to understand prioritization:
Assistant
Let me explore the core work queue and ranking logic:
Assistant
Let me check ranking and selection logic:
Assistant
Now let me look at the snapshot and ranking modules for the actual prioritization logic:
Assistant
Let me continue reading the ranking.py file to see the sort key logic:
Assistant
Let me look at the narrative decisions around reminders and action selection:
Assistant
Now let me read the full action computation:
Assistant
Let me read the action priorities assignment:
Assistant
Let me read those action computation functions:
Assistant
Let me look at the existing complexity/simplicity heuristics in detectors:
Assistant
Perfect! Now let me gather one more piece about tiers and impact:
Assistant
Excellent. Let me look at one more piece about the plan triage and prioritization:
Assistant
Let me find the TRIAGE_STAGE_ORDER:
Assistant
Let me find the TRIAGE_STAGE_ORDER definition:
Assistant
Perfect! Now I have enough information. Let me compile my findings into a comprehensive report.
Summary: Desloppify Triage and Prioritization Architecture
Based on my exploration of the codebase, here's how the desloppify tool handles triage and prioritization of findings:
1. FINDING PRIORITIZATION HIERARCHY
The tool uses a multi-level prioritization system across different queue views:
Plan-Aware Tiers (in _work_queue/ranking.py):
Tier 0 (PLANNED): Items with explicit position in living_plan.queue_order
Tier 1 (EXISTING): Known items sorted by natural ranking
Tier 2 (NEW): Newly discovered items in current scan
Within natural ranking, items stratify into groups:
Each dimension has a tier (Tier.AUTO_FIX=1, QUICK_FIX=2, JUDGMENT=3, MAJOR_REFACTOR=4)
Dimensions below MIN_SAMPLE (200 checks) have dampened weight proportionally
User
Thoroughly explore the work queue ranking and filtering system in desloppify. I need to understand:
engine/_work_queue/ranking.py — the full item_sort_key() function, impact calculation, standalone_threshold logic, and how items get filtered vs included
engine/_work_queue/snapshot.py — how queue snapshots partition items into EXECUTION vs BACKLOG, and what visibility rules exist
engine/planning/queue_policy.py — how the queue is built and what policy decisions are made
Any constants or thresholds that control what surfaces vs what gets suppressed
I want to understand the exact decision points where "should this item surface?" is determined. Read the actual code, not just signatures. Thoroughness: very thorough.
Assistant
I'll conduct a thorough exploration of the work queue ranking and filtering system. Let me start by reading the key files.
Assistant
Now let me search for related files to complete the picture of the work queue system.
User
Explore the scoring and dimension system in desloppify to understand how tiers affect prioritization:
engine/_scoring/policy/core.py — dimension definitions, tier assignments, how dimensions are weighted
base/scoring_constants.py — tier weights, confidence weights, any thresholds
engine/_scoring/results/impact.py — how score impact is estimated for individual items
base/enums.py — Tier enum values and any related enums
I need to understand: how does tier (AUTO_FIX, QUICK_FIX, JUDGMENT, MAJOR_REFACTOR) influence what gets surfaced and in what order? What are the actual numeric weights? How is "estimated impact" computed for a single finding?
Read the actual code. Thoroughness: very thorough.
Assistant
Now let me read the supporting helper and context files:
Assistant
I'll explore the scoring and dimension system thoroughly. Let me read the key files to understand how tiers affect prioritization.
Assistant
Let me continue reading helpers and look at the models/inputs:
Assistant
Now let me read the key scoring and policy files:
User
Explore the strategy and phase system in desloppify:
intelligence/narrative/strategy_engine_hints.py — how strategy hints are generated, what conditions trigger what advice
intelligence/narrative/phase.py — phase detection logic and all phase values
intelligence/narrative/action_engine.py and action_engine_routing.py — how actions are computed, prioritized, and routed
intelligence/narrative/reminders.py — how reminders decide what to surface
I want to understand how the narrative layer decides "what to recommend" and whether there are existing hooks for applying YAGNI/KISS filtering at the advisory level.
Read the actual code. Thoroughness: very thorough.
Assistant
I'll conduct a thorough exploration of the strategy and phase system in desloppify. Let me start by searching for the relevant files and understanding the architecture.
Assistant
Now let me look at the synthetic items builders and constants:
Assistant
Now let me read the health scoring and results core to complete the picture:
Assistant
Good, I found the files. Now let me read the core files in a logical order to understand the narrative layer architecture. Let me start with the phase system, then strategy, then actions and reminders.
Assistant
Let me read the core narrative orchestrator and other key files:
Assistant
Let me check the registry for standalone_threshold usage:
Assistant
Now let me look at how dimensions are used in prioritization and planning:
Assistant
Now let me look at some examples and finalization logic:
Assistant
Now let me read the reminders system:
Assistant
Let me look at how tiers are used in the registry and narrative dimensions:
Assistant
Now let me read the strategy engine and related files:
Assistant
Now let me check the plan_order.py for sorting/position logic:
Assistant
Now let me check how tiers are used in prioritization and work queue logic:
Assistant
Now let me read the dimensions and signals modules to understand the full picture:
Assistant
Let me check config for constants and stale policy:
Assistant
Let me also check the types module and the headline module to complete my understanding:
Assistant
Perfect! Now let me search for any existing filters or simplification hooks to understand the current filtering mechanisms:
Assistant
Perfect! Now let me look at one more critical piece—how tiers are displayed and used in planning:
Assistant
Let me get the constant values and wrap up the exploration:
Assistant
Excellent. Now let me check if there are any configuration knobs or hooks for filtering:
Assistant
Now let me look at specific examples of how tiers are used in test or display contexts:
Assistant
Let me continue reading the catalog to see all tier assignments:
Assistant
Perfect! Now I have a comprehensive understanding of the scoring and dimension system. Let me compile the findings into a clear report.
Comprehensive Analysis: Scoring & Dimension System in Desloppify
Based on a thorough read of the codebase, here's how tiers affect prioritization and how the scoring system works:
How used: Tiers weight dimension scores in debt analysis. In dimensions.py:183, tier weights are applied when computing weighted dimension averages — higher tier = higher weight in the overall gap calculation.
"strong" if coverage >40% OR impact_ratio >30% OR (phase is "first_scan"/"stagnation"/"regression" AND coverage >15%)
"moderate" if coverage >10%
"none" otherwise
B. Lane Partitioning (compute_lanes)
Splits work into parallelizable workstreams by file overlap:
Assistant
Perfect. Now I have a comprehensive understanding of the work queue system. Let me compile a detailed report.
Comprehensive Work Queue Ranking & Filtering System Report
Based on thorough code analysis, here is the complete breakdown of the desloppify work queue ranking and filtering architecture:
1. ranking.py — Core Ranking Logic
item_sort_key() Function (Lines 239–262)
This is the unified sort key that determines final item order across all queue views. It implements a tiered sorting strategy:
python
def item_sort_key(item: WorkQueueItem) -> tuple[Any, ...]:
"""Unified sort key: plan position first, then natural ranking."""
plan_pos = item.get("_plan_position")
if plan_pos is not None:
# TIER 1: Items with explicit plan position (rank 0)
# Triage stages maintain blocked-before-unblocked invariant
if kind == "workflow_stage":
return (_TIER_PLANNED, plan_pos, blocked, stage_idx, item.get("id"))
return (_TIER_PLANNED, 0, plan_pos, item.get("id"))
# TIER 2/3: Known vs new items by natural ranking
is_new = item.get("_is_new", False)
group = _TIER_NEW if is_new else _TIER_EXISTING
return (group, *_natural_sort_key(item))
ALL applicable actions generated — no min impact threshold, no max count cap
Strategy hints based on fixer leverage + lane parallelization
Lanes: significance threshold = file_count ≥5 OR impact ≥1.0
Reminders (intelligence/narrative/reminders.py)
Decay after 3 shows
Hard-coded priority/severity per type
No phase-based suppression
What's Missing (YAGNI/KISS Gaps)
No impact floor: actions with 0.1pt impact surface alongside 5pt impact actions
No tier gating by phase: MAJOR_REFACTOR items surface in early_momentum alongside AUTO_FIX
No action count cap: users can see 15+ actions, overwhelming the signal
No "good enough" recognition: no messaging when score is high and remaining work is diminishing returns
Strategy hints don't warn about over-engineering: never say "this is probably fine, don't bother"
Assistant
I'll explore the relevant codebase to understand the current implementation before designing the plan.
Assistant
Now let me look at the scoring tiers and how the work queue connects to tier info.
Assistant
Now let me check where tier info is available on queue items and how the narrative output is rendered.
Assistant
Now let me check how the tier info is available on issues (from the registry/detectors).
Assistant
Good, so issues have a tier field (1-4). Now let me check the registry location and see where actions are consumed for display.
Assistant
I now have a thorough understanding of the codebase. Let me finalize by checking how the action list is actually rendered/consumed by the CLI output.
Assistant
Let me find where actions are rendered in the coaching/scan output.
Assistant
Let me look at the status render to see how many actions are actually displayed.
Assistant
Good -- print_ranked_actions already has a limit=3 default. Now I have a comprehensive understanding. Let me check the query.json output to see how the full actions list is persisted.
Assistant
I have enough understanding now. Here is the implementation plan.
Implementation Plan: YAGNI/KISS Principles in Triage/Prioritization
Overview
Five targeted changes, ordered by value-to-effort ratio. Each is additive -- filtering or annotating existing data rather than restructuring code flow.
Logic: After _assign_priorities(actions) returns, filter the list to remove low-impact actions. Add a constant for the threshold.
code
# New constant at module level:
MIN_ACTION_IMPACT = 0.5 # Suppress actions below this impact threshold
# After line 149 (prioritized = _assign_priorities(actions)):
prioritized = [
action for action in prioritized
if action.get("impact", 0) >= MIN_ACTION_IMPACT
or action.get("type") == "debt_review" # debt_review has no impact score
]
The debt_review type uses gap not impact, so it must be exempt. This is the right place because compute_actions is the single producer of the actions list consumed by core.py, strategy_engine.py, and all renderers.
Interaction: Downstream consumers (strategy lanes, rendering) automatically see fewer actions. print_ranked_actions already caps at 3 for display, but the strategy engine and query.json get the full list -- this prevents noise in both.
Change 2: Action count cap
Problem: Even after impact floor, users can see many actions. The query.json and strategy engine process them all.
Function to modify: compute_actions(), same location as Change 1
Logic: After the impact floor filter, cap to a maximum count. Since actions are already sorted by type-priority and impact, truncation preserves the best items.
User
I need to understand exactly what the "triage" process surfaces in desloppify. Explore thoroughly:
The plan triage command — find the command implementation and trace what it does step by step
The epic triage system — what stages exist, what each stage does, what gets surfaced to users
How triage interacts with the work queue — what items appear during triage vs execution
The triage stage workflow items in snapshot.py — how they appear, their dependencies
Any triage-related files in engine/_plan/ or engine/planning/
What the user actually SEES during triage — what output/prompts they get
I want to understand the full user journey: "I run plan triage, what happens? What do I see? What decisions am I asked to make?" Read actual code and trace the flow end-to-end. Thoroughness: very thorough.
Assistant
I'll conduct a thorough exploration of the triage process in desloppify. Let me start by mapping out the key areas and then tracing the flow end-to-end.
Assistant
Let me search for triage-related files more specifically:
User
I need to understand what users actually SEE when running desloppify next and desloppify plan queue — what items surface and how they're presented.
Look at:
app/commands/next/cmd.py — the full next command flow
app/commands/next/render.py or any rendering in that directory — how items are displayed
app/commands/plan/cmd.py — the plan queue subcommand specifically
Any rendering/display code for work queue items
What the scan output coaching section looks like
I want to understand: what does a user actually see in their terminal? What items, what format, what recommendations? Read the rendering code. Thoroughness: very thorough.
Assistant
Now let me read the key triage files. I'll start with the command implementation:
Assistant
I'll explore the command structures and rendering code to understand what users see when running these commands. Let me start by mapping out the relevant files.
Assistant
Good! Let me now read the main triage command and related files:
Assistant
The globs aren't finding files. Let me check the actual directory structure first.
Assistant
Now let me read the workflow implementation:
Assistant
Good! Now let me find the actual next and plan commands:
Assistant
Let me read the workflow file:
Assistant
Perfect! Now let me read the key files to understand what users see:
Assistant
Now let me look at the stages and the snapshot.py file for the triage stage workflow items:
Assistant
Now let me read the queue_flow to understand the full next command rendering:
Assistant
Now let me look at the scan output to understand the coaching section:
Assistant
Let me read the key triage-related files from engine/_plan:
Assistant
Now let me read the triage core and how the stages interact:
Assistant
Let me read the agent context and reporting files:
Assistant
Now let me look at the stage_queue.py and how triage stages are injected:
Assistant
Now let me look at the render support to understand the queue header and other item rendering:
Assistant
Now let me look at how the dashboard and rendering work, and also the confirmations:
Assistant
Perfect. Now let me read more of the render_nudges to see the follow-up nudges and the queue header rendering:
Assistant
Let me also check the stage completion flow and what output users actually see:
Assistant
Excellent. Now let me look at the complete scan cmd to see where the coaching appears:
Assistant
Now let me look at some tests to understand user interactions, and also check triage_start_policy.py:
Assistant
Now let me check the integrity_report to see what post-scan analysis outputs:
Assistant
Now let me trace how the user sees the triage dashboard. Let me look at a test to understand the flow:
Assistant
Let me look at the parser to understand what command-line options are available for the triage command:
Assistant
Now let me look at one more important piece - the dashboard layout to understand what gets displayed:
Assistant
Excellent! Now I have a comprehensive understanding. Let me create a detailed summary document for the user based on my exploration:
Summary: The Desloppify "Triage" Process
I've conducted a thorough exploration of the triage system in desloppify. Here's what I found:
The command dispatcher cmd_plan_triage() routes through the main workflow orchestrator at /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/workflow.py.
Perfect! Now I have a comprehensive understanding. Let me create a detailed report summarizing what users see when they run these commands.
Summary: User-Facing Terminal Output for desloppify next and desloppify plan queue
Based on my thorough exploration of the codebase, here's exactly what users see when running these commands:
desloppify next Output
The command shows a prioritized single work item with rich context:
1. Queue Header
code
Queue: N items
(Skip items only when explicitly requested.)
2. Queue Status Block (when plan is active and not frozen)
Shows progress toward target:
Live queue breakdown (plan-ordered, skipped, subjective items)
North star guidance (strict score current/target)
Score projection if plan is frozen (plan start strict vs. current live estimate)
3. Main Work Item Card (for standard issues)
code
Next item (#123 in queue) [position/count if multiple shown]
(medium confidence)
────────────────────────────────────────────────────
Summary of the issue (in yellow)
Type: Auto-fixable | Design review | (none if standard fix)
→ Plan override description (if present, in cyan)
Cluster: name — "description" (N items)
Note: manual override note (if present, dim)
File: path/to/file.py
ID: detector::unique_id (dim)
Lines: 42, 57, 103
Category: error type
Active importers: count
Suggestion: how to fix (dim)
Code: (code snippet around the line, dim)
Score impact:
Strict: +X.X pts if fixed (shows dimension and pool)
Health: +Y.Y pts
Auto-fixable: N similar issues. Run `cmd` to fix all at once. (if batch available, cyan)
For cluster items (collapsed batch tasks):
code
User
I need to understand who CONSUMES the outputs of the narrative/action/strategy system in desloppify. Specifically:
Where is compute_narrative() called from? What commands use it?
Where are actions from the narrative result actually rendered or used?
Where is strategy.hint displayed?
How does query.json get written — what writes it, what reads it?
Where does the scan coaching output come from — what renders the "CUSTOM COACHING" or "INSTRUCTIONS FOR LLM" section?
Does the next command use narrative actions, or does it use the work queue directly?
Does plan triage use narrative actions at all, or is it entirely separate?
I want to understand: if I filter actions in compute_actions(), what downstream outputs actually change? Trace the data flow from compute_narrative to terminal output. Thoroughness: very thorough.
Assistant
I'll trace the narrative system's consumption path thoroughly. Let me start by searching for all call sites of the key functions and understanding the data flow.
Assistant
Let me get more targeted searches for the data flow:
Assistant
Now let me examine the scan command and how it uses the narrative:
Assistant
Let me read the scan command and trace through the flow:
Assistant
Now let me look at the integrity_report and agent_context which seem to be where the coaching is:
Assistant
Now let me check the next and plan commands to see if they use narrative actions:
Assistant
Now let me search for how the narrative is used in other commands, particularly show and status:
Assistant
Now let me check how the narrative actions are actually used in the rendering:
Assistant
Let me search for where narrative actions are actually rendered/printed:
Assistant
Now let me check where print_ranked_actions and print_agent_plan are called:
Assistant
Let me look at the actual rendering in show and status:
Assistant
Now let me check the status command's rendering:
Assistant
Perfect! Now let me check how query.json is built in the next command and other places:
Assistant
Now let me check the plan triage command to see if it uses narrative actions:
Assistant
Let me check what plan triage actually does with narrative:
Assistant
Let me search for where action_engine.compute_actions is called to see the full flow:
Assistant
Perfect! Now I have a comprehensive understanding. Let me search for where strategy.hint is rendered:
Assistant
Perfect! Now I have enough information. Let me compile a comprehensive summary of the narrative consumption flow.
Summary of Narrative System Consumption Flow
Based on my thorough analysis of the codebase, here's how the narrative output flows from compute_narrative() to terminal outputs:
1. Where compute_narrative() is called from
compute_narrative() is invoked from these commands:
next / backlog → /app/commands/next/queue_flow.py:_render_non_empty_queue() (line 362)
show → /app/commands/show/cmd.py:cmd_show() (line 139)
status → /app/commands/status/flow.py:_build_status_context() (line 78)
Each call passes a NarrativeContext with the command name, language, plan data, and optionally the diff.
2. Where narrative actions are rendered
Actions from narrative["actions"] are displayed in terminal output only, through two functions:
a) print_ranked_actions() in /app/commands/helpers/rendering.py (lines 83-109)
Sorts actions by impact and priority
Limits to top 3 actions
Called from:
show command → /app/commands/show/render.py:show_agent_plan() (line 256)
status command → /app/commands/status/render.py:show_agent_plan()
Output format:
code
Score context: (or "Biggest things impacting score:")
- detector_name: N open — `command_to_run`
b) show_agent_plan() / print_agent_plan() in commands
Show the single top action with: Agent focus: \{top['command']}` — {top['description']}`
Called from:
User
I need to understand what issues get fed into the plan triage workflow and how the LLM prompts are constructed for each stage. Explore thoroughly:
engine/_plan/triage/prompt.py — how the triage prompt is built, what issue data is included, any filtering of issues before they're sent to triage
app/commands/plan/triage/runner/ — the orchestrator code that runs stages, what data each stage receives
app/commands/plan/triage/stages/ — individual stage implementations, what each stage's prompt looks like, what decisions each stage makes
engine/_plan/triage/playbook.py — stage definitions and their guidance text
Any filtering or scoping that happens before issues enter triage — do ALL open issues go in? Are low-impact/low-confidence ones included?
How clusters are created from triage output — what criteria determine grouping?
engine/_plan/triage/apply.py and parsing.py — how triage results get applied to the plan
I want to find: where are the decision points about WHAT gets triaged and HOW deeply? Are there any existing gates/filters? Read actual code. Thoroughness: very thorough.
Assistant
I'll explore the triage workflow thoroughly, examining how issues are prepared, filtered, and fed into the LLM prompts at each stage.
Assistant
Let me read the key source files systematically:
User
I need to find the actual LLM prompt templates/builders used for each triage stage. Look for:
Any files in app/commands/plan/triage/stages/ — what prompt does each stage (observe, reflect, organize, enrich, sense-check) build?
Files in app/commands/plan/triage/runner/ — how do orchestrators construct prompts for each stage?
Any "system prompt" or "user prompt" construction for triage stages
What instructions/guidance the LLM gets during each stage — are there YAGNI/KISS-like instructions already?
How the observe stage decides what to analyze vs skip
How the organize stage decides how many clusters to create and what goes in each
Search broadly for prompt construction patterns. Look for string templates, f-strings building prompts, any markdown prompt builders. Thoroughness: very thorough.
Assistant
Now let me read the triage parsing and apply modules:
Assistant
I'll conduct a comprehensive search for the triage stage prompt templates and builders. Let me start by exploring the directory structure and searching for prompt-related code.
Assistant
Now let me explore the app-level orchestration:
Assistant
Great! I can see there are dedicated prompt files in the runner directory. Let me search comprehensively for prompt templates and construction patterns.
Assistant
Now let me read all the key prompt files to understand the full picture:
Assistant
Now let me look at the validation requirements and examine the orchestrator files:
Assistant
Let me read more about the orchestrator and filtering:
Assistant
Let me read the main orchestrator files to see how prompts are constructed and executed:
Assistant
Now let me search for how the orchestrators decide on batching and decision logic:
Assistant
Now let me check the dismiss module and look at what filters exist:
Assistant
Perfect! Let me read the observe_batches and see how the system decides on clustering:
Assistant
Let me check how batches are created in the codex parallel orchestrator:
Assistant
Let me read the organize stage implementation:
Assistant
Let me also look at the pipeline execution to see the full flow and understand the decision logic:
Assistant
Let me check the stage_prompts_instruction_shared to understand more guidance:
Assistant
Let me also check what happens in the reflect stage and how issue filtering works:
Assistant
Now let me search for any existing YAGNI/KISS/simplicity prompting in the actual instruction blocks:
Assistant
Perfect! Now let me look for any additional prompt files or guidance:
Assistant
Let me check the schema definitions to see any filtering or scoping logic:
Assistant
Let me read the codex_runner to understand how prompts are actually executed:
Assistant
Now let me check the reflect and enrich stages more carefully:
Assistant
Perfect. Now let me check if there are any additional files that contain more prompt logic or decision-making:
Assistant
Now let me check for any policy guidance or decision rules:
Assistant
Now let me check the full triage_clusters function and look at the remaining logic:
Assistant
Perfect. Now let me examine cluster creation and how the enrich stage works:
Assistant
Perfect. Now let me get the remaining information about how enrich and sense-check work with respect to clustering:
Assistant
Excellent. Let me now verify how issues are initially sourced and if there are any confidence/impact filters at the state level:
Assistant
Now let me look at how the prompt filters are applied before sending to triage:
Assistant
Perfect! Now let me create a comprehensive summary by examining one more critical area - the actual orchestration that feeds data:
Assistant
Perfect! Now I have a comprehensive understanding. Let me compile all the findings into a detailed report.
Summary of LLM Prompt Templates & Builders for Triage Stages
I've conducted a thorough exploration of the triage prompt architecture. Here are my key findings:
1. Prompt File Architecture
Core prompt builders (in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/runner/):
stage_prompts.py — Main orchestrator; builds complete stage prompts via build_stage_prompt()
stage_prompts_instruction_blocks.py — Stage-specific instruction text (observe/reflect/organize/enrich/sense-check)
stage_prompts_instruction_shared.py — Shared preambles, CLI references, and standard blocks
stage_prompts_observe.py — Batch-specific observe prompts for parallel execution
stage_prompts_sense.py — Content & structure verification prompts for sense-check
stage_prompts_validation.py — Validation requirement blocks per stage
def group_issues_into_observe_batches(si: TriageInput, max_batches: int = 5):
# Group by review dimension (e.g., "type_safety", "abstraction_fitness", etc.)
# Load-balance issues across up to 5 parallel batches
# Each batch gets dimension-group(s) to keep load balanced
Automatically groups issues by dimension (not by file/directory)
Creates up to 5 parallel batches (max_batches parameter)
Load-balances so each batch gets ~equal issue count
Each batch runs independently, verifies ALL its issues
REFLECT Stage — What Gets Clustered vs Skipped
Assistant
Perfect. Now I have everything I need to provide a comprehensive answer. Let me compile my findings:
Summary: Triage Workflow - Issues, Filtering, Data Flow, and Decision Points
Based on my thorough exploration of the codebase, here's the complete picture of what issues get fed into the triage workflow and how the LLM prompts are constructed:
1. WHAT ISSUES GET TRIAGED - The Filtering Gates
Initial Filtering in collect_triage_input() (prompt.py:123-154)
The triage input is collected from all open review issues only:
python
def _split_open_issue_buckets(issues: dict[str, dict]) -> tuple[dict[str, dict], dict[str, dict]]:
open_review = {}
open_mechanical = {}
for issue_id, issue in issues.items():
if issue.get("status") != "open": # GATE 1: Must be OPEN
continue
if issue.get("detector") in ("review", "concerns"): # GATE 2: Must be review/concerns detector
open_review[issue_id] = issue
continue
open_mechanical[issue_id] = issue
return open_review, open_mechanical
Key decision points:
NO confidence/severity filters at triage input collection time — ALL open review issues are included, regardless of confidence (low/medium/high) or impact
Mechanical issues (imports, formatting, etc.) are excluded from the main triage input (open_issues dict) but kept in mechanical_issues for context only
Closed/resolved issues are completely filtered out before building the prompt
What Gets Included in TriageInput (prompt.py:18-30)
refactor_N - refactor/manual actions, grouped by file overlap (union-find)
test_coverage - isolated lane
debt_review - wontfix debt review
Sets run_first=True on cleanup lane if its files overlap with other lanes.
Flags lanes as significant (parallelizable) if: file_count >= 5 OR total_impact >= 1.0 AND not "debt_review" or "run_first".
C. Strategy Hint Generation (compute_strategy_hint)
One or two-sentence execution guidance:
code
if recommendation == "strong" and can_parallelize:
"Run fixers first — they cover {coverage}%. Then {lane_count} independent workstreams..."
elif recommendation == "strong":
"Run fixers first — they cover {coverage}%. Then rescan..."
elif can_parallelize:
"{lane_count} independent workstreams, safe to parallelize..."
elif phase == "maintenance":
"Maintenance mode — address new issues as they appear."
elif phase == "stagnation":
"Try a different dimension to break the plateau."
else:
"Work through actions in priority order..."
Then appends review action count if present.
Critical: There are NO YAGNI/KISS filters in the strategy engine — it recommends based on coverage, impact, and parallelizability only.
Debt action threshold - Only appended if overall_gap > 2.0 pts (line 104, action_engine_routing.py)
FP rate calibration - Only surfaces if rate >30% (signals.py, reminders_primary.py)
Reminder decay - Suppresses after 3 shows (except no_decay cases)
Significance threshold for lanes - file_count >= 5 OR impact >= 1.0 (strategy_engine_lanes.py, line 199)
Review queue heuristic - Only shows "review not run" if never cached AND strict >=80% (signals.py, lines 62-73)
Wontfix stale reminder - Only after 20 scans AND 60+ days (reminders_primary.py, lines 107-124)
What DOES NOT EXIST:
No min impact threshold on actions — all actions >0 impact are shown
No max action count cap — no "limit to top N"
No detector-level filtering — all open detectors generate actions
No phase-based action suppression — maintenance phase doesn't reduce actions
No "signal quality" gate before showing actions — all actions shown regardless of noise
No YAGNI pruning — no "hide unless critical" logic
No KISS simplification hooks — action list not simplified by complexity heuristics
INTEGRATION POINTS FOR ADVISORY FILTERING
If you wanted to add YAGNI/KISS filtering, these are the natural hooks:
In compute_actions(ctx) after _assign_priorities() — Filter actions before return
In compute_strategy() — Suppress low-impact lanes before hint generation
In compute_reminders() before return — Add a filtering stage for "noise"
In _build_refactor_entry() or _append_*_actions() — Skip actions below threshold
In compute_lanes() return — Remove "insignificant" lanes before returning
In compute_narrative() return — Post-process NarrativeResult before serialization
The cleanest pattern would be to add a filter function in action_engine_routing.py called something like _filter_by_significance() that takes actions and phase/context, then apply it after _assign_priorities() but before _annotate_with_clusters().
That's the complete narrative layer system. There are NO existing YAGNI/KISS hooks — everything that computes as applicable is presented. The system is transparent but unfiltered.
Items in dimensions with more score headroom (more room to improve) get higher impact and sort first. This directs effort toward the highest-leverage improvements.
Processing:
Uses compute_health_breakdown() to normalize dimension scores
For subjective items: looks up detail.dimension_name in impact lookup
For mechanical issues: uses detector → dimension mapping
Falls back to 0.0 if dimension not found
Standalone Threshold Logic (Lines 146–153)
Filters out "evidence-only" issues that lack sufficient confidence:
python
def build_issue_items(...) -> list[WorkQueueItem]:
for issue_id, issue in scoped.items():
# ... other filters ...
detector = issue.get("detector", "")
meta = DETECTORS.get(detector)
if meta and meta.standalone_threshold:
threshold_rank = CONFIDENCE_ORDER.get(meta.standalone_threshold, 9)
issue_rank = CONFIDENCE_ORDER.get(issue.get("confidence", "low"), 9)
if issue_rank > threshold_rank: # confidence is worse than threshold
continue # SKIP this issue
Logic: If a detector has a standalone_threshold (e.g., "medium"), only issues with confidence >= that threshold appear as queue items. Below-threshold issues still affect scores but are filtered out of view.
This is key decision point #1 for surfacing items.
A state machine that determines the current lifecycle phase:
python
if fresh_boundary and initial_review_items:
return PHASE_REVIEW_INITIAL # ← Start here after plan reset
if objective_items:
return PHASE_EXECUTE # ← Main execution phase
if scan_items:
return PHASE_SCAN # ← Run scans/deferred items
if postflight_review_items:
return PHASE_REVIEW_POSTFLIGHT
if postflight_workflow_items:
return PHASE_WORKFLOW_POSTFLIGHT
if triage_items:
return PHASE_TRIAGE_POSTFLIGHT
return PHASE_SCAN # ← Default fallback
True if plan is None OR plan.plan_start_scores.reset == true
Used to force initial-review subjective dimensions to the front on plan reset
Execution vs Backlog Partitioning
(_execution_items_for_phase(), lines 168–199):
PHASE_REVIEW_INITIAL → execution = initial review items only
PHASE_EXECUTE → execution = planned objective items only (not all objective)
PHASE_SCAN → execution = deferred or run-scan item (one at a time)
Other phases → execution = items for that phase
Backlog (lines 272–277) = all items not in execution for current phase
Objective Item Classification
(_is_objective_item(), lines 88–93):
python
def _is_objective_item(item: WorkQueueItem, *, skipped_ids: set[str]) -> bool:
return (
item.get("kind") in {"issue", "cluster"}
and item.get("detector", "") not in NON_OBJECTIVE_DETECTORS
and item.get("id", "") not in skipped_ids
)
This system implements a multi-layered filtering + ranking architecture where items are partitioned by phase, filtered by multiple policies, ranked by impact & confidence, and finally sorted by plan position. The key insight: "surface vs suppress" is determined by a cascade of filters applied before sorting, while ranking within each partition follows a clear hierarchy of impact, confidence, and artifact type.
Design Goals
YAGNI: Don't surface work that isn't needed yet. In early phases, suppress complex refactoring until cheap wins are done. Don't recommend major restructuring when the codebase scores well.
KISS: Keep recommendations simple and focused. Cap visible actions. Prefer "do the easy thing" framing. When multiple fix paths exist, highlight the simpler one.
Constraints
Changes should be additive (new filtering/capping logic), not restructuring existing code
Should work with the existing phase system
Backward compatible — no changes to state format or CLI interface
Should be tunable (thresholds as constants, not magic numbers)
Design a concrete implementation plan. For each change, specify:
Which file(s) to modify
What function(s) to add or modify
The exact logic/algorithm
How it interacts with existing code
Focus on the minimal set of changes that delivers the most value. Avoid over-engineering the YAGNI/KISS implementation itself.
code
# New constant:
MAX_ACTIONS = 7 # Cap visible actions to keep recommendations focused
# After impact floor filter:
prioritized = prioritized[:MAX_ACTIONS]
# Re-number priorities after filtering/truncation:
for i, action in enumerate(prioritized, 1):
action["priority"] = i
Why 7: Enough for one action per type (auto_fix, reorganize, refactor, manual_fix, debt_review) plus a couple extra for multiple detectors in the same type. Low enough to never feel overwhelming.
Change 3: "Good enough" messaging in strategy hints
Problem: When score is 90+ and remaining actions have low impact, strategy still pushes "work through actions in priority order." No recognition that remaining work is diminishing returns.
Logic: Add an early-return check before the existing phase-based logic. This uses data already available in the function's parameters.
code
# New constant:
GOOD_ENOUGH_SCORE_THRESHOLD = 90 # Consider "good enough" above this score
# In compute_strategy_hint, add a new parameter `strict_score: float | None = None`
# and check at the top of the function body, after existing lines:
total_impact = sum(
lane.get("total_impact", 0)
for lane in lanes.values()
if lane_name != "debt_review"
)
if strict_score is not None and strict_score >= GOOD_ENOUGH_SCORE_THRESHOLD and total_impact < 3.0:
return (
"Score is strong. Remaining items are diminishing returns — "
"focus on new features unless a specific issue bothers you."
)
Caller change needed: compute_strategy() in strategy_engine.py must pass strict_score through to compute_strategy_hint(). This requires compute_strategy() to accept strict_score as a parameter, and core.py to pass strict_score when calling compute_strategy().
Specifically:
strategy_engine.py line 35: add strict_score: float | None = None parameter to compute_strategy()
strategy_engine.py line 61: pass strict_score=strict_score to compute_strategy_hint()
core.py line 105: pass strict_score=strict_score to compute_strategy()
Change 4: Phase-aware tier gating for actions
Problem: In early_momentum phase, MAJOR_REFACTOR (tier 4) actions surface alongside AUTO_FIX actions. Users should focus on cheap wins first.
Function to modify: compute_actions() -- add a phase parameter
Logic: When phase is early_momentum or first_scan, suppress actions whose detector is tier 3+ (judgment/refactor). This requires looking up the detector's tier from the registry.
code
# New constant:
PHASE_TIER_GATES: dict[str, int] = {
"first_scan": 2, # Only show T1-T2 (auto_fix, quick_fix)
"early_momentum": 3, # Show T1-T3, suppress major_refactor
}
# In compute_actions, after building the full actions list but before return:
max_tier = PHASE_TIER_GATES.get(phase)
if max_tier is not None:
from desloppify.base.registry import DETECTORS
prioritized = [
action for action in prioritized
if action.get("detector") is None # debt_review has no detector
or DETECTORS.get(action["detector"], DetectorMeta(...)).tier <= max_tier
]
Caller changes:
ActionContext in action_models.py: add phase: str = "" field
core.py line 96-103: pass phase=phase to ActionContext
compute_actions reads ctx.phase
Interaction with Change 1-2: This filter runs before impact floor and cap, in the same function. Order: generate all -> tier gate -> impact floor -> cap -> re-number priorities.
Change 5: "Probably fine" annotation on strategy hints
Problem: Strategy hints never say "this is probably fine, don't bother." They always push toward more work.
Function to modify: compute_strategy_hint() (same function as Change 3)
Logic: This is a refinement of Change 3. When in maintenance phase and there are zero significant lanes, strengthen the existing maintenance message.
code
# Replace the existing maintenance check (line 79-80):
if phase == "maintenance":
if not any(
lane.get("total_impact", 0) >= 1.0
for lane_name, lane in lanes.items()
if lane_name != "debt_review"
):
return "Codebase is in good shape. No high-impact work remaining — focus on features."
return "Maintenance mode — address the remaining items when convenient, not urgent."
This replaces the current terse "Maintenance mode -- address new issues as they appear" with impact-aware messaging.
Implementation Sequence
Change 1 + 2 (impact floor + cap): These are the highest-value changes. A single edit session in action_engine.py plus two constants. Everything downstream benefits immediately.
Change 4 (tier gating): Requires a small data-flow change (phase through ActionContext) but delivers strong YAGNI value -- early users don't see scary refactoring recommendations.
Change 3 + 5 (strategy messaging): Both touch strategy_engine_hints.py and the calling chain. Lower priority because they're messaging-only, but complete the KISS story.
Constants Summary
All thresholds as named constants (not magic numbers), all in the file they're used in:
Constant
Value
File
MIN_ACTION_IMPACT
0.5
action_engine.py
MAX_ACTIONS
7
action_engine.py
PHASE_TIER_GATES
{"first_scan": 2, "early_momentum": 3}
action_engine.py
GOOD_ENOUGH_SCORE_THRESHOLD
90
strategy_engine_hints.py
Testing Approach
Unit tests for compute_actions with various phase/impact combinations to verify filtering
Unit test for compute_strategy_hint with high score + low remaining impact
Existing tests should pass unchanged since these are additive filters (actions list gets shorter, never longer)
Self-scan test: run python -m desloppify --lang python scan --path desloppify and verify actions count is capped and low-impact items are gone
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/intelligence/narrative/action_engine.py - Primary target: impact floor, action cap, and tier gating all apply here
/Users/user_c042661f/Documents/desloppify/desloppify/intelligence/narrative/strategy_engine_hints.py - "Good enough" and "probably fine" strategy messaging
/Users/user_c042661f/Documents/desloppify/desloppify/intelligence/narrative/action_models.py - Add phase field to ActionContext dataclass
/Users/user_c042661f/Documents/desloppify/desloppify/intelligence/narrative/core.py - Thread phase and strict_score through to action/strategy computation
/Users/user_c042661f/Documents/desloppify/desloppify/intelligence/narrative/strategy_engine.py - Pass strict_score through to compute_strategy_hint()
The system has guards that prevent starting triage:
If objective backlog still has work (unless --attestation override provided)
If unconfirmed stage reports from prior triage still exist (unless override)
4. Triage Stage Workflow Items in snapshot.py
The stages themselves are persisted in the plan under epic_triage_meta:
epic_triage_meta.triage_stages dict: keyed by stage name ("observe", "reflect", etc.)
Each stage entry contains:
report: the stage report text (user/agent analysis)
confirmed_at: ISO timestamp when confirmed (if confirmed)
confirmed_text: the attestation that confirmed it
cited_ids: issue IDs referenced in the report
Plus stage-specific data (issue counts, recurring patterns, cluster names, etc.)
When a later stage is modified, earlier confirmations are cascade-cleared (later stages lose their confirmed_at marker and must be re-confirmed).
Stage Records come from /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/stages/records.py which encapsulates how each stage's data is recorded.
5. Files in engine/_plan/ Related to Triage
Core triage modules:
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/triage/core.py - whole-plan triage orchestration API (legacy one-shot triage)
6. User Journey: "I run plan triage, what happens?"
Default Dashboard Display (no args):
When you run desloppify plan triage with no arguments, you see the dashboard rendered by /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/display/dashboard.py:
code
Cluster triage
───────────────────────────────────────────────────
Open review issues: N
Goal: identify contradictions, resolve them, then group...
Preferred: staged runner workflow (Codex or Claude).
Codex: desloppify plan triage --run-stages --runner codex
Claude: desloppify plan triage --run-stages --runner claude
[Stage Progress Summary]
[Current Clusters]
[Unclustered Issues]
[Action Guidance]
Case 1: Fresh Start (no observe yet, no prior triage)
code
Next step: use staged runner (Codex or Claude)
Or fallback: desloppify plan triage --stage observe --report "..."
(themes, root causes, contradictions between issues — NOT a list of IDs)
Case 2: Observe Done, Working Through Stages
If reflect not done: shows reflect runner with instruction
If organize not done: shows cluster creation/enrichment commands
If enrich not done: shows enrichment guidance
If sense-check not done: shows sense-check runner
If all done: shows completion runner with --strategy "same" option
Case 3: Triage Complete, New Issues Arrived
code
Two paths available:
Fast-track: desloppify plan triage --confirm-existing --note "..." --strategy "same" --confirmed "I have reviewed..."
Full re-triage: desloppify plan triage --run-stages --runner codex
desloppify plan cluster create <name> --description "..."
desloppify plan cluster add <name> <patterns>
desloppify plan cluster update <name> --steps "step1" "step2"
5. Completion Strategy:
code
desloppify plan triage --complete --strategy "execution plan here..."
OR for incremental changes only:
code
desloppify plan triage --confirm-existing --strategy "same" --confirmed "I reviewed..."
Output/Prompts Users See
Triage Start:
code
Planning mode started (6 stages queued).
Open review issues: 42
Begin with observe:
desloppify plan triage --stage observe --report "..."
After Recording Observe:
code
Observe stage recorded: 42 issues, 3 recurring dimension(s).
Now confirm your strategy.
desloppify plan triage --confirm observe
┌─ Strategic briefing (share with user before organizing) ─┐
│ [Summarized themes from observe] ...
└────────────────────────────────────────────────────────┘
After Confirming Observe:
code
Stage: OBSERVE — Analyse issues & spot contradictions
──────────────────────────────────────────────────
Your analysis covered 42 issues across 5 dimensions:
[dimension]: N issues
You cited 15 issue IDs in your report.
✓ Observe confirmed.
Organize Stage Feedback:
code
Organize stage recorded: 8 enriched cluster(s).
All 42/42 issues are in clusters.
✓ Ready to enrich and sense-check.
desloppify plan triage --stage enrich --report "..."
Completion:
code
✓ All 5 triage stages complete.
Ready to execute: desloppify next
Key Architecture Insights
Triage is staged, not monolithic: The old triage_epics() in engine._plan.triage.core was a single LLM call. The new system breaks it into 6 sequential interactive stages, allowing human review/intervention at each step.
Stages are workflow items: They live in the plan's queue_order, so they can be queued, deferred, resumed, and tracked alongside objective work.
Confirmation is attestation-based: Each stage requires a human attestation (at least 30 chars for basic stages, 80+ for observe) that proves they read/reviewed the work.
Cascade invalidation: Modifying an earlier stage invalidates later confirmations—users must re-confirm the chain.
Two runner paths:
Codex: Orchestrator runs all 5 stages (observe→sense-check) in parallel/pipeline, building prompts from live plan data
Claude: Orchestrator runs stages sequentially with deeper reflection
Manual fallback: Users can record stages manually via --stage <name> --report "...", then use --confirm <name> --attestation "..." to validate.
Async friendly: Users can --start triage, work through stages over time, and resume later. The system tracks progress in epic_triage_meta.triage_stages.
Key Files to Review:
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan/triage/workflow.py - main workflow router
(Auto-fixable batch, 47 issues)
────────────────────────────────────────────────────
Cluster summary (in yellow)
Action plan: (if steps defined)
1. [ ] Step one
2. [x] Step two (checked)
3. [ ] Step three
Priority: complete before other clusters (cyan, if dependency_order ≤ 2)
Files: (count breakdown or "Spread across N files")
path/to/file.py (12)
path/to/other.py (8)
... and 3 more files
Sample:
- First issue summary
- Second issue summary
- ... and 44 more
Try auto first: desloppify autofix detect_name ... (cyan)
If auto finds 0, drill into individual issues:
Action: desloppify plan resolve "cluster-name" ... (cyan)
Drill in: desloppify next --cluster cluster-name --count 10 (dim)
Mark step done: desloppify plan cluster update cluster-name --done-step N (dim)
For workflow items (triage workflow stages):
code
[TRIAGE] Stage description [blocked] if blocked
Stage: Observe | Organize | Enrich (dim)
Reason: why stage is present (dim)
4. Post-Item Nudges
Single item resolution hints:
code
Resolve with:
desloppify plan resolve "issue-id" --note "<what you did>" --confirm
desloppify plan skip --permanent "issue-id" --note "<why>" --attest "..."
For subjective review items:
code
Review with:
desloppify review --prepare --dimensions dimension-key
Note: re-review scores what it finds — scores can go down if issues are discovered.
Run `desloppify review --run-batches --dry-run` to generate prompt files...
5. Follow-up Context (when not a single item)
Score status:
Frozen score block (if plan was just started): plan-start strict vs. live estimate with delta
North star (if not frozen): current → target strict score
Live queue block: breakdown of remaining work by category
Subjective bottleneck warning (when objective work is done but subjective dimensions drag):
code
Subjective dimensions are the main bottleneck (-X pts vs -Y pts mechanical).
Code fixes alone won't close the gap — run `desloppify review --prepare` and follow
your skill doc's review workflow to re-score.
Rescan nudge (when queue > 10 items):
code
Tip: after structural fixes (splitting files, moving code), rescan to let cascade
effects settle: `desloppify scan --path .`
Subjective summary:
code
Subjective: N dimensions below target, M stale, K unassessed, L review issues open, O files need review.
Run `desloppify show subjective` for details.
Uncommitted reminder:
code
N resolved issue(s) uncommitted — `desloppify plan commit-log` to review
6. Final Execution Prompt
code
✨
Start working on the task above. When done: `desloppify plan resolve`.
Full queue: `desloppify plan show`.
✨
desloppify plan queue Output
A compact tabular view of all upcoming work:
1. Queue Header
code
Queue: N ordered, S subjective, K skipped items
Focus: cluster-name (if focused)
(P skipped items hidden — use --include-skipped)
2. Cluster Banners (if plan-ordered clusters exist and not in cluster-drill view)
New: N | Auto-resolved: M | Reopened: K | Fixed: J
3. Score Delta
code
Overall score: 75.2 → 78.5% (+3.3)
Strict score: 68.4 → 71.2% (+2.8) ← your north star
Objective: 82.1 → 84.0% (+1.9)
4. Plan Workflow Nudge (if this is the plan's first scan):
code
🎯 First scan with a living plan — this plan snapshot is now frozen.
Scores above reflect live state. Finish items on the queue, then re-scan
to finalize and unlock an updated score.
5. Visibility Hints
code
* Fast scan — slow phases (duplicates) skipped (yellow)
* 45 issues hidden (showing 20/detector). Use `desloppify show <detector>` to see all. (dim)
6. Detector Progress Bars
code
Detector progress (open issues by detector):
──────────────────────────────────────────────────
structural ████████░░░░░░ 64% 23 open / 36
duplication ██████░░░░░░░░░ 42% 15 open / 26
smells █████████████░░ 86% 3 open / 21
Biggest score drags (fixing these dimensions has the most impact):
- File health: -5.23 pts (score 72.5%, 12.1% of mechanical pool)
- Duplication: -3.87 pts (score 68.0%, 9.8% of mechanical pool)
9. Dimension Deltas (if scores changed)
code
Moved:
File health 83.2% → 72.5% (-10.7%) (red, if down)
Test health 77.1% → 81.3% (+4.2%) (green, if up)
10. Post-Scan Warnings (if issues detected)
code
12 issues reopened — was a previous fix reverted? (yellow)
⟳ 3 chronic reopeners — run `desloppify show --chronic` to see them. (yellow)
11. Narrative Headline & Coaching
code
→ Phase: Consolidation. Next: finish structural fixes, then re-review subjective dimensions. (cyan)
Run `desloppify next` for the highest-priority item.
Run `desloppify plan` to see the updated living plan. (if plan active)
Run `desloppify status` for the full dashboard.
12. LLM Agent Summary (if running inside agent)
code
────────────────────────────────────────────────────
INSTRUCTIONS FOR LLM
IMPORTANT: ALWAYS present ALL scores to the user after a scan.
Show overall health (lenient + strict), ALL dimension scores,
AND all subjective dimension scores in a markdown table.
The goal is to maximize strict scores. Never skip the scores.
Overall score: 75.2/100
Objective score: 82.1/100
Strict score: 68.4/100
Verified score: 65.1/100
Score guide: [explanations of each score type]
[Full dimension table in markdown format]
[Score drag summary]
[Stats line: total, open, fixed, wontfix, ignored]
LIVING PLAN ACTIVE: 42 ordered, 3 skipped.
Focused on: structural-batch (18 items remaining).
The plan is the single source of truth for work order.
Use `desloppify next` which respects the plan.
Use `desloppify plan` to view and update it.
────────────────────────────────────────────────────
✨
Hey — please follow the living plan. Run `desloppify next` for your next
execution task. No need to reply, just continue.
✨
Agent vs. human modes: LLM-facing output (markdown tables, explicit instructions) appears only when is_agent_environment() detects agent env vars
Living plan integration: every command shows plan context (frozen scores, focus, queue position, overrides)
Narrative coaching: computed per command (scan/next/backlog) via NarrativeContext with phase/headline/strategy/actions
The coaching output in scan is the richest — it includes warnings, dimension breakdowns, drag analysis, and explicit LLM instructions. In next, the coaching is contextual (north star, frozen scores, bottleneck hints). In plan queue, the focus is on compact browsability with cluster drill-down support.
/app/commands/plan/cmd.py (static steps, not narrative)
When a living plan is active, these both bypass narrative actions entirely and render the plan focus instead.
3. Where strategy.hint is displayed
strategy.hint appears in LLM-facing output only:
print_llm_summary() in /app/commands/scan/reporting/agent_context.py (lines 279-335)
Called from scan command after post-scan analysis
Only prints if running in agent environment (CLAUDECODE, AGENT, DESLOPPIFY_AGENT, etc.)
Output format (lines 206-221):
code
Current status: {headline}
Strategy: {hint}
Top action: `{command}` — {description}
4. How query.json is written
query.json is written by write_query() from /base/search/query.py, called by each command:
Command
Call Site
Payload includes
scan
/app/commands/scan/cmd.py:179
build_scan_query_payload() with narrative
next
/app/commands/next/queue_flow.py:151
build_query_payload() with narrative
show
/app/commands/show/cmd.py:194
build_show_payload() with narrative
status
/app/commands/status/render.py:224
write_status_query() with narrative
The payload structure includes "narrative": {...} containing the full result from compute_narrative().
5. Where scan "CUSTOM COACHING" / "INSTRUCTIONS FOR LLM" comes from
This is rendered in print_llm_summary() in /app/commands/scan/reporting/agent_context.py (lines 347-358):
code
"─" * 60
INSTRUCTIONS FOR LLM
IMPORTANT: ALWAYS present ALL scores to the user after a scan.
...
(followed by dimension table, drag summary, stats summary, workflow guide)
Then: _print_narrative_status(narrative) ← prints headline, strategy.hint, top action
This block is only shown when running in an agent environment.
6. Does next command use narrative actions?
No, next does NOT use narrative actions for work selection. The flow:
Computes narrative (line 362 in queue_flow.py)
Includes it in the query payload for agent consumption
But the actual work queue is built from build_execution_queue() which uses:
Plan order (if active)
Dimension tiers and scoring
NOT narrative actions
The narrative is purely informational for terminal/agent display.
7. Does plan triage use narrative actions?
No, plan triage does NOT call compute_narrative() or use narrative actions. It operates independently:
Observes existing issues and dimensions
Triages them into clusters
Organizes them into the work queue
Completely bypasses the narrative system
8. If you filter actions in compute_actions(), what changes?
Filtering actions affects ONLY these terminal outputs:
show command terminal: Top 3 ranked actions disappear from "Score context:" section
status command terminal: Top 3 ranked actions disappear from "Score context:" section
scan command LLM block: Top action: line disappears from _print_narrative_status() section
next command terminal: No visible change (actions not rendered there)
All work queues remain unchanged — they use scoring, tiers, and plan data, not narrative actions.
The narrative system is fundamentally advisory only — it informs the agent/user what the highest-leverage work is, but doesn't drive the actual queue construction. The next and plan triage commands use separate, independent work queue logic.
Key Insight
The narrative system is purely informational coaching. It tells agents what they should focus on and why, but the actual next command uses plan-aware scoring to determine which items to work on. If you filtered actions, agents would see less guidance, but their work queue would remain the same.
Instruction in stage_prompts_instruction_blocks.py lines 102-170:
Decision rules from the prompt:
Filter: Only genuine issues (from observe verdicts). Issues marked false-positive or over-engineering MUST be skipped
Map: Track which files/directories each issue touches
Group: Cluster issues by file/directory proximity (not by dimension)
Skip: Issues marked false-positive, exaggerated, or over-engineering by observe
Order: Identify cross-cluster dependencies
Check recurring patterns: Compare against resolved history for root causes
Account for every hash exactly once — mandatory ledger
Key quote from reflect instructions:
"Issues with verdict false-positive or over-engineering should go into skip lines, not clusters."
ORGANIZE Stage — Cluster Creation
Instruction in stage_prompts_instruction_blocks.py lines 228-257:
Decision logic:
Must follow reflect's blueprint exactly
Skip issues observe flagged false-positive or over-engineering (mandatory, not optional)
One step per file or logical change (NOT one step per issue) — consolidation happens here
Set --depends-on when clusters touch overlapping files
- Read the actual source code. Every opinion must come from reading the file.
- Have specific opinions (not "seems like an issue")
- Do the hard thinking (figure out WHY things relate)
- Don't take shortcuts (read all files, use subagents to parallelize)
- Follow the authoritative stage contract in the prompt
- hash: <issue-hash>
verdict: <verdict-type>
verdict_reasoning: <what you found in code>
files_read: [<actual files opened>]
recommendation: <what to do next>
Must cite ≥10% of issues (or 5, whichever smaller) in report
Goal: Make every step executor-ready. Test: "Could a developer with zero context execute this step without asking?"
Requirements (ALL BLOCKING):
Every step MUST have --detail with 80+ chars INCLUDING at least one file path
Every step MUST have --issue-refs linking to review issue hash(es)
Every step MUST have --effort tag (trivial|small|medium|large) — set INDIVIDUALLY
File paths in detail MUST exist on disk (validator checks)
No step may reference skipped/wontfixed issues
Common lazy patterns to avoid:
Copying issue description as step detail (says WHAT'S WRONG, not WHAT TO DO)
Vague action verbs ("refactor", "clean up", "improve") — must be specific
Guessing file paths (must verify they exist)
Bulk effort tags (each step gets individual tag)
Example GOOD detail:
code
--detail "In src/shared/hooks/billing/useAutoTopup.ts lines 118-129, add onMutate
handler to capture previous queryClient state before optimistic update. In onError
callback, restore previous state and change showToast from false to true."
--issue-refs 79baeebf --effort small
Two parallel subagents: Content (per-cluster) + Structure (global)
Content checks:
Line numbers match code
Function/variable names exist
Counts are accurate
Problem still present (not already fixed)
Effort tags realistic
No duplicate work between clusters
No over-engineering (abstractions that don't justify themselves)
Structure checks:
File-touch graph validation
Clusters sharing files have --depends-on
Rename/remove operations have cascade steps
No circular dependencies
Filtering: Flag steps to remove/simplify if net-negative
4. HOW CLUSTERS ARE CREATED FROM TRIAGE OUTPUT (apply.py:187-249)
After the LLM triage result is parsed, clusters are created via apply_triage_to_plan():
python
def apply_triage_to_plan(plan, state, triage, trigger="manual"):
"""
1. Creates/updates triage clusters in plan["clusters"]
2. Marks dismissed issues as triaged_out skips
3. Reorders queue_order to group cluster members by dependency_order
4. Updates epic_triage_meta with snapshot hash
"""
Cluster Creation Logic (apply.py:109-133)
Clusters are named with epic/ prefix
For each cluster in LLM output:
Create if it doesn't exist OR doesn't have a prior thesis
Update if it exists and has a thesis (preserves in_progress status)
def dismiss_triage_issues(triage, order, skipped, now, version, scan_count):
"""Move triage-dismissed issues out of queue and into skipped metadata."""
# From triage.dismissed_issues list
# From epic_data.get("dismissed", []) in clusters
# Creates triaged_out skip entries with reason and note
Reordering (apply.py:136-155)
Issues are reordered to group by cluster membership and dependency_order:
python
def _reorder_queue_by_dependency(order, triage, dismissed_ids):
# Extract all issue IDs from clusters in dependency_order
# Place cluster-member issues first (ordered by cluster order)
# Place non-epic items at the end
5. PARSING & VALIDATION (parsing.py)
The LLM JSON output is parsed and validated with issue ID filtering:
python
def parse_triage_result(raw: dict, valid_ids: set[str]) -> TriageResult:
"""
valid_ids = set of open review issue IDs
- Invalid issue IDs are SILENTLY DROPPED from clusters
- Dismissed issues must have valid IDs
- Clusters with no name or no issues become None (dropped)
- Directions normalized to VALID_EPIC_DIRECTIONS
- Every epic, dismissed issue, and contradiction parsed separately
"""
Issue Citation Extraction (parsing.py:65-79)
Flexible matching supports:
Full issue IDs: review::abcdef12
Bracketed short IDs: [abcd1234]
Bare 8+ char hex suffixes matching a known issue
Substring literal matching
6. KEY DECISION POINTS & GATES
Stage
Gate
Filtering
Flexibility
Input
Only OPEN + detector in (review, concerns)
No confidence filter
Mechanical issues for context only
Observe
Batched by dimension
All issues verified
Verdict determines downstream treatment
Reflect
Coverage ledger hard constraint
All issues must be mapped to cluster or skip
Observe verdicts are authoritative
Organize
False-positive/over-eng must skip
LLM reflects blueprint
Can adjust for code mismatches
Enrich
File paths must exist
One step per logical change
Sub-agent parallelization per cluster
Sense-Check
Line numbers, effort, names verified
Detects over-engineering
Can remove/simplify net-negative steps
Apply
Invalid issue IDs silently dropped
Reorders by dependency
Preserves in_progress status
7. NO LOW-IMPACT/LOW-CONFIDENCE FILTERS
Critical insight: The triage system does NOT filter issues based on:
Confidence level (low/medium/high) at input time
Severity or impact scores
Dimension risk or importance
All open review issues are included. The observe stage is responsible for filtering via verdict (false-positive, over-engineering). The reflect stage then accounts for every issue exactly once — it's a hard constraint.
8. CLUSTERING CRITERIA
From the reflect/organize instructions, clusters are formed based on:
Root cause: Issues sharing a common underlying problem
File proximity: Issues touching the same file or directory
Dependency: Whether fixing one requires fixing another
Architectural area: Features, modules, or subsystems
Risk profile: Agent-safe (scriptable) vs manual judgment
NOT by:
Dimension (though patterns are noted)
Confidence
Complexity
Issue type
File Paths (Read-Only Exploration Only)
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/triage/prompt.py — Input collection and prompt building