Do a thorough exploration of the desloppify codebase focusing on how the "plan" and "next" commands work, and how state is managed. I need to understand:
How the plan command generates and displays the prioritized task list (look at plan.py, plan_cmd.py or similar)
How the "next" command picks the highest-priority item (look at next_cmd.py or similar)
How state is persisted in .desloppify/state-{lang}.json and .desloppify/query.json
The structure of findings, tiers, and how items are ordered/prioritized
Any existing mechanisms for user customization of the plan
Look at files like:
desloppify/cli.py (entry point)
desloppify/plan.py or similar
desloppify/state.py
desloppify/scoring.py
desloppify/narrative/ directory
Any cmd files (fix_cmd.py, etc.)
Give me a detailed summary of the architecture, data structures, and flow.
Assistant
I'll start by exploring the directory structure and key files in parallel.
Assistant
The codebase has been restructured. Let me explore the actual command and core directories.
Assistant
Now I can see the structure. Let me read the key files in parallel.
Assistant
Now let me read the planning internals and the work queue system.
Assistant
Now let me read the core planning, work queue, and state files in parallel.
Assistant
Now let me read the work queue core, ranking, state schema, and persistence files.
Assistant
Now let me read the remaining key files: the work queue helpers, the scoring internals, the state scoring, the config system, and the command registry.
Assistant
Now let me read a few more files to complete the picture: the scoring policy, query writing, the state helpers used by commands, and the narrative system.
Assistant
Let me also check the query path resolution, the core query module, and the enums to complete the picture.
Assistant
Let me check one final thing -- the merge logic and the CommandRuntime dataclass.
Assistant
I now have a comprehensive understanding of the codebase. Here is the detailed summary.
Desloppify Architecture: Plan, Next, and State Management
1. High-Level Structure
The codebase has been refactored into a layered architecture:
desloppify/state.py and desloppify/scoring.py -- Thin facade modules that re-export from engine._state and engine._scoring.
2. State Persistence
2a. State File Location
State files live at .desloppify/state-{lang}.json (e.g., state-python.json, state-typescript.json). Resolution logic is in /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/state.py:
If --state CLI arg is provided, that path is used directly.
Otherwise, language is detected (from --lang arg or auto-detection), and the path becomes PROJECT_ROOT / ".desloppify" / f"state-{lang_name}.json".
For non-scan commands, if the detected state file doesn't exist, it falls back to the sole existing state-*.json file (if exactly one exists).
2b. StateModel Schema
Defined in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/schema.py:
python
User
I'm planning a "living plan" feature for desloppify. I need to deeply understand the current state persistence and work queue system so I can figure out where user overrides (reordering, clustering, annotations) would fit.
Please read and summarize the key data structures and logic in these files:
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/schema.py - The StateModel and Finding types. What fields exist? What's extensible?
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/persistence.py - How state is loaded/saved. What happens to unknown keys?
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/merge.py - How scan results merge into state. What happens when findings disappear?
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py - The build_work_queue function and QueueBuildOptions
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/ranking.py - item_sort_key and build_finding_items - how priority is computed
/Users/user_c042661f/Documents/desloppify/desloppify/engine/planning/render.py - How plan markdown is generated
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next.py - How next command picks and displays items
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan_cmd.py - Plan command handler
For each file, note:
The exact data structures (TypedDicts, dataclasses, etc.)
Where user overrides could be injected without breaking existing logic
Be very thorough - read every file completely.
Assistant
I'll read all 8 files in parallel to start.
User
I'm researching a "living plan" feature for the desloppify project. Please help me understand:
Check GitHub for related issues. Run these commands:
gh issue list --repo peteromallet/desloppify --state open --limit 30 to see all open issues
Look for issues related to: plan, queue, reorder, priority, cluster, batch, living document, next command
Read any related issues with gh issue view N --comments for the most relevant ones
Look at the CLI argument structure for plan and next commands:
Read /Users/user_c042661f/Documents/desloppify/desloppify/cli.py to understand how subcommands are registered and what args plan/next accept
Read /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/runtime.py for CommandRuntime
Look at the config system:
Read /Users/user_c042661f/Documents/desloppify/desloppify/core/config.py to understand CONFIG_SCHEMA and how config is loaded/saved
This matters because user plan overrides might live in config
Check if there's any existing "user override" or "pin" or "prioritize" mechanism anywhere in the codebase.
Look at the query.json output format - read /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/query.py and any related query path files.
Give me a comprehensive summary of findings.
Assistant
I'll research this systematically. Let me start by gathering information from multiple sources in parallel.
Assistant
Now let me read the supporting files that are referenced by the main files -- the merge_findings, merge_history, helpers, and planning types.
Assistant
Good, I found issue #153 which is directly about "Active Planning Mode: make plan a living document". Let me read that issue and several other related ones, plus explore the plan/next command implementations and parser structure.
Assistant
Now let me also check the scoring module to understand _recompute_stats and the state.py re-exports for completeness.
Assistant
Now let me read the plan and next command implementations, the parser_groups for their argument definitions, and search for any existing "pin"/"prioritize"/"override" mechanisms.
Assistant
Now let me read the core work queue and planning modules, plus the admin parser groups for plan/next argument details.
Assistant
Now let me look at the query.json output format and the core query module, plus the planning module's init and types.
Assistant
Let me read the remaining planning files and the next_parts modules for a complete picture, plus look at the query.json snapshot.
Assistant
Let me also check the state model for any existing priority/pin-related fields, and look at the narrative system which drives coaching output.
Assistant
Now I have a thorough understanding of all the files. Here is my comprehensive analysis:
Deep Analysis: State Persistence and Work Queue System
1. /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/schema.py -- StateModel and Finding Types
Core Data Structures:
Finding (TypedDict, all required except noted):
python
id: str # Unique finding identifier (e.g., "detector::file::hash")
detector: str # Which detector found it
file: str # File path (relative)
tier: int # 1-4 priority tier
confidence: str # "high" / "medium" / "low"
summary: str # Human-readable description
detail: dict[str, Any] # Free-form detail payload (varies by detector)
status: FindingStatus # "open" | "fixed" | "auto_resolved" | "wontfix" | "false_positive"
note: str | None # User/system annotation
first_seen: str # ISO timestamp
last_seen: str # ISO timestamp
resolved_at: str | None # ISO timestamp when resolved
reopen_count: int # Times this finding reopened
Optional Finding fields (NotRequired):
python
suppressed: bool # Ignored by pattern
suppressed_at: str | None # When suppression applied
suppression_pattern: str | None # Which pattern matched
resolution_attestation: dict[str, ...] # Proof of fix (anti-gaming)
lang: str # Language tag
zone: str # Zone classification (production/test/config/etc.)
Assistant
Now I have a comprehensive picture. Let me provide the full summary.
Comprehensive Research Summary: "Living Plan" Feature for Desloppify
1. Related GitHub Issues
Primary issue: #153 -- "Active Planning Mode: make plan a living document (reorder + context + next integration)"
This is the main tracking issue. It has two substantive self-comments from the repo owner:
Comment 1 (Problem statement): The snapshot-only planning model loses strategy context when findings are re-imported, rephrased, or superseded during review cycles. The failure mode: "the queue is accurate now, but strategy context evaporates when findings are re-imported/rephrased/superseded." A comparison with a manual 10-step cleanup plan showed that durable context (root-cause epics, rationale, completion gates) prevents priority whiplash. Key request: When a source finding disappears, keep the plan item alive as superseded/needs-remap with previous rationale and candidate replacement links, instead of silently dropping context.
Comment 2 (Clustering): Flat item lists still create churn. Items should be clustered by root cause/epic, architectural seam/package area, and dependency chain. If an underlying finding is superseded, keep the cluster and remap members.
Related issues:
Issue
Title
Relevance
#152
Score-pressure workflow nudges
Companion feature -- keep scan/next/plan continuously target-focused without hard enforcement
#157
Gate subjective reruns behind a drained plan
Plan-aware gating: don't re-run subjective review if plan items still open
#160
Auto-refresh and report updated score/scorecard after all score-changing operations
Tighter scan-plan-score feedback loop
2. CLI Argument Structure
Parser architecture:
/Users/user_c042661f/Documents/desloppify/desloppify/app/cli_support/parser.py -- top-level parser, delegates to _add_*_parser builders
/Users/user_c042661f/Documents/desloppify/desloppify/app/cli_support/parser_groups.py -- defines _add_scan_parser, _add_next_parser, _add_show_parser, etc.
/Users/user_c042661f/Documents/desloppify/desloppify/app/cli_support/parser_groups_admin.py -- defines , , etc.
User
I'm designing a "Living Plan" feature for the desloppify codebase health tool. I need a detailed implementation plan that fits naturally into the existing architecture. Here's the full context:
Problem (from GitHub Issue #153)
The plan is currently a snapshot - regenerated from scratch every time. This causes:
Strategy context evaporates when findings are re-imported/rephrased/superseded across scan cycles
Engineers lose continuity and re-derive intent each cycle
No way to reorder the work queue based on architectural strategy
No clustering by root cause/epic - flat lists cause priority whiplash from raw volume shifts
No way for agents (or humans) to bundle related items into batches of work
What users want:
Reorder the queue: pin items to top, defer items, set custom priority that next respects
Cluster/bundle items: group related findings into named epics/batches (e.g., "auth cleanup", "boundary seams")
Add context/rationale: annotate items or clusters with why they matter
Survive scan churn: when a finding disappears (auto_resolved), keep planning context alive with superseded/needs-remap status and candidate replacement links
next integration: next should respect user ordering and show cluster context
Current Architecture
State
StateModel TypedDict in engine/_state/schema.py, total=False (unknown keys survive round-trips)
I'll start by thoroughly exploring the existing codebase to understand the architecture before designing the plan.
Assistant
Let me focus the search on the project source files, excluding .venv.
Assistant
Now let me read the core files that are critical to this design.
Assistant
Now let me look at the state persistence layer and the next command's rendering.
Assistant
Now let me look at the parser admin file, the work queue helpers, and the planning types to understand the full picture.
Assistant
Now let me look at the CLI parser and command dispatch to understand how commands are wired up.
Assistant
Now let me check how the discovery API's safe_write_text works and how the state module re-exports things, and look at the resolve command for patterns.
Assistant
Now let me look at the existing state.py re-exports and the _state/__init__.py to understand the state module's public interface.
Assistant
Now let me check the engine's work_queue public facade and the planning common module.
Assistant
Let me also check the discovery_api for safe_write_text since plan persistence will follow the same pattern.
Assistant
Now let me look at how finding IDs are constructed to understand ID churn patterns.
Assistant
Good. Finding IDs follow the pattern detector::relative_file::name. Now let me look at the CLI dispatch to understand how commands are routed.
Assistant
Now I have a thorough understanding of the codebase. Let me compile everything into a comprehensive implementation plan.
Let me first check a few more things -- the zone_cmd pattern (since it uses subcommands for a dict-type feature, which is the pattern we'd follow), and existing test patterns.
Assistant
Now I have a comprehensive understanding of the codebase. Let me provide the full implementation plan.
Living Plan Feature -- Implementation Plan
1. Architecture Overview and Design Decisions
Answer to Question 1: Data Model for Plan Overrides
The plan state should be a separate JSON document (plan.json) that references findings by ID and maintains user intent that survives scan churn. The data model has three top-level concepts:
Clusters -- named groups of findings with rationale and ordering
Supersession Map -- tracks finding IDs that disappeared and links them to candidate replacements
Answer to Question 2: plan.json vs state.json
Separate file (.desloppify/plan.json). Reasons:
State is machine-generated (scan merge); plan is human/agent-authored intent. Mixing them creates merge conflicts.
State already has total=False with unknown-key preservation, but plan data is structurally different (it references findings, not defines them).
Separate file allows plan to be version-controlled independently from state, which is already large.
Follows the precedent of config.json being separate from state-{lang}.json.
Answer to Question 3: Work Queue Integration
The item_sort_key function in ranking.py is the single chokepoint. The plan will be loaded alongside state and injected into build_work_queue via a new optional plan parameter on QueueBuildOptions. The sort key will prepend a "user priority" tuple element that overrides the default tier/confidence ranking when present.
Answer to Question 4: Scan Merge Reconciliation
After merge_scan runs and auto-resolves disappeared findings, a new reconcile_plan function will:
For each plan-referenced finding ID that is now auto_resolved, mark it superseded in plan with timestamp and the last known finding metadata (detector, file, summary).
Search the new findings for candidates sharing the same (detector, file) or (detector, similar-summary) pattern.
Attach candidate IDs to the superseded entry so the user/agent can remap.
Answer to Question 5: CLI Commands
New plan subcommands (follows the and subcommand pattern):
User
I need to deeply understand how the "ignore" and "wontfix" systems work in desloppify, and specifically how they affect the different score types (overall, objective, strict, verified_strict). This is relevant because we're building a "defer" capability in a new living plan feature, and we need to understand if/how deferring items should interact with scoring.
Please thoroughly investigate:
The ignore system:
Read desloppify/core/config.py - how ignore patterns work in config
Read desloppify/engine/_state/filtering.py - how _matches_pattern and ignore suppression works
Read desloppify/engine/_state/merge.py - how ignore patterns suppress findings during scan merge
How suppressed findings affect scoring - are they counted? excluded?
The wontfix status:
Read desloppify/engine/_state/resolution.py - how resolve wontfix works
How wontfix affects each score type (overall vs strict vs objective)
Read desloppify/engine/_state/scoring.py or desloppify/engine/_scoring/ - look for how different statuses map to pass/fail in scoring
The wontfix_snapshot and wontfix_scan_count fields - what are they for?
Read desloppify/engine/_scoring/ - the scoring engine, look for how lenient vs strict modes differ
Specifically: in lenient mode (overall_score, objective_score), which statuses count as "passing"?
In strict mode (strict_score, verified_strict_score), which statuses count as "passing"?
How does wontfix specifically factor into strict vs lenient?
The resolve command:
Search for the resolve command handler (grep for cmd_resolve or resolve in app/commands/)
What statuses can findings be resolved to?
What's the attestation mechanism?
Any existing "defer" or "skip" mechanism:
Search for anything like defer, skip, postpone, backlog in the codebase
Is there any concept of "I know about this but not now"?
Give me a complete picture of how ignore/wontfix/statuses interact with scoring, and whether "deferring" in the plan should be score-aware or score-neutral.
Assistant
I'll conduct a thorough investigation of the ignore, wontfix, and scoring systems. Let me start by exploring the key files in parallel.
Assistant
Now let me read the core files in parallel.
Assistant
Excellent. The FAILURE_STATUSES_BY_MODE dict on line 183 of policy/core.py is the key. Now let me read the scoring engine and related files in parallel.
Assistant
Now let me search for the resolve command and any existing defer/skip concepts.
Assistant
Let me read the resolve command and the scan wontfix handler, plus the schema for Finding status types.
Assistant
Now let me look at the resolve selection/validation logic to understand what statuses are accepted, and the enums for finding statuses.
Assistant
Now let me check the CLI parser to see what statuses are accepted by the resolve command, and search for the parser registration.
Assistant
Now let me look at the suppressed findings and how they interact with scoring -- particularly checking if suppressed findings are filtered out of score computation.
Assistant
Important finding: the scoring engine (detection.py) does NOT filter by suppressed. It only looks at status and checks against FAILURE_STATUSES_BY_MODE. Let me verify this by looking more closely at how suppressed findings have their status set, and look at the parser_groups file for the resolve command's accepted statuses.
Assistant
Now let me look at the work queue to understand how suppressed findings are filtered for display vs scoring, and search for "suppressed" in the scoring candidates iterator.
Assistant
Now I have the full picture. Let me also quickly check the scan reporting analysis file for the note about suppressed findings and strict scores.
Assistant
I now have a complete picture. Here is the comprehensive analysis:
Complete Analysis: Ignore, Wontfix, and Scoring Interactions
matched_ignore_pattern(finding_id, file, ignore_patterns) checks three pattern forms:
Glob patterns (contains *): if pattern contains ::, it globs against the finding_id; otherwise it globs against the file path.
ID prefix patterns (contains ::): checks if finding_id.startswith(pattern).
File path patterns (plain string): exact match against the file or its rel() form.
Suppression during scan merge (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/merge_findings.py, lines 139-184):
During upsert_findings(), every incoming finding is checked against ignore patterns.
If matched:
New findings: inserted into state with suppressed=True, suppressed_at=now, suppression_pattern=<pattern>. They are counted as ignored_count but NOT counted as new_count. They do NOT trigger changed_detectors.
Existing findings: updated with suppressed=True. If the finding was previously fixed, auto_resolved, or false_positive, its status is reset to "open" with the note "Suppressed by ignore pattern -- remains unresolved for score integrity". This is crucial -- suppressed findings are NOT removed from state; they retain status "open".
(, lines 107-132):
User
I'm building a "living plan" feature for desloppify. I need to check for any adjacent capabilities that should be considered. Please investigate:
The narrative/strategy system - Read desloppify/intelligence/narrative/strategy.py and related files. Does the narrative system generate any kind of "recommended next steps" or "strategy lanes" that could benefit from plan integration? How does the strategy interact with the next command?
The fix command and batch operations - Read desloppify/app/commands/fix/ to understand how batch fixes work. If a cluster has auto-fixable items, should we surface "fix this whole cluster" as a command?
The show command - grep for cmd_show to find the show command. Does it show anything plan-related? Is there a show queue or similar?
Review system - Does the review system produce findings that map to plan items? Read desloppify/app/commands/review/ briefly. Could review recommendations feed into plan clusters?
The scan reporting - Read desloppify/app/commands/scan/scan_reporting_analysis.py briefly. After a scan completes, what coaching/narrative is shown? Should plan context appear in post-scan reporting?
Check if there's any "focus mode" or "scope" persistence — does the tool remember what you were working on?
For each, briefly summarize what exists and whether it should integrate with the living plan feature.
Assistant
I'll investigate all six areas in parallel to understand the adjacent capabilities.
Assistant
The first Read failed because the path structure might differ. Let me discover the actual directory layout first.
Assistant
Good, now I can see the actual structure. The strategy file is strategy_engine.py, not strategy.py. Let me now read all the key files in parallel.
Assistant
Good progress. Now let me read the remaining files in parallel -- fix command, show command, review, scan reporting, plan_cmd, next command, and check for focus/session persistence.
Assistant
Good. Now let me read the remaining key files -- the fix command, scan reporting analysis, the planning engine, work queue, and check for focus/session persistence in the CLI.
Assistant
Now let me read the remaining files: planning engine core, work queue, the CLI for focus/session args, and the review entrypoint.
Assistant
Now let me read the CLI parser to check for focus/session/scope args, and the planning render/core for the plan markdown generation.
Assistant
Let me now check the CLI parser for focus/session args, and the concerns engine mentioned in the show command.
Assistant
Now let me check for tree command --focus, and grep for any persistence of "last worked on" or similar state.
Assistant
I now have a thorough picture of all six areas. Here is my report.
Investigation Report: Adjacent Capabilities for "Living Plan" Feature
What exists: The strategy engine is rich and highly relevant. compute_strategy() already produces:
Lanes (compute_lanes()): Partitions actions into parallelizable work streams -- cleanup, restructure, refactor_N, test_coverage, debt_review. Uses union-find on file overlap to determine independence.
Fixer leverage (compute_fixer_leverage()): Estimates how much automated fixers cover, with a recommendation field (strong / moderate / none).
Strategy hint (compute_strategy_hint()): A 1-2 sentence execution plan (e.g. "Run fixers first -- they cover 40% of findings. Then 3 independent workstreams, safe to parallelize.").
Actions (from action_engine.py): Prioritized action list with types auto_fix, manual_fix, reorganize, refactor, debt_review. Each action is annotated with a lane field by compute_strategy().
The NarrativeResult type (line 140 of types.py) bundles: phase, headline, dimensions, actions, strategy, tools, primary_action, why_now, verification_step, risk_flags, strict_target, reminders.
User
I need a comprehensive audit of every system in desloppify that tells the agent "what to do" or "what to work on next." The goal is to identify everything that could compete with or contradict a new "living plan" feature that should become the SINGLE source of truth for work prioritization.
Please investigate ALL of the following:
Tier system (T1/T2/T3/T4) - How tiers are used, where they appear in output, whether agents are told to "work on T1 first". Read engine/planning/common.py for tier labels.
Narrative system actions/primary_action - Read intelligence/narrative/action_engine.py and intelligence/narrative/core.py. The narrative system computes "actions" with priority and recommends a "primary_action". Where does this appear? Is it shown to agents?
Strategy hints - Read intelligence/narrative/strategy_engine.py. It computes strategy hints like "Run fixers first." Where are these shown?
show_agent_plan() / print_agent_plan() - Grep for these function names. Where are they called? What do they render? This sounds like it directly competes with the living plan.
print_ranked_actions() - Grep for this. What does it show?
Post-scan coaching - Read app/commands/scan/scan_reporting_analysis.py fully. What specific "do this next" guidance does it give after a scan?
The CUSTOM COACHING section - The MEMORY.md mentions "After running scan, the output includes CUSTOM COACHING (strategy, next steps)." Find where this is rendered.
Skill docs / agent instructions - Search for files in core/skill_docs.py or any .md skill files that give agents instructions about workflow. These might tell agents to follow a specific order.
query.json payload - Read app/commands/next_parts/output.py to see what guidance metadata is included for agent consumption.
The status command - grep for cmd_status. Does it give prioritization guidance?
The dimension health table in plan output - does it suggest specific actions per dimension?
Any "coaching", "guidance", "recommendation", "suggested", "hint" strings - Grep broadly for these words to find guidance scattered across the codebase.
For each system found, report:
What it tells the agent to do
Where it appears (which commands, which output)
Whether it could contradict the living plan's ordering
Whether it should be removed/modified/kept as-is
Be very thorough — the user wants to find everything.
Assistant
I'll conduct a comprehensive audit of all systems that provide work prioritization guidance in the desloppify codebase. Let me start by exploring the project structure and then investigate each system systematically.
Assistant
Let me start by exploring the project structure and then begin reading all the relevant files in parallel.
Assistant
Good, I have the file locations. Now let me read all the key files in parallel.
Assistant
Good. Now let me read the remaining critical files - the status_parts/render.py, show/render.py and cmd.py, the SKILL.md templates, the next command, and grep for coaching/guidance terms.
Assistant
Now let me read the remaining key files: SKILL.md, the next command, the reminders system, the scan reporting dimensions, the zone command, and the next_parts render.
Assistant
Let me read a few more files to complete the picture - the scan command output section (where the post-scan coaching renders), the work_queue, the scan_reporting_presentation, and the scan_reporting_llm.
Assistant
Now let me read the remaining files - the workflow guide text, the fix review_flow AGENT PLAN, review prepare AGENT PLAN, and the planning generate_plan_md function.
Assistant
Let me read the remaining key files - the workflow guide text, the plan rendering, and the issues command.
Assistant
Let me get a few more remaining pieces -- the scan_reporting_summary.py for strict target progress, and the _constants.py in narrative for DETECTOR_TOOLS.
Assistant
Now I have a thorough understanding of all the systems. Let me compile the comprehensive audit.
Assistant
Comprehensive Audit: All "What To Do Next" Systems in Desloppify
Executive Summary
There are 12 distinct systems that tell agents what to work on. They are layered, sometimes redundant, and occasionally capable of giving contradictory prioritization. Here is every one of them, in order from most authoritative to most peripheral.
1. TIER SYSTEM (T1/T2/T3/T4)
What it tells the agent: Work items are classified into 4 priority tiers. The labels strongly imply a priority ordering.
plan command (/Users/user_c042661f/Documents/desloppify/desloppify/engine/planning/render.py lines 208-221): Generates markdown sections ## Tier 1: Highest priority (...), ## Tier 2: ..., etc., with open item counts.
next command (/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next_parts/render.py lines 46-63): "Tier Navigator" header shows counts per tier, and suggests desloppify next --tier N commands.
status command: show_tier_progress_table shows per-tier progress bars as a fallback when dimension scores are unavailable.
Every individual queue item: Each item displayed by next is labeled (Tier N, confidence).
Workflow guide (/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_reporting_text.py line 25-26): Decision guide says "Tackle: T1/T2 (high impact), auto-fixable, security findings" and "Consider skipping: T4 low-confidence, test/config zone findings."
class StateModel(TypedDict, total=False):
version: Required[int] # Always 1
created: Required[str] # UTC ISO timestamp
last_scan: Required[str | None] # Last scan timestamp
scan_count: Required[int]
overall_score: Required[float] # Lenient, includes subjective
objective_score: Required[float] # Lenient, mechanical only
strict_score: Required[float] # Strict, includes subjective
verified_strict_score: Required[float] # Only scan-verified fixes
stats: Required[StateStats] # Aggregated status counts
findings: Required[dict[str, Finding]] # All findings by ID
scan_coverage: dict[str, ScanCoverageRecord]
score_confidence: dict[str, Any]
scan_history: list[ScanHistoryEntry]
subjective_integrity: Required[SubjectiveIntegrity]
subjective_assessments: Required[dict[str, SubjectiveAssessment]]
concern_dismissals: dict[str, ConcernDismissal]
Key sub-types:
StateStats: total, open, fixed, auto_resolved, wontfix, false_positive, plus by_tier breakdown.
ScanHistoryEntry: Per-scan snapshot with timestamp, scores, diff counts, suppression metrics.
2c. Finding Structure
The central data unit is the Finding TypedDict (in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/schema.py):
python
class Finding(TypedDict):
id: str # e.g. "unused::src/utils.py::unused_import_os"
detector: str # "unused", "structural", "smells", "review", etc.
file: str # Relative file path
tier: int # 1-4 (see below)
confidence: str # "high", "medium", "low"
summary: str # Human-readable description
detail: dict # Detector-specific payload (lines, count, category, etc.)
status: FindingStatus # "open", "fixed", "auto_resolved", "wontfix", "false_positive"
note: str | None
first_seen: str # UTC ISO timestamp
last_seen: str
resolved_at: str | None
reopen_count: int # How many times reopened after resolution
# Optional fields:
suppressed: bool
lang: str # "python", "typescript", etc.
zone: str # "production", "test", "config", etc.
Finding IDs are constructed by make_finding() as "{detector}::{relative_file}::{name}".
2d. Load and Save
In /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/persistence.py:
load_state(path): Reads JSON from disk. On corruption, tries .json.bak backup, then falls back to empty_state(). Calls ensure_state_defaults() to normalize, then validate_state_invariants().
save_state(state, path): Calls _recompute_stats() (which recalculates all scores and stats from findings), validates, creates a .json.bak backup, then atomically writes via safe_write_text() (temp file + os.replace).
2e. Query Output
query.json is written to .desloppify/query.json (path from /Users/user_c042661f/Documents/desloppify/desloppify/core/query_paths.py). It is a structured JSON payload containing the latest command output (items, queue metadata, narrative, config, scores). Written by the next command handler and other commands for tool integration.
3. Tier System
Defined in /Users/user_c042661f/Documents/desloppify/desloppify/engine/planning/common.py:
Each finding has an inherent tier (1-4) set by its detector. Additionally, the work queue computes an effective_tier -- subjective findings and subjective dimension items are always forced to tier 4 regardless of their original tier.
Gets state from CommandRuntime (loaded during CLI init in _load_shared_runtime).
Calls require_completed_scan(state) to gate on a prior scan.
Calls planning_mod.generate_plan_md(state) to produce a markdown string.
Outputs to file (with --output) or stdout.
Plan generation (/Users/user_c042661f/Documents/desloppify/desloppify/engine/planning/render.py -> generate_plan_md):
Header (_plan_header): Title with date, health scores (overall/objective/strict), open/fixed/wontfix/auto-resolved counts, codebase metrics (files, LOC, directories).
Dimension health table (_plan_dimension_table): Markdown table with columns: Dimension, Tier, Checks, Issues, Health%, Strict%, Action. Iterates the canonical DIMENSIONS list (derived from scoring policies), then appends custom non-subjective dimensions, then subjective measures. Subjective rows are sourced from the scorecard projection system.
Tier summary (_tier_summary_lines): Per-tier progress bars: "Tier N: X open / Y total (Z% addressed)".
Per-tier sections (_plan_tier_sections): This is the core prioritized task list. It calls build_work_queue() with count=None (all items), status="open", include_subjective=True, and no_tier_fallback=True. Items are grouped by tier then by file. Each item is rendered as a markdown checkbox with confidence badge and finding ID. Subjective items get a [subjective] tag.
Addressed section (_addressed_section): Summary of non-open findings (fixed, wontfix, etc.).
# Required fields:
version: int # Always 1 currently (CURRENT_VERSION = 1)
created: str # ISO timestamp
last_scan: str | None # ISO timestamp of last scan
scan_count: int # Number of scans performed
overall_score: float # Lenient score including subjective
objective_score: float # Mechanical-only score
strict_score: float # Strict scoring including subjective
verified_strict_score: float # Only credits scan-verified fixes
stats: StateStats # Aggregate counters
findings: dict[str, Finding] # All findings keyed by ID
subjective_integrity: SubjectiveIntegrity # Anti-gaming metadata
subjective_assessments: dict[str, SubjectiveAssessment] # Per-dimension scores
# Optional fields (total=False):
scan_coverage: dict[str, ScanCoverageRecord]
score_confidence: dict[str, Any]
scan_history: list[ScanHistoryEntry] # Last 20 scan snapshots
concern_dismissals: dict[str, ConcernDismissal]
Extension Points:
Finding.detail is dict[str, Any] -- completely open-ended. Already used for dimension_name, count, holistic flag, etc. This is the obvious place for user annotations per-finding.
StateModel is total=False -- any new top-level key survives json.dumps/json.loads round-tripping. The ensure_state_defaults() function only calls setdefault() on known keys; it does not strip unknown keys.
Finding is also technically a TypedDict but used as dict throughout; extra keys on findings would survive persistence too (they are just dict(finding) copies).
StateStats and DimensionScore are both total=False -- extensible.
The ScanHistoryEntry has total=False and is append-only (last 20 entries capped).
Key Observation for Living Plan: The note field on Finding is currently the only user-writable annotation. It is a single string. There is no structured metadata for user overrides (priority override, cluster membership, custom labels, etc.).
2. /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/persistence.py -- State Loading/Saving
Load Flow:
load_state(path) reads JSON from disk (default: .desloppify/state.json)
On corruption: tries .json.bak backup, then renames corrupt file to .json.corrupted, returns empty_state()
On version mismatch: warns but proceeds (forward-compatible)
Calls _normalize_loaded_state() which runs ensure_state_defaults() then validate_state_invariants()
ensure_state_defaults() uses setdefault() -- unknown keys are preserved
validate_state_invariants() only checks: findings is dict, stats is dict, each finding has valid id/status/tier/reopen_count
Calls _recompute_stats() which recalculates all scores, stats, dimension_scores from findings
Calls validate_state_invariants()
Creates .json.bak backup of previous file
Writes atomically via safe_write_text() (temp file + os.replace)
What Happens to Unknown Keys:
They survive round-tripping.ensure_state_defaults only does setdefault(). json.dumps serializes everything. _load_json reads back everything. No key stripping anywhere.
This means you can add a "plan_overrides" or "user_annotations" top-level key to StateModel and it will persist across save/load cycles without any code changes to persistence.
Important:_recompute_stats() runs on every save. It recomputes stats, dimension_scores, overall_score, objective_score, strict_score, verified_strict_score, score_confidence, and subjective_integrity. These are all derived data -- the source of truth is findings + potentials + subjective_assessments.
auto_resolve_disappeared() -- findings not in current scan get auto_resolved:
Skips findings from different language
Skips findings outside scan_path scope
Skips findings from suspect_detectors (detectors that probably didn't run)
Skips findings matching exclusion patterns
_mark_stale_on_mechanical_change() -- when mechanical findings change, marks related subjective assessments as stale
_recompute_stats() -- recalculates all scores
_append_scan_history() -- records snapshot (capped at 20)
Returns ScanDiff
What happens when findings disappear: They get status: "auto_resolved" with a resolution_attestation of kind: "scan_verified". They are NOT deleted -- they remain in state["findings"] with resolved status. This is important: the findings dict is append-only for tracking history.
Where overrides could be injected: The merge pipeline does not touch arbitrary extra keys on findings. If a finding had user_priority: 1 or cluster: "auth-cleanup", those keys would survive merge updates (since previous.update(...) only overwrites specific known fields).
4. /Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py -- Work Queue Construction
QueueBuildOptions (frozen dataclass):
python
tier: int | None = None # Filter to specific tier
count: int | None = 1 # Max items to return (None = all)
scan_path: str | None = None # Scope to path
scope: str | None = None # Glob/pattern filter
status: str = "open" # Status filter
include_subjective: bool = True # Include subjective dimension items
subjective_threshold: float = 100.0 # Score threshold for subjective items
chronic: bool = False # Only chronic reopeners
no_tier_fallback: bool = False # Don't fall back to nearest tier
explain: bool = False # Include ranking explanation
WorkQueueResult (TypedDict):
python
items: list[dict] # Ranked queue items
total: int # Total count before slicing
tier_counts: dict[int, int] # Items per tier
requested_tier: int | None
selected_tier: int | None
fallback_reason: str | None
available_tiers: list[int]
grouped: dict[str, list[dict]] # Items grouped by key
Build Pipeline:
build_finding_items() -- converts each open finding to a queue item dict (adds kind, is_review, is_subjective, effective_tier, review_weight, subjective_score, primary_command)
Optionally appends synthetic subjective_dimension items from build_subjective_items()
Sorts all items by item_sort_key -- this is where priority ordering happens
Tier filtering: if a tier is requested and empty, falls back to nearest non-empty tier
Count slicing
Optional explain annotations
Grouping for alternate output modes
Where overrides could be injected:
The sort key is the critical control point. Currently item_sort_key() is a pure function of item fields. A user priority override could be injected by:
Adding a user_priority field to items before sorting
Wrapping item_sort_key to check for overrides
Or sorting items post-hoc with a custom comparator that respects pinned/boosted items
The scope filter is another injection point for showing only certain clusters
QueueBuildOptions could gain fields like cluster: str | None, respect_user_order: bool
group_queue_items() groups by: file, detector, tier, or "items" (flat)
Where overrides fit:
The sort key tuple is the entire ranking logic. Inserting a user_priority as the first element (or a very early element) would let users override the entire ordering:
python
(user_priority_or_default, effective_tier, ...)
Pinning: items with pinned=True could get user_priority=0 (always first)
Deferring: items with deferred=True could get user_priority=999 (always last)
Clustering: items sharing a cluster tag could be sorted adjacently by adding cluster rank to the tuple
6. /Users/user_c042661f/Documents/desloppify/desloppify/engine/planning/render.py -- Plan Markdown Generation
Calls planning_mod.generate_plan_md(state) -- delegates entirely to render.py
Either writes markdown to a file or prints to terminal
Shows agent hint about executing the plan
Where overrides fit:
The state dict passed to generate_plan_md() is the full state. If user overrides were stored in state (e.g., state["plan_overrides"]), the render functions could read them.
A --respect-overrides flag could toggle between default ordering and user-customized ordering.
Summary: Architecture for User Overrides
Data Flow Pipeline
code
scan -> merge_scan() -> state["findings"] -> save_state() -> disk
|
load_state() from disk
|
build_work_queue(state) -> sorted items -> next/plan/show
Key Injection Points
State-level (new top-level key): Add state["plan_overrides"] with structure like:
This survives persistence automatically (unknown keys are not stripped).
Finding-level (extra keys on Finding dicts): Add fields like user_priority, cluster, user_note directly onto finding dicts. These survive merge (upsert only overwrites specific fields). However, they would need to be manually preserved during the previous.update(...) in upsert_findings.
Work queue sort key: Modify item_sort_key() to accept overrides, or wrap it. The sort key is the single chokepoint for all ordering.
Plan rendering:_plan_tier_sections() calls build_work_queue() then groups by tier/file. Custom rendering could inject cluster headers, user annotations, and custom ordering.
What WON'T Break
Adding new top-level keys to state: safe (preserved by load/save)
Adding new keys to Finding dicts: mostly safe (merge updates specific fields, doesn't strip others), but auto_resolve_disappeared sets specific fields and doesn't clear extras
Adding new fields to QueueBuildOptions: safe (it's a dataclass with defaults)
Adding new sections to plan markdown: safe (just appending to lines list)
What COULD Break
Changing item_sort_key signature: every caller would need updating (core.py, any tests)
Modifying Finding TypedDict required fields: validators would reject unexpected types
Changing the meaning of tier or effective_tier: ripple effects everywhere
Storing override data inside findings dict keys that collide with scan-produced IDs
_add_plan_parser
_add_review_parser
plan command arguments (very minimal today):
python
# parser_groups_admin.py, line 418-425
def _add_plan_parser(sub) -> None:
p_plan = sub.add_parser("plan", help="Generate prioritized markdown plan from state")
p_plan.add_argument("--state", type=str, default=None)
p_plan.add_argument("--output", type=str, metavar="FILE", help="Write to file instead of stdout")
Only two args: --state (alternate state file) and --output (write to file). No filtering, no reorder, no cluster, no pin.
next command arguments (richer):
python
# parser_groups.py, lines 155-201
--state # alternate state file
--tier # filter to tier 1/2/3/4
--count # number of items (default: 1)
--scope # path, detector, ID prefix, or glob filter
--status # open/fixed/wontfix/false_positive/auto_resolved/all
--group # group by item/file/detector/tier
--format # terminal/json/md
--explain # show ranking rationale
--no-tier-fallback # don't auto-fallback to another tier
--output # write JSON/markdown to file
Command handlers:
plan command: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/plan_cmd.py -- extremely thin, just calls planning_mod.generate_plan_md(state) and prints it
next command: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next.py -- builds a QueueBuildOptions, calls build_work_queue(), enriches with narrative context, writes query.json, and renders terminal output
There are no config keys for plan overrides, pinning, prioritization, clustering, or user ordering. The zone_overrides pattern (a dict mapping paths to values, persisted in config) is the closest analog to a "user override" mechanism -- it could serve as a design precedent.
Config CLI:desloppify config set <key> <value> / desloppify config unset <key> / desloppify config show. The set_config_value function handles type coercion, and dict-type keys explicitly reject CLI set (raise ValueError("Cannot set dict key ... via CLI -- use subcommands")).
There are none. I searched for pin, prioritize, user_override, reorder, manual_priority, pinned, priority_override, user_plan, plan_override, manual_rank, focus, boost, custom_order, and user_order across the entire codebase. Zero matches in the work queue or planning engine.
The only relevant precedents are:
zone_overrides in config -- user-controlled per-path overrides persisted in config.json
ignore patterns in config -- user-controlled pattern suppression
--scope filter on next -- ephemeral (not persisted) scope filtering
--manual-override on review -- allows untrusted assessment score imports, but this is about review trust, not plan ordering
5. Work Queue and Plan Generation Pipeline
Work Queue (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/):
The queue is rebuilt from scratch on every next or plan call:
build_finding_items() in ranking.py iterates all findings from state, filtering by status/scope/chronic
build_subjective_items() in helpers.py adds synthetic T4 items for subjective dimensions below threshold
Items are sorted by item_sort_key():
python
# For findings:
(effective_tier, 0, CONFIDENCE_ORDER[confidence], -review_weight, -count, id)
# For subjective:
(effective_tier, 1, subjective_score, id)
Tier counts are computed, tier fallback logic applied if needed
Items are sliced to count and optionally explain-annotated
There is no injection point for user-defined priority overrides in this pipeline. The sort key is purely derived from finding metadata.
Plan generation (/Users/user_c042661f/Documents/desloppify/desloppify/engine/planning/render.py):
generate_plan_md() builds a static markdown document from state. It calls build_work_queue() with count=None (all items), groups by tier then by file, and renders as a checklist. There is no persistent plan state -- it is regenerated from findings on every call.
query.json output format:
The next command writes to .desloppify/query.json with this shape:
6. Key Architectural Observations for a Living Plan Feature
What exists (stateless, ephemeral):
The plan is fully regenerated from state every time desloppify plan runs
The queue ordering is computed deterministically from finding metadata
No persistent plan state, no user ordering, no clustering, no "superseded/needs-remap" tracking
The narrative system (strategy, lanes, fixer leverage) provides execution guidance but it's also computed fresh each time
What would need to change (per issue #153):
Persistent plan state -- a new data structure (likely in .desloppify/plan.json or a new section of state) to track:
User-defined ordering overrides / pinned items
Clusters (groups of findings by root cause / epic)
Superseded/remapped items (findings that disappeared but whose plan context should survive)
Rationale / notes per plan item or cluster
Plan mutation commands -- new CLI subcommands or plan sub-actions like plan pin <id>, plan cluster <ids> --name "...", plan reorder <id> --before <id>
Work queue integration -- item_sort_key() would need to consult user overrides when they exist
Plan reconciliation on scan -- when a scan produces new findings, the plan reconciler would need to match against existing plan items, mark disappeared ones as superseded/needs-remap, and suggest candidate replacements
Config integration -- plan overrides could live in config (like zone_overrides) or in a separate plan state file
Parser defined in app/cli_support/parser_groups.py and parser_groups_admin.py
Design Constraints
Must not break existing scan->state->queue->render pipeline
Must be agent-friendly (Claude Code agents are primary users alongside humans)
User overrides should be explicit opt-in, not change default behavior
Must survive finding ID churn across scans (findings get new IDs when reimported)
Should follow existing patterns (TypedDict, dataclass, atomic writes, etc.)
The plan should be stored as a separate file (.desloppify/plan.json) rather than bloating the state file
Questions to address in your plan:
What's the right data model for plan overrides (pinning, ordering, clusters, annotations)?
Should plan state live in state.json or a separate plan.json?
How should the work queue incorporate user overrides into sorting?
How should scan merge reconcile with plan state (superseded finding handling)?
What CLI commands/subcommands should be added?
How should clusters work - finding-level grouping? Named groups?
How should next change to show cluster context and respect user ordering?
How should plan change to reflect user customizations?
What's the right interaction model for agents (edit JSON directly? CLI commands? Both?)
Please provide a concrete, detailed implementation plan with specific data structures, file changes, and the order of implementation.
zone
config
code
desloppify plan # existing: generate markdown plan
desloppify plan pin <pattern> # pin finding(s) to top of queue
desloppify plan unpin <pattern> # remove pin
desloppify plan defer <pattern> # push to bottom / exclude from next
desloppify plan undefer <pattern> # remove deferral
desloppify plan annotate <pattern> --note "..." # add rationale
desloppify plan cluster create <name> --note "..." # create named cluster
desloppify plan cluster add <cluster> <pattern> # add findings to cluster
desloppify plan cluster remove <cluster> <pattern> # remove from cluster
desloppify plan cluster delete <name> # delete cluster
desloppify plan cluster list # list all clusters
desloppify plan show # show plan state (overrides + clusters + superseded)
desloppify plan reset # reset all plan overrides
Answer to Question 6: Cluster Design
Clusters are named groups stored in plan.json with:
finding_ids: ordered list of finding IDs in this cluster
created_at, updated_at: timestamps
priority: optional integer for cluster-level ordering
Finding-level grouping (not file-level). Clusters are cross-file by design.
Answer to Question 7: next Changes
next will:
Load plan.json alongside state
Pinned items float to absolute top (before tier sorting)
Deferred items sink to absolute bottom (or are excluded by default, shown with --include-deferred)
When showing a clustered item, print Cluster: <name> (<note>) context
--cluster <name> flag to filter to a specific cluster
Answer to Question 8: plan Changes
The markdown plan output will:
Show a "Pinned" section at the top for pinned items
Show clusters as grouped sections (with cluster name/note as heading)
Show a "Deferred" section at the bottom
Show "Superseded" section for orphaned plan items with remap candidates
Answer to Question 9: Agent Interaction Model
Both CLI and direct JSON editing should work:
CLI subcommands for structured operations (pin/defer/cluster)
plan.json is a well-documented, agent-editable JSON format
Agents can read plan.json, modify it, and the tool validates on load (like state does with ensure_state_defaults)
2. Concrete Data Structures
plan.json Schema
python
# In new file: desloppify/engine/_plan/schema.py
class ItemOverride(TypedDict, total=False):
"""Per-finding override stored in plan.json."""
finding_id: Required[str] # finding ID this override applies to
pinned: bool # true = float to top of queue
deferred: bool # true = sink to bottom / hide from next
priority_boost: int # signed integer: positive = higher priority, negative = lower
note: str | None # user annotation / rationale
cluster: str | None # cluster name this finding belongs to
created_at: str # ISO timestamp
updated_at: str # ISO timestamp
class SupersededEntry(TypedDict, total=False):
"""Tracks a plan-referenced finding that disappeared from scan."""
original_id: Required[str] # the finding ID that disappeared
original_detector: str # preserved for matching
original_file: str # preserved for matching
original_summary: str # preserved for human context
status: str # "superseded" | "remapped" | "dismissed"
superseded_at: str # when the finding was auto_resolved
remapped_to: str | None # new finding ID if user confirmed remap
candidates: list[str] # candidate replacement finding IDs
note: str | None # user annotation
class Cluster(TypedDict, total=False):
"""A named group of related findings."""
name: Required[str] # unique identifier, slug-style
note: str | None # rationale / description
finding_ids: list[str] # ordered list of finding IDs
priority: int # cluster-level priority (lower = higher priority)
created_at: str
updated_at: str
class PlanModel(TypedDict, total=False):
"""Root shape of .desloppify/plan.json."""
version: Required[int] # schema version (1)
created: Required[str] # ISO timestamp
updated: Required[str] # ISO timestamp
overrides: dict[str, ItemOverride] # keyed by finding_id
clusters: dict[str, Cluster] # keyed by cluster name
superseded: dict[str, SupersededEntry] # keyed by original finding_id
3. File-by-File Implementation Plan
Phase 1: Plan Data Layer (foundation)
New file: /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/__init__.py
New file: /Users/user_c042661f/Documents/desloppify/desloppify/engine/_plan/persistence.py
load_plan(path: Path | None = None) -> PlanModel -- load from disk or return empty, following the same pattern as load_state in engine/_state/persistence.py
Add plan_sort_key(item: dict, plan: dict) -> tuple that returns (0 if pinned, 1 if normal, 2 if deferred, *existing_sort_key) -- this is a simpler alternative to partitioning, making pinned/deferred a leading sort dimension.
Alternatively (and more cleanly): keep item_sort_key unchanged and handle plan overrides as a post-sort partition step in core.py. This avoids coupling the sort key to plan state. I recommend this approach.
In _render_item, after the existing detail/suggestion output, add plan context:
python
if item.get("plan_cluster"):
print(colorize(f" Cluster: {item['plan_cluster']['name']}", "cyan"))
if item['plan_cluster'].get('note'):
print(colorize(f" Context: {item['plan_cluster']['note']}", "dim"))
if item.get("plan_note"):
print(colorize(f" Plan note: {item['plan_note']}", "dim"))
if item.get("plan_pinned"):
print(colorize(" [PINNED]", "yellow"))
p_next.add_argument("--cluster", type=str, default=None, help="Filter to a specific cluster")
p_next.add_argument("--include-deferred", action="store_true", help="Include deferred items")
Phase 5: Scan Merge Hook
Modify: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_cmd.py (or wherever the scan command calls merge_scan and save_state)
After merge_scan and save_state, call:
python
from desloppify.engine.plan import load_plan, save_plan, reconcile_plan_after_scan
plan = load_plan()
if plan.get("overrides") or plan.get("clusters"):
result = reconcile_plan_after_scan(plan, state)
if result.changes:
save_plan(plan)
# Print reconciliation summary
Plan CLI commands accept patterns using the same matching logic as resolve (finding IDs, prefixes, detector names, file paths, globs). Reuse match_findings from engine/_state/resolution.py:
python
from desloppify.state import match_findings
matched_ids = match_findings(state["findings"], patterns)
This ensures the UX is consistent: if desloppify resolve fixed "unused::*" works, then desloppify plan pin "unused::*" works too.
5. Agent-Friendliness Design
For agent interaction, the key considerations are:
plan.json is directly editable -- agents can cat .desloppify/plan.json, modify it, and write back. The schema is validated on load.
query.json integration -- plan context (cluster membership, pin/defer status, notes) is included in the next command's query.json payload so agents consuming the structured output get the full picture.
Stable finding-ID references -- plan references finding IDs which follow the detector::file::name pattern. When IDs churn, the supersession map with candidates makes remapping explicit rather than silent.
CLI commands are composable -- each operation (pin, defer, cluster add) is a single CLI call that can be scripted or chained.
6. Implementation Order
Phase 1: Plan Data Layer -- schema, persistence, operations, reconcile. Pure functions, no CLI changes. Fully testable in isolation. ~3-4 files.
Phase 2: Work Queue Integration -- modify QueueBuildOptions and build_work_queue to accept and apply plan overrides. ~2 files modified.
Phase 3: CLI Commands -- convert plan_cmd.py to package, add subcommand handlers. ~4-5 new files.
Phase 4: next Integration -- load plan in next command, annotate items with plan context, update rendering. ~3 files modified.
Phase 5: Scan Merge Hook -- reconcile plan after scan. ~1 file modified.
Phase 6: Plan Rendering -- update markdown plan output with plan-aware sections. ~1 file modified.
7. Key Risks and Mitigations
Risk: Finding ID churn makes plan references stale
Mitigation: The reconcile step runs automatically after every scan. Superseded entries preserve original metadata and surface candidate replacements. Plan never silently drops references.
Risk: plan.json grows unbounded with superseded entries
Mitigation: Add a prune_superseded(plan, max_age_days=90) function that cleans old superseded entries. Call it during reconcile.
Risk: Plan overrides create confusing ordering that surprises users
Mitigation: Plan overrides are explicit opt-in. Default behavior (no plan.json) is unchanged. The --explain flag on next will show plan override reasoning.
Risk: Clusters reference findings that no longer exist
Mitigation: Reconcile cleans cluster membership. Empty clusters are preserved (they represent intent) but flagged in the plan show output.
8. Detailed Sort Key Design
Current sort key (from item_sort_key in ranking.py):
Plan-aware sort (applied as post-sort partition in build_work_queue):
code
Phase 0 (pinned): items where plan.overrides[id].pinned == True
-> sorted by existing item_sort_key within partition
Phase 1 (normal): items not pinned and not deferred
-> sorted by existing item_sort_key
Phase 2 (deferred): items where plan.overrides[id].deferred == True
-> excluded by default, included with --include-deferred
This design is clean: it does not modify the core sort key, only partitions the result. The existing ranking logic remains the single source of truth for relative ordering within each partition.
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/core.py - Core work queue builder where plan overrides are applied to item ordering
/Users/user_c042661f/Documents/desloppify/desloppify/engine/planning/render.py - Plan markdown renderer that needs plan-aware sections (pinned, clusters, deferred, superseded)
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/merge.py - Scan merge entry point where plan reconciliation hook must be triggered after auto-resolve
/Users/user_c042661f/Documents/desloppify/desloppify/app/cli_support/parser_groups_admin.py - Parser definitions where plan subcommands (pin/defer/cluster/annotate) are registered
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next.py - Next command handler where plan is loaded and passed into queue build, and plan context is surfaced
Called when a user adds an ignore pattern via the ignore command.
Marks ALL matching findings (any status) as suppressed=True.
If a finding was fixed, auto_resolved, or false_positive, its status is reverted to "open" for "score integrity".
Then calls _recompute_stats() which recomputes all scores.
How suppressed findings affect scoring:
This is the critical finding. The scoring engine in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_scoring/detection.py does NOT filter on the suppressed field at all. The _iter_scoring_candidates() function (lines 35-46) only filters by detector name and zone -- it never checks suppressed. The scoring loop (lines 156-165) only looks at finding.get("status") and checks it against FAILURE_STATUSES_BY_MODE[mode].
Consequence: A suppressed finding with status="open" counts as a failure in ALL scoring modes (lenient, strict, verified_strict). Suppression is purely a display/UI concern:
The work queue (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_work_queue/ranking.py, line 41) skips suppressed findings.
The match_findings() function (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/resolution.py, line 91) skips suppressed findings.
But the scoring engine does not.
The scan reporting explicitly confirms this at /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_reporting_analysis.py line 195: "Suppressed findings still count against strict and verified scores".
Summary: Ignore suppression hides findings from the user's work queue and from manual resolution, but does NOT remove them from score calculations. In all three modes (lenient, strict, verified_strict), a suppressed status="open" finding still counts as a failure.
2. THE WONTFIX STATUS
Resolve command (/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/resolve/cmd.py and selection.py):
The resolve command accepts statuses: open, fixed, wontfix, false_positive (line 209 of parser_groups.py).
wontfix requires --note (mandatory -- exits with error if missing, line 67-71 of selection.py).
All non-open statuses require --attest with specific anti-gaming keywords ("I have actually" and "not gaming").
Large wontfix batches (>10 findings) require --confirm-batch-wontfix and show estimated strict score drop.
Wontfix snapshot mechanism (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/resolution.py, lines 116-125):
When a finding is resolved as wontfix:
wontfix_scan_count: records the scan number when the wontfix decision was made. Used later to compute how many scans have passed since the wontfix.
wontfix_snapshot: captures a full snapshot of the finding's state at the time of the wontfix decision, including tier, confidence, and detail (complexity scores, LOC, etc.).
Stale wontfix detection (/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_wontfix.py):
During each scan, augment_with_stale_wontfix_findings() checks wontfix findings for staleness:
Scan decay: if wontfix_decay_scans scans have passed since the wontfix was applied, the finding is considered stale.
Severity drift: for structural detector findings, if complexity grew by 10+ or LOC grew by 50+ compared to the snapshot, it is flagged.
When stale, a new stale_wontfix finding is created as an open finding, prompting re-triage.
Wontfix auto-resolution (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/merge_findings.py, lines 66-114):
When auto_resolve_disappeared() runs, it checks findings with status in ("open", "wontfix", "fixed", "false_positive") that are absent from the current scan. If a wontfix finding disappears from the scan (the issue was actually fixed), it gets auto_resolved with note: "Fixed despite wontfix -- disappeared from scan (was wontfix)".
3. SCORE TYPES AND STATUS MAPPING
The canonical mapping (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_scoring/policy/core.py, lines 183-187):
This is the single most important data structure for understanding scoring:
Status
Lenient (overall/objective)
Strict (strict_score)
Verified Strict (verified_strict_score)
open
FAIL
FAIL
FAIL
wontfix
PASS
FAIL
FAIL
fixed
PASS
PASS
FAIL
false_positive
PASS
PASS
FAIL
auto_resolved
PASS
PASS
PASS
The logic is at /Users/user_c042661f/Documents/desloppify/desloppify/engine/_scoring/detection.py, lines 156-165:
python
for finding in _iter_scoring_candidates(detector, findings, policy.excluded_zones):
status = finding.get("status", "open")
weight = _finding_weight(finding, use_loc_weight=False)
for mode in SCORING_MODES:
if status not in FAILURE_STATUSES_BY_MODE[mode]:
continue
issue_count[mode] += 1
weighted_failures[mode] += weight
The four score types (computed in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_scoring/results/core.py, compute_score_bundle()):
overall_score: Lenient mode + subjective dimensions. Wontfix/fixed/false_positive/auto_resolved all pass.
objective_score: Lenient mode, mechanical dimensions only (no subjective). Same pass/fail as overall but without subjective dimensions.
strict_score: Strict mode + subjective dimensions. Wontfix still counts as failure.
verified_strict_score: Verified strict mode, mechanical only. Only auto_resolved counts as passing (scan-verified).
4. THE RESOLVE COMMAND
Accepted statuses: open, fixed, wontfix, false_positive (from parser at /Users/user_c042661f/Documents/desloppify/desloppify/app/cli_support/parser_groups.py line 209).
For reopens (resolving back to open), the kind becomes "manual_reopen".
For auto-resolves (by scan), the kind is "scan_verified" with scan_verified=True.
Wontfix-specific protections:
--note is required for wontfix (records reasoning).
Batch wontfix (>10 findings) requires --confirm-batch-wontfix and previews the strict score impact.
5. EXISTING DEFER/SKIP CONCEPTS
I searched for defer, postpone, backlog, and skip across the codebase. There is no existing defer or "I know about this but not now" mechanism in the finding status system. The closest analogues are:
wontfix: The closest to "defer" but semantically means "I accept this debt permanently." It has score consequences (fails strict) and is monitored for staleness.
ignore patterns: Hides findings from the work queue but keeps them as status="open" -- so they still hurt ALL scores. This is more of a "noise filter" than a deferral.
Noise budget (/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/noise.py): Caps how many findings are displayed per detector -- purely a presentation concern, not a deferral mechanism.
Tier-based prioritization: The next command and work queue rank by tier, so lower-tier items naturally get deferred in practice, but there is no explicit "defer" flag.
IMPLICATIONS FOR A "DEFER" CAPABILITY IN THE LIVING PLAN
Given this analysis, here are the key design considerations:
Option A: Score-neutral defer (like ignore but better)
A deferred finding would remain status="open" but get a deferred=True flag (similar to suppressed).
The scoring engine already ignores the suppressed flag, so a deferred flag would also be ignored -- the finding still hurts all scores.
Pro: No score gaming possible. Con: Deferring doesn't feel meaningful if scores don't change.
Option B: Score-aware defer (new status)
Add a new FindingStatus value like "deferred".
You would need to decide where it falls in the FAILURE_STATUSES_BY_MODE matrix. The natural position:
Strict: FAIL (like wontfix -- it's not actually fixed)
Verified strict: FAIL (definitely not fixed)
This would make deferred behave identically to wontfix in the scoring engine. The difference would be semantic/workflow: deferred implies "will do later" while wontfix implies "accepting permanently".
Risk: This creates a new way to game the lenient score. You'd want attestation requirements similar to wontfix.
Option C: Plan-layer defer (no state changes)
Deferring in the living plan could be purely a plan-layer concept that does not modify finding status at all.
The plan would track which findings are deferred, but the scoring engine would be completely unaware.
Pro: Cleanest separation of concerns. The plan is a prioritization tool, not a score manipulation tool.
Con: The plan can't provide "focus on what matters now" if deferred items still crowd the score.
Option D: Hybrid -- plan-layer defer with wontfix staleness monitoring
Defer in the plan suppresses from the plan's work queue but leaves the finding status="open".
Add a deferred_until or deferred_scan_count field (like wontfix_scan_count) to auto-expire deferrals.
Scores remain honest (open = fail everywhere), but the plan filters deferred items from its recommendations.
The existing pattern strongly suggests the project prefers score honesty -- even ignore (which explicitly hides findings) still leaves them counting against scores. The wontfix system is the only mechanism that affects lenient scores, and it has heavy guardrails (attestation, mandatory notes, batch confirmation, stale monitoring, strict score penalty). This suggests that any "defer" mechanism should probably be score-neutral (Options A, C, or D) unless there is a deliberate decision to create a new lenient-passing status with equivalent guardrails.
How it connects to next: The cmd_next (at /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/next.py) calls compute_narrative() and emits the full narrative payload into query.json. However, the next command renders items from the work queue (build_work_queue()), not from the narrative actions/lanes. The narrative is attached as metadata but its lane/strategy structure is not rendered to the user in the next terminal output.
Integration verdict:Strong integration candidate. The living plan should consume strategy.lanes and strategy.fixer_leverage directly. The lane concept (independent workstreams with file overlap analysis) maps naturally to plan clusters. The primary_action and why_now fields are ready-made for plan headers. The living plan should be the renderer for what the strategy engine already computes.
What exists: The fix command operates on a single named fixer (e.g., desloppify fix unused-imports --dry-run). It:
Loads a FixerConfig by name from the language plugin
Detects candidates via fixer.detect(path)
Applies via fixer.fix(entries, dry_run=...) returning FixResult
Auto-resolves matching findings in state
Runs cascade post-fix hooks (e.g., _cascade_unused_import_cleanup for debug-logs and dead-useeffect)
The fix command reports a narrative after fixing and emits query.json with before/after scores.
There is no batch-fix-all or cluster-fix capability. Each fixer runs independently by name. The action engine already generates the right command strings (e.g., desloppify fix unused-imports --dry-run), but there is no way to say "run all fixers for this lane" or "fix everything in the cleanup lane."
Integration verdict:Yes, surface "fix this cluster" as a plan action. When a plan cluster's actions are all type: auto_fix, the living plan should present a single composite command or sequence. The strategy engine already identifies the cleanup lane and knows run_first status. The plan could emit something like:
What exists: The show command is a flexible query tool: show <file|dir|detector|pattern|dimension>. Key plan-adjacent features:
show_agent_plan() (render.py lines 205-237): Already renders a compact "AGENT PLAN" block when showing findings. It picks the top narrative action and shows ranked actions via print_ranked_actions(). This is the closest thing to plan context in the show output.
show concerns: A special view that runs generate_concerns() to surface cross-cutting design concerns from mechanical signals. These are ephemeral (not persisted) and bridge mechanical findings to subjective review.
No show queue: There is no show queue or show plan subcommand. The show command only queries findings.
Show emits full narrative to query.json including strategy, so agents already get plan context when calling show.
Integration verdict:Moderate integration. The show_agent_plan() in the show renderer could be enhanced to show living-plan context ("You're in cluster 2 of 4, cleanup lane"). The concerns engine is interesting -- concerns could feed into plan clusters as "investigation items" alongside mechanical findings. No new subcommands needed, but the existing show_agent_plan rendering point is the right place to inject plan awareness.
What exists: The review system is large and has multiple modes:
--prepare: Prepares structured review prompts with dimension templates for AI evaluation
--run-batches: Orchestrates batch LLM reviews (with runners like Codex/Claude)
--external-start / --external-submit: External blind review sessions with session IDs
--import: Import review findings JSON into state
--merge: Merge duplicate review findings
Review findings use detector: "review" and are tracked in state just like mechanical findings. The action engine already handles them -- see action_engine.py line 183-193 where _build_refactor_entry creates review-specific actions with commands like desloppify show review --status open.
The narrative strategy engine also checks for review actions (line 326-330 of strategy_engine.py) and appends a review pointer to the strategy hint.
Integration verdict:Yes, review recommendations should feed into plan clusters. Review findings are already first-class findings in state with status: open. They flow into the work queue and narrative actions automatically. The living plan should:
Include review findings in clusters (they already have file paths and dimensions)
Surface "needs review" as a plan step when subjective_review findings exist
The by_detector counts for review and review_holistic are already tracked separately in _count_open_by_detector()
Narrative headline (a single compute_narrative() call with command="scan" context)
Two pointers: "Run desloppify next for the highest-priority item" and "Run desloppify status for the full dashboard"
The scan also shows show_score_integrity() with wontfix debt, ignore pattern suppression, and score confidence.
The post-scan output does NOT mention the plan command or show plan context. It points to next and status only.
Integration verdict:Yes, plan context should appear in post-scan reporting. The two-pointer section (lines 103-105 of scan_reporting_analysis.py) is the natural insertion point. After a scan, the output could say:
"Run desloppify plan to see the updated living plan" or
Show a condensed plan summary ("3 clusters remain: cleanup lane (12 auto-fixable), refactor_0 (8 manual), test_coverage (5)")
The narrative strategy.hint is already computed during scan reporting and could be rendered more prominently.
What exists: There is no persistent focus mode or "what you were working on" tracking. Specifically:
--scope exists on the next command (filters work queue by path prefix) but is not persisted between invocations.
--focus exists on the tree command (filters the tree view to a subtree) but is purely a display filter.
--session-id and --session-ttl-hours exist on the review command, but only for tracking external review session provenance, not for "working session" tracking.
scan_path is stored in state and reused by the review command's default path resolution, but this is scan scope, not user focus.
The state.py file has no fields like last_worked_on, current_cluster, active_lane, focus, or session.
The concern_dismissals dict in state is the closest to "memory of past decisions" but only tracks dismissed concerns.
reminder_history in state tracks reminder decay (how many times each reminder has been shown) but not work focus.
Integration verdict:This is the biggest gap and highest-value addition for the living plan. The tool has no memory of what you were working on. A living plan could provide this by:
Persisting the current plan cluster/lane assignment in .desloppify/ state
Tracking which findings have been actively worked on (not just fixed/wontfixed)
Resuming where you left off: "You were working on the cleanup lane (3 of 7 items fixed)"
The next --scope flag hints at the desire for this -- a living plan could automatically scope next to the active cluster
Strong yes -- living plan is the natural renderer for strategy lanes
High
Fix command
No batch/cluster fix
Yes -- surface "fix this cluster" composite commands
Medium
Show command
Yes -- show_agent_plan() renders compact actions
Moderate -- inject cluster context into existing agent plan rendering
Low
Review system
Yes -- review findings are first-class in work queue and actions
Yes -- review findings should appear in plan clusters naturally
Medium
Scan reporting
Only mentions next and status post-scan
Yes -- add plan summary/pointer after scan completes
Medium
Focus/scope persistence
Nothing exists
Highest value -- living plan needs session/focus state to be truly "living"
High
SKILL.md (/Users/user_c042661f/Documents/desloppify/docs/SKILL.md line 148): "Tiers: T1 auto-fix, T2 quick manual, T3 judgment call, T4 major refactor."
Contradiction risk: MODERATE. Tiers are intrinsic to each finding and represent the nature of work (easy auto-fix vs. hard refactor). They do not inherently conflict with a living plan -- the living plan could incorporate tier data. However, the "Tier Navigator" in the next command actively encourages agents to navigate by tier, which could override plan ordering. The plan command renders items grouped by tier rather than by a plan-defined priority.
Recommendation: Keep tier metadata on findings (it is structural), but the plan command should render items in the living plan's order, not grouped by tier. The Tier Navigator in next should defer to the living plan's ordering.
2. NARRATIVE ACTIONS / PRIMARY_ACTION SYSTEM
What it tells the agent: A prioritized list of actions, each with a command, description, detector, impact score, and priority rank. A single primary_action is picked as the top recommendation.
Where computed:
/Users/user_c042661f/Documents/desloppify/desloppify/intelligence/narrative/action_engine.py -- compute_actions() builds the list.
/Users/user_c042661f/Documents/desloppify/desloppify/intelligence/narrative/core.py -- _compute_primary_action() picks actions[0] as the top action.
status command (status_parts/render.py line 450): show_agent_plan() prints "Agent focus: {command} -- {description}".
show command (show/render.py line 219): show_agent_plan() prints same.
query.json payload: The entire narrative.actions list is written to query.json for every command (scan, status, show, next).
SKILL.md line 151: "query.json: After any command, has narrative.actions with prioritized next steps."
Contradiction risk: HIGH. This is an independent prioritization system that ranks by action type first (auto_fix > reorganize > refactor) and then by score impact. A living plan might want a completely different ordering (e.g., "finish refactoring module X before running fixers on module Y"). The primary_action is always the first auto-fix action, which may not be what the plan says to do.
Recommendation: This is the primary system to replace/subordinate. The living plan should own the primary_action slot. The actions list could remain as a data source for the living plan to draw from.
3. STRATEGY HINTS SYSTEM
What it tells the agent: A one- or two-sentence execution strategy, like "Run fixers first -- they cover 40% of findings. Then 3 independent workstreams, safe to parallelize."
"Run fixers first -- they cover X% of findings. Then N independent workstreams, safe to parallelize. Rescan after each phase to verify."
"Maintenance mode -- address new findings as they appear."
"Try a different dimension to break the plateau."
"Work through actions in priority order. Rescan after each fix to track progress."
Where it appears in output:
scan LLM block (scan_reporting_llm.py line 198-200): "Strategy: {hint}" printed to agents.
query.json: Written as narrative.strategy.hint in every command's query payload.
_compute_why_now() in core.py line 223: Falls back to the strategy hint to explain why the primary action should happen now.
Contradiction risk: HIGH. The strategy hint directly tells agents "Run fixers first" or "Work through actions in priority order" or "Try a different dimension." These are imperative workflow instructions that override any plan ordering.
Recommendation: Replace with the living plan's high-level summary. The parallelization/lane analysis could remain as data the living plan consumes.
4. show_agent_plan() FUNCTION (THREE IMPLEMENTATIONS)
What it tells the agent: A "AGENT PLAN" block with the top action and ranked actions.
Contradiction risk: VERY HIGH. This is a direct competitor with the living plan concept. It says "AGENT PLAN" and gives explicit instructions. The name itself implies it IS the plan.
Recommendation: This should be the primary integration point for the living plan. Instead of computing the plan from narrative.actions on the fly, it should render the living plan's current state.
5. print_ranked_actions() FUNCTION
What it tells the agent: "Biggest things impacting score:" followed by the top 3 actions by impact, each with detector, count, and command.
Where defined:/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/rendering.py line 44
Where called:
status_parts/render.py line 452 -- inside show_agent_plan() for the status command.
show/render.py line 235 -- inside show_agent_plan() for the show command.
Output example:
code
Biggest things impacting score:
- unused: 15 open -- `desloppify fix unused-imports --dry-run`
- smells: 8 open -- `desloppify show smells --status open`
- dupes: 3 open -- `desloppify show dupes --status open`
Contradiction risk: MODERATE. It gives a separate "impact-ranked" view that may conflict with both the tier ordering and the living plan ordering.
Recommendation: Could remain as supplementary data but should clearly defer to the living plan. Perhaps rendered as "context" rather than "instructions."
What it tells the agent: After scan, prints a headline and two pointer commands.
Where defined:/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_reporting_analysis.py lines 58-108
Output:
code
-> [narrative headline, e.g., "First scan: 23 issues across 5 dimensions"]
Run `desloppify next` for the highest-priority item.
Run `desloppify status` for the full dashboard.
Plus critical warnings about reopened findings, cascading issues, and chronic reopeners.
Contradiction risk: LOW. The headline is informational. The pointers direct to next and status which would eventually serve the living plan. However, it does say "highest-priority item" which implies the next command's prioritization is authoritative.
Recommendation: Keep the warnings. Modify the pointers to reference the living plan if one exists.
7. "INSTRUCTIONS FOR LLM" BLOCK (scan_reporting_llm.py)
What it tells the agent: A comprehensive block only shown in agent environments (CLAUDE_CODE, DESLOPPIFY_AGENT, etc.) that includes scores, dimension table, workflow guide, strategy hint, and top action.
Where defined:/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_reporting_llm.py lines 258-309
Content rendered by _print_llm_summary():
Score lines (overall, objective, strict, verified) with score guide
Full dimension table in markdown
Drag summary ("Biggest score drags")
Stats summary (findings counts, wontfix debt)
Workflow guide (see system #8 below)
Narrative status (headline + strategy + top action)
Badge hint
Contradiction risk: HIGH. This is the most comprehensive guidance block. It contains the workflow guide which has its own priority instructions ("Run auto-fixers first"), the strategy hint, AND the top action -- three separate prioritization voices in one block.
Recommendation: This block should reference the living plan and render its current step, rather than independently computing guidance.
8. WORKFLOW GUIDE (scan_reporting_text.py)
What it tells the agent: A fixed-text decision workflow:
"Consider skipping: T4 low-confidence, test/config zone findings"
"Wontfix: Intentional patterns, false positives"
Where defined:/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_reporting_text.py
Where shown: Inside the "INSTRUCTIONS FOR LLM" block (agent environments only).
Contradiction risk: HIGH. This is a hardcoded workflow ordering that will always say "Run auto-fixers first" regardless of what the living plan says. It establishes a fixed priority: auto-fix > manual fix > review > status check.
Recommendation: Replace with a reference to the living plan. The workflow steps can become a template that the living plan engine can override.
9. SKILL.MD / AGENT INSTRUCTIONS
What it tells the agent: A persistent document installed into the agent's working directory that defines the entire workflow:
Where defined:
/Users/user_c042661f/Documents/desloppify/docs/SKILL.md -- the template
Installed to .claude/skills/desloppify/SKILL.md, AGENTS.md, .cursor/rules/desloppify.md, etc.
Auto-updated by auto_update_skill() on every scan in agent environments.
Key directives:
Section 1 "Your Job": "Improve code quality by fixing findings and maximizing strict score honestly."
Section 2 "Core Loop": "scan -> follow the tool's strategy -> fix or wontfix -> rescan"
Line 36: "the scan output ends with INSTRUCTIONS FOR AGENTS. Follow them. Don't substitute your own analysis."
Line 151: "query.json: After any command, has narrative.actions with prioritized next steps."
Contradiction risk: VERY HIGH. The SKILL.md is the most persistent and foundational directive. It tells agents to "follow the tool's strategy" and read "INSTRUCTIONS FOR AGENTS" and narrative.actions. If the living plan becomes the single source of truth, the SKILL.md must be updated to point agents there instead.
Recommendation: Must be updated to reference the living plan. This is probably the most important single change.
10. QUERY.JSON PAYLOAD
What it tells the agent: Machine-readable JSON written after every command, containing the full narrative (actions, strategy, primary_action, why_now, reminders, risk_flags, strict_target, etc.).
Where written:
scan command: scan_artifacts.py::build_scan_query_payload() -- includes full narrative dict.
status command: status_parts/render.py::write_status_query() -- includes full narrative plus next_command.
next command: next.py line 127 -- includes full narrative plus scores and scorecard dimensions.
show command: show/cmd.py line 238 -- includes full narrative.
Contradiction risk: HIGH. query.json is the machine-readable API surface that agents may parse programmatically. Multiple fields provide prioritization: primary_action, actions[0], strategy.hint, why_now. All computed independently from any living plan.
Recommendation: Add a plan key to query.json that represents the living plan's current state and next steps. Consider deprecating primary_action in favor of the plan's top item.
11. REMINDERS SYSTEM
What it tells the agent: Contextual nudges with priority and decay, such as:
"X findings are auto-fixable. Run desloppify fix ...."
"Rescan to verify -- cascading effects may create new findings."
"Wontfix debt is growing."
"X stale subjective dimensions -- re-review."
"ALWAYS share ALL scores with the user" (no-decay, always shown on scan).
Where computed:/Users/user_c042661f/Documents/desloppify/desloppify/intelligence/narrative/reminders.py
Where shown: Written to narrative.reminders in query.json. Not directly printed to terminal in most cases -- they are consumed by agents reading query.json.
Contradiction risk: MODERATE. Reminders like "auto_fixers_available" push agents toward specific actions. "stagnant_nudge" says "try a different dimension." These can override plan ordering.
Recommendation: Keep reminders as advisory signals but clearly label them as supplementary to the living plan. The living plan should incorporate reminder data into its own prioritization.
12. FOCUS SUGGESTION & DIMENSION HINTS
What it tells the agent: "Focus: [lowest dimension name] (X%) -- fix Y items for +Z pts" and "Needs attention: [dimension] (X%) -- [specific hint]"
Where defined:
status_parts/render.py::show_focus_suggestion() line 344 -- prints the lowest-scoring dimension as a "Focus" directive.
scan_reporting_presentation.py::show_low_dimension_hints() line 176 -- prints "Needs attention" with per-dimension-specific commands.
Where shown:
status command calls show_focus_suggestion() (line 112).
scan command calls show_low_dimension_hints() via show_scorecard_subjective_measures().
Example output:
code
Focus: Code quality (87.5%) -- fix 12 items for +3.2 pts
Needs attention:
File health (45%) -- run `desloppify show structural` -- split large files
Duplication (38%) -- run `desloppify show dupes` -- deduplicate functions
Contradiction risk: MODERATE. This gives yet another prioritization axis (lowest dimension) that may differ from the action engine's ordering (highest impact), the tier system's ordering (T1 first), and the living plan.
Recommendation: Subordinate to the living plan. Could remain as informational context.
13. ADDITIONAL MINOR GUIDANCE POINTS
13a. next command: render_single_item_resolution_hint() and render_followup_nudges()
Prints: "Create a task doc for each area -> farm to sub-agents for decomposition" plus numbered workflow steps.
Contradiction risk: MODERATE. This is a workflow prescription for structural debt that could conflict with the living plan.
Summary Matrix
#
System
Commands
Priority axis
Contradiction risk
Recommendation
1
Tier system
plan, next, status
Work difficulty (T1-T4)
MODERATE
Keep as metadata, don't render as ordering
2
Narrative actions/primary_action
scan, status, show, query.json
Action type then impact
HIGH
Living plan owns primary_action
3
Strategy hints
scan, query.json
Phase-dependent heuristics
HIGH
Replace with plan summary
4
show_agent_plan() (x3)
status, show, plan, zone
Top action from narrative
VERY HIGH
Render living plan here
5
print_ranked_actions()
status, show
Impact descending
MODERATE
Relabel as context, not instruction
6
Post-scan coaching
scan
Headline + pointers
LOW
Point to living plan
7
"INSTRUCTIONS FOR LLM" block
scan (agent env only)
Multi-layered
HIGH
Reference living plan
8
Workflow guide
scan (agent env only)
Fixed hardcoded order
HIGH
Replace with plan reference
9
SKILL.md
Persistent agent doc
"Follow the tool's strategy"
VERY HIGH
Must point to living plan
10
query.json narrative payload
All commands
Multiple fields
HIGH
Add plan key, deprecate primary_action
11
Reminders system
query.json
3-tier urgency
MODERATE
Keep as advisory
12
Focus suggestion / dimension hints
status, scan
Lowest dimension
MODERATE
Subordinate to plan
Key Architectural Insight
The fundamental problem is that every command independently computes its own prioritization by calling compute_narrative(), which runs compute_actions() + compute_strategy() fresh each time. There is no persistent plan object that commands read from. Instead, the "plan" is ephemeral -- recomputed from raw state on every invocation, with the action_engine and strategy_engine serving as the de facto prioritization brains.
For the living plan to become the single source of truth, it needs to:
Be persisted (in .desloppify/plan.json or similar)
Be what show_agent_plan() renders instead of narrative.actions[0]
Be what query.json's top-level guidance fields point to
Be what SKILL.md tells agents to follow
Still use the narrative system's data (actions, strategy, reminders) as inputs, but apply its own ordering logic on top