I need to thoroughly understand the ignore/exclude and scan state management in this codebase. This is for designing a fix for a bug where ignore pattern changes corrupt persisted score accounting.
Please find and summarize:
All ignore/exclude entry points — what CLI commands exist for adding ignore patterns or exclusions? Look in desloppify/app/commands/resolve/cmd.py, parser groups, and anywhere else ignore or exclude patterns are managed. What's the UX flow for each?
State mutation during ignore — In desloppify/engine/_state/filtering.py, trace exactly what remove_ignored_findings and add_ignore do. What happens to findings (status changes, suppression flags)? How does _recompute_stats handle suppressed findings?
Score recomputation — In desloppify/engine/_state/scoring.py, how does _recompute_stats work? Does it account for suppressed findings? Does it count them as open debt?
Scan reconciliation — How does a normal scan reconcile with existing state? Look at merge_scan in state.py or engine/_state/. When findings are suppressed, does a rescan properly handle them?
Post-command hooks — Is there any existing mechanism to flag state as "dirty" or "needs rescan"? Look for any needs_rescan, stale, dirty flags in state schema.
Score reporting after state changes — Look at desloppify/app/commands/helpers/score_update.py and how scores are reported after commands. Is there a centralized post-command score display?
Be very thorough — read the actual function implementations, not just signatures. Level: very thorough.
Assistant
I'll conduct a thorough investigation of the ignore/exclude and scan state management system. Let me start by mapping out all the relevant files and their implementations.
Assistant
Now let me read the core files systematically:
Assistant
Now let me continue reading the critical scoring and state files:
Assistant
Now let me read the state schema and merge logic to understand the scan reconciliation:
Assistant
Now let me look at merge_findings to see how upsert_findings handles ignores:
Assistant
Now let me check config handling and scan workflow to see how ignores are loaded and used:
Assistant
Now let me look at how scan actually calls merge_scan with the ignore patterns:
Assistant
Let me find the merge_scan_results function in scan_workflow:
Assistant
Good! Now let me look at any existing dirty/stale flags and check the apply.py for resolve to see how state is modified:
Assistant
Now let me check the full state schema to see all fields:
Assistant
Now let me check the entire SubjectiveAssessment schema and look at how needs_review_refresh works:
Assistant
Perfect! Now let me create a comprehensive summary by reading a few more key files related to post-command hooks:
Assistant
User
Assistant
I'll start by thoroughly exploring the codebase to understand the current architecture and all the files involved, then design a detailed implementation plan.
Assistant
Now let me look at the state schema, the CLI entry point, and the score_update helper to understand the full picture.
Assistant
Now let me look at the command registry, the state module's public API, and how commands currently check state to understand where to add the needs_rescan warning.
Assistant
Now let me look at the merge module to understand how ignore patterns are applied during scan merge, and the persistence module to see how state is saved.
Assistant
Let me also look at the open_scope_breakdown usage and how _iter_scoring_candidates is used elsewhere, plus the existing tests for scoring to understand what's already covered.
Assistant
Now let me look at the existing tests and the parser_groups_admin file to understand how CLI parsers are organized.
Assistant
Now let me look at the config command to understand how config-level commands work, and check the resolution module for the suppressed filter reference I saw.
Assistant
Let me check the open_scope_breakdown function usage and how the status_cmd works to understand where warnings could be injected.
Assistant
Let me check the require_completed_scan helper and the command_runtime pattern to understand the best place for a cross-cutting warning.
Assistant
Now let me look at the existing tests for filtering and scoring to understand the test patterns.
Assistant
Let me also check the check_tool_staleness pattern to understand the existing warning mechanism that we can model needs_rescan after.
Assistant
Now I have a thorough understanding of the codebase. Let me also quickly check how open_scope_breakdown filters findings (since it only checks status != "open" but not suppressed) to confirm it's also affected.
Assistant
Perfect! Now I have enough information. Let me create a comprehensive summary of the findings.
Summary: Ignore/Exclude and Scan State Management
Based on my thorough analysis of the desloppify codebase, here's a detailed breakdown of the ignore/exclude and scan state management system:
1. ALL IGNORE/EXCLUDE ENTRY POINTS
CLI Commands for Ignore Patterns:
a) ignore subcommand — /Users/user_c042661f/Documents/desloppify/desloppify/app/cli_support/parser_groups.py (lines 251-267):
This provides historical record of ignore operations but not of pattern changes over time.
SUMMARY TABLE
Aspect
Details
Ignore entry points
desloppify ignore <pattern> CLI command
Config storage
config.json with ignore: [list] and ignore_metadata: {pattern: {note, added_at}}
State mutation
remove_ignored_findings() → sets suppressed=True, reverts status to "open", calls _recompute_stats()
Score accounting
Suppressed findings counted as "open" in all score calculations
Scan reconciliation
merge_scan() loads patterns from config.ignore and applies via upsert_findings()
Post-command reporting
print_score_update() displays quartet with deltas after ignore/resolve
Dirty flag mechanism
NONE — relies on immediate recompute + next scan application
Stale marking
Only needs_review_refresh for mechanical detector changes during scan
Bug risk
Pattern change between saves can cause status/suppression mismatches without detection
Design an implementation plan for fixing the ignore/exclude score corruption bug in desloppify (GitHub issue #168).
Problem
When desloppify ignore "pattern" is run:
remove_ignored_findings() in engine/_state/filtering.py:107-132 marks matched findings as suppressed=True
BUT it also reopens resolved findings (fixed/auto_resolved/false_positive → open) at line 121-126
_recompute_stats() in engine/_state/scoring.py:388-409 calls _count_findings() which does NOT filter suppressed findings — they all count
Score computation via _iter_scoring_candidates() in engine/_scoring/detection.py:35-46 also does NOT filter suppressed findings
Result: score collapses because reopened+suppressed findings count as open debt
A normal rescan doesn't recover because the state has corrupted status values
Current Architecture
Ignore vs Exclude
Ignore (config.ignore): Suppresses findings after detection. Has CLI command desloppify ignore <pattern> --attest "...". Managed in core/config.py:add_ignore_pattern() and engine/_state/filtering.py:remove_ignored_findings().
Exclude (config.exclude): Path patterns to skip during scanning. Applied at startup via cli.py:_apply_persisted_exclusions(). NO dedicated CLI command — only --exclude flag on main parser and manual config editing.
Scoring Pipeline
_recompute_stats() → _count_findings(findings) — tallies all findings by status (no suppression filter)
_update_objective_health() → compute_score_bundle() → compute_dimension_scores_by_mode() → detector_stats_by_mode() → _iter_scoring_candidates() — iterates findings filtered by detector and zone only (no suppression filter)
Both file-based and finding-based scoring paths go through _iter_scoring_candidates()
State Schema
Finding fields relevant to suppression:
suppressed: bool — True if matching ignore pattern
suppressed_at: str | None — When suppressed
suppression_pattern: str | None — Which pattern matched
The reopen hack in filtering.py:121-126 and merge_findings.py:174-180: When a finding matches an ignore pattern, the code reopens resolved findings (changing fixed/auto_resolved/false_positive to open) under the belief that this preserves "score integrity." This is the original corruption vector -- it undoes legitimate work.
Suppressed findings are not filtered from scoring: Both _count_findings() in scoring.py:38-50 and _iter_scoring_candidates() in detection.py:35-46 iterate over all findings without checking finding.get("suppressed"). This means suppressed findings still count as open debt, dragging scores down.
The combination is devastating: resolved findings get reopened to status="open", then still count in scoring because suppression is not checked. Score collapses.
Step 1: Filter suppressed findings from scoring (the core fix)
Rationale: Suppressed findings must be invisible to all scoring pathways. There are three filter points that need modification.
1a. _count_findings() in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/scoring.py (line 38-50)
Add a suppression filter. Currently:
python
def _count_findings(findings: dict) -> tuple[dict[str, int], dict[int, dict[str, int]]]:
counters = dict.fromkeys(_EMPTY_COUNTERS, 0)
tier_stats: dict[int, dict[str, int]] = {}
for finding in findings.values():
status = finding["status"]
...
Change to skip suppressed findings:
python
for finding in findings.values():
if finding.get("suppressed"):
continue
status = finding["status"]
...
This is the stats counter used for the dashboard. Suppressed findings should not appear in any status count.
1b. _iter_scoring_candidates() in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_scoring/detection.py (line 35-46)
Add suppression filter. Currently yields any finding matching detector + zone. Change to:
python
def _iter_scoring_candidates(
detector: str,
findings: dict[str, Finding],
excluded_zones: frozenset[str],
):
for finding in findings.values():
if finding.get("suppressed"):
continue
if finding.get("detector") != detector:
continue
if finding.get("zone", "production") in excluded_zones:
continue
yield finding
This is the critical scoring path -- all dimension scores flow through here.
1c. open_scope_breakdown() in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/filtering.py (line 52-77)
Add suppression filter in the loop. Currently checks status != "open" but not suppressed. Add:
python
for finding in findings.values():
if finding.get("suppressed"):
continue
if finding.get("status") != "open":
continue
This function is used by status_cmd and scan_artifacts for the in-scope/out-of-scope breakdown display.
Step 2: Remove the problematic reopen-to-open hack
Rationale: The reopening of resolved findings when they match an ignore pattern was a misguided attempt to prevent score gaming. The attestation requirement already handles this -- if someone ignores resolved findings, the attestation proves intent. Reopening them actually creates the corruption because combined with the non-filtering of suppressed findings from scoring, it creates phantom open debt.
2a. remove_ignored_findings() in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/filtering.py (line 107-132)
Remove lines 121-126 entirely. The function should just set suppressed=True and related fields, without touching status, resolved_at, or note. The corrected version:
python
def remove_ignored_findings(state: StateModel, pattern: str) -> int:
ensure_state_defaults(state)
matched_ids = [
finding_id
for finding_id, finding in state["findings"].items()
if is_ignored(finding_id, finding["file"], [pattern])
]
now = utc_now()
for finding_id in matched_ids:
finding = state["findings"][finding_id]
finding["suppressed"] = True
finding["suppressed_at"] = now
finding["suppression_pattern"] = pattern
# (removed: the block that reopened fixed/auto_resolved/false_positive findings)
from desloppify.engine._state.scoring import _recompute_stats
_recompute_stats(state, scan_path=state.get("scan_path"))
validate_state_invariants(state)
return len(matched_ids)
2b. upsert_findings() in /Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/merge_findings.py (line 170-180)
The same reopen logic exists here for the scan-time path. Currently lines 174-179:
python
if matched_ignore:
previous["suppressed"] = True
previous["suppressed_at"] = now
previous["suppression_pattern"] = matched_ignore
if previous["status"] in ("fixed", "auto_resolved", "false_positive"):
previous["status"] = "open"
previous["resolved_at"] = None
previous["note"] = (
"Suppressed by ignore pattern -- remains unresolved for score integrity"
)
continue
Remove the if previous["status"] in ... block. Just set suppressed fields and continue:
python
if matched_ignore:
previous["suppressed"] = True
previous["suppressed_at"] = now
previous["suppression_pattern"] = matched_ignore
continue
Step 3: Add needs_rescan state flag
Rationale: When ignore or exclude config changes, the current scores are based on pre-change state. Findings were suppressed/removed in-memory, but a proper rescan is needed to get accurate potentials and to discover any new findings in previously excluded paths.
3a. Add config-level flag in /Users/user_c042661f/Documents/desloppify/desloppify/core/config.py
Add to CONFIG_SCHEMA:
python
"needs_rescan": ConfigKey(
bool, False, "Set when config changes require a rescan for accurate scores"
),
Why config, not state?: The flag relates to configuration changes (ignore/exclude patterns) that make the persisted state potentially inaccurate. Putting it in config means it persists across state loads and is cleared by the scan command which reads config. Using config also means it is language-independent (a config change affects all languages).
3b. Set the flag in ignore command
In /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/resolve/cmd.py, in cmd_ignore_pattern() after the config save (around line 169):
print(colorize(" Scores may be approximate until next scan. Run: desloppify scan", "yellow"))
3c. Set the flag in the new exclude command (see Step 4)
Same pattern: after adding exclude pattern, set config["needs_rescan"] = True.
3d. Clear the flag after scan
In /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/scan/scan_workflow.py, in merge_scan_results() after the state save succeeds (around line 415):
python
# Clear needs_rescan flag after successful scan merge
if runtime.config.get("needs_rescan"):
runtime.config["needs_rescan"] = False
try:
from desloppify.core.config import save_config
save_config(runtime.config)
except OSError:
pass # Best-effort
Step 4: Add exclude CLI subcommand
Rationale: Currently the only way to add persistent exclude patterns is to manually edit config.json or use desloppify config set exclude <pattern>. A dedicated exclude command parallels the existing ignore command.
4a. Add parser in /Users/user_c042661f/Documents/desloppify/desloppify/app/cli_support/parser_groups.py
Add after _add_ignore_parser:
python
def _add_exclude_parser(sub) -> None:
p_exclude = sub.add_parser(
"exclude", help="Add path pattern to exclude list, requires rescan"
)
p_exclude.add_argument("pattern", help="Path pattern to exclude from scanning")
p_exclude.add_argument("--state", type=str, default=None)
Add _add_exclude_parser to the __all__ list.
4b. Register parser in /Users/user_c042661f/Documents/desloppify/desloppify/app/cli_support/parser.py
Import and call _add_exclude_parser(sub) in create_parser().
4c. Add config helper in /Users/user_c042661f/Documents/desloppify/desloppify/core/config.py
python
def add_exclude_pattern(config: dict, pattern: str) -> None:
"""Append a pattern to the exclude list (deduplicates)."""
excludes = config.setdefault("exclude", [])
if pattern not in excludes:
excludes.append(pattern)
4d. Create command handler
New file: /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/exclude_cmd.py
python
"""exclude command: add path pattern to exclude list."""
from __future__ import annotations
import argparse
import sys
from desloppify.app.commands.helpers.runtime import command_runtime
from desloppify.core import config as config_mod
from desloppify.core.fallbacks import print_error
from desloppify.core.output_api import colorize
def cmd_exclude(args: argparse.Namespace) -> None:
"""Add a path pattern to the exclude list."""
config = command_runtime(args).config
pattern = args.pattern
if pattern in config.get("exclude", []):
print(colorize(f" Pattern already excluded: {pattern}", "yellow"))
return
config_mod.add_exclude_pattern(config, pattern)
config["needs_rescan"] = True
try:
config_mod.save_config(config)
except OSError as exc:
print_error(f"could not save config: {exc}")
sys.exit(1)
print(colorize(f" Added exclude pattern: {pattern}", "green"))
print(colorize(
" Scores may be stale. Run: desloppify scan",
"yellow",
))
4e. Register in command registry
In /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/registry.py, import cmd_exclude and add "exclude": cmd_exclude to the handler dict.
4f. Update usage examples
In parser.py's USAGE_EXAMPLES, add:
code
exclude <pattern> Add path pattern to exclude from scanning
Step 5: Warning on all commands when needs_rescan is set
Rationale: Every command that reads state should warn the user that scores are potentially stale after ignore/exclude changes.
5a. Create a centralized check function
Add to /Users/user_c042661f/Documents/desloppify/desloppify/app/commands/helpers/state.py:
python
def check_needs_rescan(config: dict) -> str | None:
"""Return warning message if config changes require a rescan."""
if config.get("needs_rescan"):
return (
"Config changed since last scan (ignore/exclude patterns updated). "
"Scores may be stale. Run: desloppify scan"
)
return None
5b. Hook into commands that already show warnings
The pattern already exists in status_cmd.py, next.py, and show/cmd.py where check_tool_staleness is called. Add the needs_rescan check alongside it in each:
/Users/user_c042661f/Documents/desloppify/desloppify/app/commands/status_cmd.py (after line 75):
python
from desloppify.app.commands.helpers.state import check_needs_rescan
rescan_warning = check_needs_rescan(config)
if rescan_warning:
print(colorize(f" {rescan_warning}", "yellow"))
def test_needs_rescan_set_by_ignore_cleared_by_scan():
# Verify that cmd_ignore_pattern sets needs_rescan
# Verify that merge_scan_results clears it
6e. Test: end-to-end score integrity after ignore
python
def test_ignore_pattern_does_not_corrupt_score():
"""End-to-end: ignoring a pattern should not change scores for unrelated findings."""
state = schema_mod.empty_state()
# Set up findings: some matching ignore pattern, some not
# Record score before
# Run add_ignore / remove_ignored_findings
# Verify score is same or better (not worse) after suppression
6f. Existing tests must still pass
Run the full test suite. Key existing tests to verify:
Step 1 (scoring filter) and Step 2 (remove reopen hack) should be done together as one atomic change -- they are the core bug fix and are logically inseparable.
Step 3 (needs_rescan flag) depends on Step 1+2 being done (the flag makes sense only when the suppression fix is in place).
Step 4 (exclude command) can be done independently but should come after Step 3 since it uses the needs_rescan flag.
Step 5 (warnings) depends on Step 3.
Step 6 (tests) should be written alongside each step, but the regression tests for the core bug (6a-6c) should go in with Step 1+2.
Risk Assessment
Low risk: Steps 1a, 1b, 1c are additive filters. They only narrow what gets counted. If any finding is incorrectly marked as suppressed=True that is a pre-existing data issue, not caused by this change.
Medium risk: Step 2 (removing the reopen hack) changes behavior. Any state files that already have corrupted status="open" + suppressed=True findings from the old behavior will need the reopen reversed. Consider adding a one-time migration: any finding with suppressed=True AND status="open" AND note containing "Suppressed by ignore pattern" should have its status restored. However, we cannot know the original status. The pragmatic approach is: let the next scan auto-resolve them (since they won't appear in detector output), and the suppression filter (Step 1) ensures they do not affect scoring in the meantime.
Low risk: Steps 3-5 are config/UI changes with no impact on scoring logic.
Critical Files for Implementation
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/scoring.py - Core fix: add suppression filter to _count_findings()
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_scoring/detection.py - Core fix: add suppression filter to _iter_scoring_candidates()
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/filtering.py - Remove reopen hack in remove_ignored_findings() + filter open_scope_breakdown()
/Users/user_c042661f/Documents/desloppify/desloppify/engine/_state/merge_findings.py - Remove reopen hack in upsert_findings()