Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(security): rescan an index whose findings predate the scanner stamp (#3516)

Raghav Chamadiya3d1e1b44c506
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index ffec2638b..54562d57b 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -68,6 +68,8 @@ from .persistence import (
health_analyzer_changed,
parser_changed,
refresh_read_snapshots,
+ rescan_security_if_changed,
+ security_scanner_changed,
stamp_head_commit,
)
from .reporting import (
@@ -1049,6 +1051,15 @@ def run_update(
"[yellow]Git history rules changed since this index was built; "
"re-reading the full history once.[/yellow]"
)
+ # Deliberately not in ``git_is_current``: the rescan does its own full parse,
+ # so falling through to the re-parse below would parse the repo twice. Every
+ # exit that skips that path runs the rescan itself instead.
+ scanner_changed = security_scanner_changed(state)
+ if scanner_changed:
+ console.print(
+ "[yellow]Security scanner changed since this index was scanned; "
+ "rescanning.[/yellow]"
+ )
# A page can be stale for a reason no commit explains: a cascade that ran
# out of budget, an interrupted run, an expiry. Git says nothing changed,
# so the shortcut below is the only place such a page could be skipped
@@ -1098,7 +1109,10 @@ def run_update(
log.debug("self_heal_skipped", reason="another update holds the lock")
else:
try:
- if needs_backfill:
+ rescanned = scanner_changed and rescan_security_if_changed(
+ repo_path, state, list(cfg.get("exclude_patterns") or [])
+ )
+ if needs_backfill or rescanned:
timings.stop("run")
save_state(
repo_path,
@@ -1328,6 +1342,8 @@ def run_update(
and not stale_deterministic_ids
):
console.print("[green]No changed files detected.[/green]")
+ if scanner_changed and not dry_run:
+ rescan_security_if_changed(repo_path, state, list(cfg.get("exclude_patterns") or []))
# Always advance the sync pointer so the on-disk freshness marker stays
# current on no-op syncs. In docs mode, no changed files means no docs
# work is pending, so the docs pointer can advance to head too, which
@@ -2528,14 +2544,9 @@ def run_update(
# be stale (#3072): the normal persist above only rescanned the changed
# files. Does its own full parse, since unlike health there is no stored
# structural fact to replay from the DB for a security finding.
- from repowise.core.analysis.security_scan import SECURITY_SCANNER_VERSION
-
- from .persistence import run_full_security_rescan, security_scanner_changed
-
- if security_scanner_changed(state):
+ if scanner_changed:
with timed(timings, "security_rescan"):
- if run_full_security_rescan(repo_path, exclude_patterns):
- state["security_scanner_version"] = SECURITY_SCANNER_VERSION
+ rescan_security_if_changed(repo_path, state, exclude_patterns)
# ---- Stored read views, then the editor files that quote them ----
_finish_outcome(repo_path, agents_md, degraded, timings=timings)
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index 4649ab97d..195b2f429 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -1790,12 +1790,27 @@ def health_analyzer_changed(state: dict) -> bool:
def security_scanner_changed(state: dict) -> bool:
"""Whether the stored security findings were written by a different scanner.
- Mirrors :func:`health_analyzer_changed`: a legacy state file with no stamp
- is not a change, it picks the stamp up on its first full security rescan
- (#3072).
+ Unlike :func:`health_analyzer_changed`, a state file with no stamp **is** a
+ change: the stamp arrived after 0.55.0 (#3086), so an unstamped store was
+ written by an older scanner. Reading absence as current would also keep it
+ unstamped forever, since only the rescan this gates writes the stamp.
+ ``init`` stamps every fresh index, so a new install never reads as stale.
"""
- stored = state.get("security_scanner_version")
- return stored is not None and stored != SECURITY_SCANNER_VERSION
+ return state.get("security_scanner_version") != SECURITY_SCANNER_VERSION
+
+
+def rescan_security_if_changed(repo_path: Any, state: dict, exclude_patterns: list[str]) -> bool:
+ """Full security rescan when the scanner changed, stamping ``state`` on success.
+
+ Returns True only when it rescanned and stamped, so the caller knows
+ ``state`` needs saving. A failed rescan leaves the stamp for a retry.
+ """
+ if not security_scanner_changed(state):
+ return False
+ if not run_full_security_rescan(repo_path, exclude_patterns):
+ return False
+ state["security_scanner_version"] = SECURITY_SCANNER_VERSION
+ return True
def full_rescore_due(state: dict, head_ts: float | None) -> bool:
diff --git a/tests/unit/cli/test_security_rescan_gate.py b/tests/unit/cli/test_security_rescan_gate.py
index 8960aadb7..0c6797a05 100644
--- a/tests/unit/cli/test_security_rescan_gate.py
+++ b/tests/unit/cli/test_security_rescan_gate.py
@@ -1,9 +1,10 @@
"""The gate that decides when `repowise update` rescans security findings
in full (#3072), and the full rescan itself.
-Mirrors ``test_health_rescore_gate.py``'s ``TestHealthAnalyzerChanged``: a
-scanner version bump is the only trigger here, there is no time cadence,
-since security findings do not decay the way health scores do.
+Like ``test_health_rescore_gate.py``'s ``TestHealthAnalyzerChanged``, except
+that a missing stamp counts as a change. A scanner version bump is the only
+trigger here, there is no time cadence, since security findings do not decay
+the way health scores do.
"""
from __future__ import annotations
@@ -21,9 +22,10 @@ from repowise.core.analysis.security_scan import SECURITY_SCANNER_VERSION
class TestSecurityScannerChanged:
- def test_absent_stamp_is_not_a_change(self):
- """A legacy state file must not read as drift (mirrors health's rule)."""
- assert security_scanner_changed({}) is False
+ def test_absent_stamp_is_a_change(self):
+ """Unlike health's rule: the stamp postdates 0.55.0, so an unstamped
+ store was written by an older scanner, and only the rescan stamps it."""
+ assert security_scanner_changed({}) is True
def test_matching_stamp_is_not_a_change(self):
assert (
diff --git a/tests/unit/cli/test_update_version_change_gate.py b/tests/unit/cli/test_update_version_change_gate.py
index f65c2c47d..ccc1da4c3 100644
--- a/tests/unit/cli/test_update_version_change_gate.py
+++ b/tests/unit/cli/test_update_version_change_gate.py
@@ -2,7 +2,8 @@
With no new commit, ``head == base_ref`` is the normal state of a checkout, so
the version stamps are the only thing that can tell ``update`` that every stored
-score or graph edge was written by an older build.
+score or graph edge was written by an older build. A scanner change is rescanned
+on that return itself, since the rescan does its own full parse.
"""
from __future__ import annotations
@@ -12,6 +13,7 @@ import pytest
from repowise.cli.commands.update_cmd import command as upd_cmd
from repowise.cli.helpers import load_state, save_state
from repowise.core.analysis.health import HEALTH_ANALYZER_VERSION
+from repowise.core.analysis.security_scan import SECURITY_SCANNER_VERSION
from .test_update_up_to_date_lock import _indexed_repo, _invoke_update
@@ -21,18 +23,31 @@ UP_TO_DATE = "Already up to date"
def test_current_versions_stay_up_to_date(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
repo, _ = _indexed_repo(tmp_path)
state = load_state(repo)
- save_state(repo, {**state, "health_analyzer_version": HEALTH_ANALYZER_VERSION})
+ save_state(
+ repo,
+ {
+ **state,
+ "health_analyzer_version": HEALTH_ANALYZER_VERSION,
+ "security_scanner_version": SECURITY_SCANNER_VERSION,
+ },
+ )
rescored: list[int] = []
monkeypatch.setattr(upd_cmd, "parser_changed", lambda _p: False)
monkeypatch.setattr(
"repowise.cli.commands.update_cmd.persistence.run_decay_health_rescore",
lambda *a, **k: rescored.append(1) or True,
)
+ rescanned: list[int] = []
+ monkeypatch.setattr(
+ "repowise.cli.commands.update_cmd.persistence.run_full_security_rescan",
+ lambda *a, **k: rescanned.append(1) or True,
+ )
out = _invoke_update(repo)
assert UP_TO_DATE in out
assert not rescored
+ assert not rescanned
def test_stale_analyzer_version_rescores_an_unchanged_checkout(tmp_path) -> None:
@@ -69,3 +84,54 @@ def test_parser_change_reparses_an_unchanged_checkout(
assert UP_TO_DATE not in out
assert "Parser changed" in out
assert rescored
+
+
[email protected]("stored", [None, SECURITY_SCANNER_VERSION - 1])
+def test_stale_scanner_rescans_an_unchanged_checkout_without_a_reparse(
+ tmp_path, monkeypatch: pytest.MonkeyPatch, stored
+) -> None:
+ """None is an index from 0.55.0 or earlier, written before the stamp."""
+ repo, c2 = _indexed_repo(tmp_path)
+ state = {**load_state(repo), "health_analyzer_version": HEALTH_ANALYZER_VERSION}
+ state.pop("security_scanner_version", None)
+ if stored is not None:
+ state["security_scanner_version"] = stored
+ save_state(repo, state)
+ monkeypatch.setattr(upd_cmd, "parser_changed", lambda _p: False)
+
+ def _no_reparse(*a, **k):
+ raise AssertionError("a scanner-only change must not re-parse for the graph")
+
+ monkeypatch.setattr(upd_cmd, "_rebuild_graph_and_git", _no_reparse)
+ rescanned: list[int] = []
+ monkeypatch.setattr(
+ "repowise.cli.commands.update_cmd.persistence.run_full_security_rescan",
+ lambda *a, **k: rescanned.append(1) or True,
+ )
+
+ out = _invoke_update(repo)
+
+ assert "Security scanner changed" in out
+ assert rescanned == [1]
+ state = load_state(repo)
+ assert state["security_scanner_version"] == SECURITY_SCANNER_VERSION
+ assert state["last_sync_commit"] == c2
+ # Stamped, so the next run is quiet again.
+ assert UP_TO_DATE in _invoke_update(repo)
+ assert rescanned == [1]
+
+
+def test_failed_rescan_leaves_the_stamp_for_a_retry(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ repo, _ = _indexed_repo(tmp_path)
+ save_state(repo, {**load_state(repo), "health_analyzer_version": HEALTH_ANALYZER_VERSION})
+ monkeypatch.setattr(upd_cmd, "parser_changed", lambda _p: False)
+ monkeypatch.setattr(
+ "repowise.cli.commands.update_cmd.persistence.run_full_security_rescan",
+ lambda *a, **k: False,
+ )
+
+ _invoke_update(repo)
+
+ assert "security_scanner_version" not in load_state(repo)