Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -344,9 +344,9 @@ High-density product roadmap, engineering milestones, and open-source integratio
- [x] **Verification Discards Real Findings on Substring Triggers and Malformed Verdicts (P0 - Critical, Issue #513)**:
- *Context & Rationale*: From the #509 audit. Deterministic checks fire on substrings: "sse" in "processed", "if none of the roles", a bare "syntax". A verdict with `invalidated_criteria_matched` beats `verified: true`, uncertainty hides the finding, and verdicts can bind to the wrong finding.
- *Delivered*: Verdicts are read as meant: string flags, "none" criteria, and contradictory or uncertain verdicts no longer discard a finding. Verdicts bind by title, never by a shared line alone. Each deterministic check fires on its own claim, and a miscounted line past the end of a file drops the line instead of the finding. The runtime floor is the reviewed project's own, and real secrets in tests or behind redaction markers are kept. Twelve real findings the old checks discarded now survive.
- [ ] **Static Scan Reports a Clean Result When Its Scanners Are Not Installed (P2 - Medium, Issue #516)**:
- [x] **Static Scan Reports a Clean Result When Its Scanners Are Not Installed (P2 - Medium, Issue #516)**:
- *Context & Rationale*: A review prints "Static analyzers completed (0 finding(s) detected)" after naming six analyzers, when only Bandit is installed. Semgrep, Trivy, kube-linter and Pluto are skipped silently, and Gitleaks falls back to its built-in patterns. A reader takes that as a clean scan.
- *Deliverable*: State which analyzers ran and which were unavailable, in the console and the session report, and record it so benchmarks can tell a clean scan from a skipped one.
- *Delivered*: Each analyzer is recorded as ran, built-in patterns, not installed or no files. The console names the analyzers that ran and, on a separate line, those not installed. The session report has a Static Analyzers table, and `profile.json` and benchmark summaries record the states, so a benchmark shows when runs differed. The unused stage modules that still print the old message are filed as #530.
- [x] **Hallucinations Catalog Learns From Unreliable Invalidations and Never Forgets (P1 - High, Issue #514)**:
- *Context & Rationale*: From the #509 audit. The catalog learns from LLM verdicts, weak checks and evaluation replays. It rewrites builtin entries with learned words, and it never expires or lists what it learned. Some categories' ground truth only checks that the file parses.
- *Delivered*: Only deterministic invalidations with ground truth, and people, teach the catalog. Model verdicts and evaluation replays no longer do. Builtin entries are never widened, persisted or shadowed. `devops review hallucinations list` and `remove` manage learned entries. Syntax ground truth needs a syntax claim, symbol and header entries defer to their deterministic checks, mutable defaults check the cited lines, and CWE-400 steps aside for untrusted input. Reviewers are shown builtin entries only.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Task 516: Static Scan Reports a Clean Result When Its Scanners Are Not Installed

**Issue**: [#516](https://github.com/dan-petty/devops-cli/issues/516)
**Status**: Backlog
**Status**: Done
**Milestone**: `v0.2.23`
**Priority**: `priority/p2-medium`
**Scope**: `type/bug`, `scope/review`, `priority/p2-medium`
Expand All @@ -14,9 +14,40 @@ A review prints "Static analyzers completed (0 finding(s) detected)" after namin
when only Bandit is installed. Semgrep, Trivy, kube-linter and Pluto are skipped silently, and
Gitleaks falls back to its built-in patterns. A reader takes that as a clean scan.

#### Key Deliverables:
- State which analyzers ran and which were unavailable, in the console and the session report.
- Record it so benchmarks can tell a clean scan from a skipped one.
- Unit and integration test coverage with structural tuple equality assertions.
- Maintain cyclomatic complexity $M \le 10$ and nesting depth $\le 5$.
- 100% passing across Gated CI validation suite (`uv run devops ci`).
### Key Deliverables Completed:

- [x] **Each analyzer's part is known**: before reporting, the pipeline records how each of the
six analyzers took part in the review:
- ran;
- used built-in patterns (Gitleaks without its binary);
- not installed;
- had no files of its kind (no Python for Bandit; no YAML for Kube-linter and Pluto; no
Dockerfile or lockfile for Trivy).
- [x] **Console**: "Static analyzers completed (N finding(s) detected)" is replaced by the
analyzers that ran and their findings, and a separate line naming those not installed. When
none ran, it says so.
- [x] **Session report**: `review.md` has a Static Analyzers table with each analyzer's result.
- [x] **Benchmarks**: `profile.json` records the states, and a benchmark summary keeps every state
each analyzer had across its runs. `devops review benchmark` prints them, so runs that
differ show more than one state.
- [x] **Gitleaks' binary** comes from `BIN_GITLEAKS`, like the other scanners.
- [x] **Automated Tests & Quality Gates**:
- `tests/test_review_static_analyzers.py`:
- the states for a host with only Bandit;
- the console lines, including when nothing ran;
- the reported review end to end (console, orchestrator state and profile);
- the report table;
- profile round trip, benchmark merge and benchmark output.
- 100% passing status across Gated CI validation suite (`uv run devops ci`).

## 2. Verification

On this devcontainer, which has Bandit only, as in the report:

```text
✓ Static analyzers found 0 finding(s): Bandit, Gitleaks (built-in patterns) ran
! Not installed, so not run: Kube-linter, Pluto, Trivy, Semgrep
```

The unused `stages/static_scan.py` still prints the old message and never calls Trivy. It is one
of six review stage entry points the pipeline never calls, filed for removal as #530.
99 changes: 89 additions & 10 deletions src/devops_cli/ai/review/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
get_default_personas_for_context,
)
from devops_cli.ai.review.flags import ReviewStageFlags
from devops_cli.ai.review.profile import active_profiler
from devops_cli.ai.review.review_environment import _get_reviews_base_dir
from devops_cli.ai.review.sanitization import (
_sanitize_filename,
Expand All @@ -67,6 +68,14 @@
)
from devops_cli.ai.task_loader import load_task_prompt
from devops_cli.ai.thinking_stream import extract_think_blocks
from devops_cli.config.commands import (
BIN_BANDIT,
BIN_GITLEAKS,
BIN_KUBELINTER,
BIN_PLUTO,
BIN_SEMGREP,
BIN_TRIVY,
)
from devops_cli.config.constants import (
CONST_MAX_FILE_SIZE_BYTES,
CONST_MAX_PROBE_FILE_SIZE_BYTES,
Expand All @@ -79,6 +88,7 @@
DEFAULT_REVIEW_CONVENTIONS_MAX_CHARS,
DEFAULT_REVIEW_PERSONA_REPLY_MAX_TOKENS,
)
from devops_cli.core.binaries import check_binary
from devops_cli.models.ai import FileAnalysisMeta
from devops_cli.models.vulnerability import (
DependencySpec,
Expand Down Expand Up @@ -777,6 +787,58 @@ def _collect_paths_to_analyze(
return paths_to_analyze


# How a static analyzer took part in a review. A scan that found nothing is clean only for the
# analyzers that ran; one that is not installed is skipped by its scanner without an error.
ANALYZER_RAN = "ran"
ANALYZER_BUILTIN_PATTERNS = "built-in patterns"
ANALYZER_NOT_INSTALLED = "not installed"
ANALYZER_NO_FILES = "no files"

# (name, binary, the kind of file it scans). Gitleaks falls back to built-in secret patterns.
_STATIC_ANALYZERS: tuple[tuple[str, str, str], ...] = (
("Bandit", BIN_BANDIT, "python"),
("Kube-linter", BIN_KUBELINTER, "yaml"),
("Pluto", BIN_PLUTO, "yaml"),
("Trivy", BIN_TRIVY, "container"),
("Semgrep", BIN_SEMGREP, "any"),
("Gitleaks", BIN_GITLEAKS, "any"),
)
_ANALYZERS_WITH_BUILTIN_PATTERNS = frozenset({"Gitleaks"})


def _static_analyzer_states(files_by_kind: dict[str, list[Path]]) -> dict[str, str]:
"""How each static analyzer takes part: runs, uses built-in patterns, is missing, or has no files."""
states: dict[str, str] = {}
for name, binary, kind in _STATIC_ANALYZERS:
if not files_by_kind.get(kind):
states[name] = ANALYZER_NO_FILES
elif check_binary(binary):
states[name] = ANALYZER_RAN
elif name in _ANALYZERS_WITH_BUILTIN_PATTERNS:
states[name] = ANALYZER_BUILTIN_PATTERNS
else:
states[name] = ANALYZER_NOT_INSTALLED
return states


def _static_analyzer_summary(states: dict[str, str], findings: int) -> list[str]:
"""Console lines naming the analyzers that ran and those skipped for not being installed."""
ran = [
f"{name} (built-in patterns)" if state == ANALYZER_BUILTIN_PATTERNS else name
for name, state in states.items()
if state in (ANALYZER_RAN, ANALYZER_BUILTIN_PATTERNS)
]
missing = [name for name, state in states.items() if state == ANALYZER_NOT_INSTALLED]
lines = (
[f" [dim]✓ Static analyzers found {findings} finding(s): {', '.join(ran)} ran[/dim]"]
if ran
else [" [yellow]! No static analyzer ran[/yellow]"]
)
if missing:
lines.append(f" [yellow]! Not installed, so not run: {', '.join(missing)}[/yellow]")
return lines


def _scan_gitleaks_and_semgrep(all_resolved: list[Path]) -> list[SavedFinding]:
"""Run Gitleaks secret and Semgrep AST static analysis."""
if not all_resolved:
Expand Down Expand Up @@ -883,6 +945,7 @@ def __init__(
# Checks the findings llm_client produced; the same client unless one is given.
self.verification_client = verification_client or self.llm_client
self.errored_files: dict[str, str] = {}
self.static_analyzers: dict[str, str] = {}
self._conventions_by_dir: dict[Path, str] = {}

def _resolve_file_path(self, fpath: str) -> Path:
Expand Down Expand Up @@ -1065,11 +1128,7 @@ def _run_static_scanners(self, file_paths: list[str]) -> dict[str, list[SavedFin
try:
from devops_cli.security.bandit import run_bandit_scan

print_info(
" • Running static security analyzers "
"(Bandit, Kube-linter, Pluto, Trivy, Semgrep, Gitleaks)...",
prefix=False,
)
print_info(" • Running static security analyzers...", prefix=False)

with trace_span(
"security.static_scanners", attributes={"file_count": n_paths}
Expand Down Expand Up @@ -1099,6 +1158,14 @@ def _run_static_scanners(self, file_paths: list[str]) -> dict[str, list[SavedFin

# 4. Gitleaks & Semgrep scans
all_static_findings.extend(_scan_gitleaks_and_semgrep(all_resolved))
self._record_static_analyzers(
{
"python": py_paths,
"yaml": yaml_paths,
"container": docker_lock_paths,
"any": all_resolved,
}
)

static_findings_by_file = _match_static_findings_to_files(
all_static_findings, file_paths
Expand All @@ -1112,16 +1179,19 @@ def _run_static_scanners(self, file_paths: list[str]) -> dict[str, list[SavedFin
}
sc_span.set_attributes(sc_attrs)

print_info(
f" [dim]✓ Static analyzers completed "
f"({len(all_static_findings)} finding(s) detected)[/dim]",
prefix=False,
)
for line in _static_analyzer_summary(self.static_analyzers, len(all_static_findings)):
print_info(line, prefix=False)
except Exception as exc:
logger.debug("Static security scanning failed or skipped: %s", exc)

return static_findings_by_file

def _record_static_analyzers(self, files_by_kind: dict[str, list[Path]]) -> None:
"""Keep how each analyzer took part, for the report and the review's profile."""
self.static_analyzers = _static_analyzer_states(files_by_kind)
if profiler := active_profiler():
profiler.set_static_analyzers(self.static_analyzers)

def _extract_dependencies_and_network_references(
self, file_paths: list[str]
) -> tuple[
Expand Down Expand Up @@ -2497,6 +2567,8 @@ def _build_consolidated_markdown_report(
lines.extend(self._build_dependencies_table(all_deps))
lines.extend(self._build_network_table(all_nets))

lines.extend(self._build_static_analyzers_section())

if self.errored_files:
lines.append("## Skipped / Errored Files")
lines.append("| File Path | Stage / Error Reason |")
Expand All @@ -2509,6 +2581,13 @@ def _build_consolidated_markdown_report(

return "\n".join(lines)

def _build_static_analyzers_section(self) -> list[str]:
"""Which static analyzers ran, so a scan with no findings is not read as clean."""
if not self.static_analyzers:
return []
rows = [f"| {name} | {state} |" for name, state in self.static_analyzers.items()]
return ["## Static Analyzers", "| Analyzer | Result |", "|---|---|", *rows, ""]

def _render_console_findings_table(
self, console: Any, reportable_findings: list[SavedFinding]
) -> None:
Expand Down
21 changes: 21 additions & 0 deletions src/devops_cli/ai/review/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ class ReviewProfile(BaseModel):
candidate_findings: int = 0
verified_findings: int = 0
reported_findings: int = 0
# How each static analyzer took part: ran, built-in patterns, not installed or no files. A
# scan that found nothing is clean only for the analyzers that ran.
static_analyzers: dict[str, str] = Field(default_factory=dict)
stages: list[StageProfile] = Field(default_factory=list)

@property
Expand Down Expand Up @@ -98,6 +101,7 @@ def __init__(self) -> None:
self._started = time.monotonic()
self._stages: dict[str, StageProfile] = {}
self._findings = (0, 0, 0)
self._static_analyzers: dict[str, str] = {}

def observe(self, call: dict[str, Any]) -> None:
"""Credit an LLM call to the stage running in the caller's context.
Expand Down Expand Up @@ -125,6 +129,9 @@ def add_stage_time(self, name: str, seconds: float) -> None:
def set_findings(self, *, candidates: int, verified: int, reported: int) -> None:
self._findings = (candidates, verified, reported)

def set_static_analyzers(self, states: dict[str, str]) -> None:
self._static_analyzers = dict(states)

def build(self, *, session_id: str, target: str, files: int = 0) -> ReviewProfile:
"""Assemble the profile of everything recorded so far."""
with self._lock:
Expand All @@ -144,6 +151,7 @@ def build(self, *, session_id: str, target: str, files: int = 0) -> ReviewProfil
candidate_findings=candidates,
verified_findings=verified,
reported_findings=reported,
static_analyzers=dict(self._static_analyzers),
stages=stages,
)

Expand Down Expand Up @@ -223,6 +231,8 @@ class BenchmarkSummary(BaseModel):
median_candidate_findings: float
median_reported_findings: float
median_seconds_per_candidate: float | None = None
# Every state each static analyzer had across the runs; runs that differ show more than one.
static_analyzers: dict[str, list[str]] = Field(default_factory=dict)
stages: list[StageSummary] = Field(default_factory=list)
sessions: list[str] = Field(default_factory=list)

Expand All @@ -240,6 +250,16 @@ def _median(values: list[float]) -> float:
return round(float(statistics.median(values)), 3) if values else 0.0


def _analyzer_states_across(profiles: list[ReviewProfile]) -> dict[str, list[str]]:
"""The states each static analyzer had across runs, in the order they first appeared."""
states: dict[str, list[str]] = {}
for profile in profiles:
for name, state in profile.static_analyzers.items():
if state not in states.setdefault(name, []):
states[name].append(state)
return states


def summarize_profiles(profiles: list[ReviewProfile]) -> BenchmarkSummary:
"""Summarise repeated reviews by their medians; single runs of a review are noisy."""
per_candidate = [p.seconds_per_candidate for p in profiles if p.seconds_per_candidate]
Expand Down Expand Up @@ -270,6 +290,7 @@ def summarize_profiles(profiles: list[ReviewProfile]) -> BenchmarkSummary:
median_candidate_findings=_median([float(p.candidate_findings) for p in profiles]),
median_reported_findings=_median([float(p.reported_findings) for p in profiles]),
median_seconds_per_candidate=_median(per_candidate) if per_candidate else None,
static_analyzers=_analyzer_states_across(profiles),
stages=stages,
sessions=[p.session_id for p in profiles],
)
Expand Down
5 changes: 5 additions & 0 deletions src/devops_cli/commands/review.py
Original file line number Diff line number Diff line change
Expand Up @@ -1053,6 +1053,11 @@ def _render_benchmark(summary: BenchmarkSummary, saved: Path) -> None:
+ (f", {per_candidate:.1f}s per candidate" if per_candidate else ""),
prefix=False,
)
if summary.static_analyzers:
analyzers = ", ".join(
f"{name} {' / '.join(states)}" for name, states in summary.static_analyzers.items()
)
print_info(f"Static analyzers: {escape_text(analyzers)}", prefix=False)
rows = [
[
stage.name,
Expand Down
4 changes: 2 additions & 2 deletions src/devops_cli/security/gitleaks.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from typing import Any

from devops_cli.ai.review_schema import Finding
from devops_cli.config.commands import build_gitleaks_cmd
from devops_cli.config.commands import BIN_GITLEAKS, build_gitleaks_cmd
from devops_cli.config.defaults import (
DEFAULT_CURRENT_PATH,
DEFAULT_SUBPROCESS_TIMEOUT_SECONDS,
Expand Down Expand Up @@ -174,7 +174,7 @@ class GitleaksScanner(BaseSecurityScanner):
"""Declarative security scanner adapter for Gitleaks secret detection."""

name: str = "gitleaks"
binary_name: str = "gitleaks"
binary_name: str = BIN_GITLEAKS

def build_command(
self,
Expand Down
Loading
Loading