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
3 changes: 3 additions & 0 deletions docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,9 @@ High-density product roadmap, engineering milestones, and open-source integratio
- [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.
- *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] **Remove the Review Stage Modules the Pipeline Never Calls (P2 - Medium, Issue #530)**:
- *Context & Rationale*: Six of the seven `run_*_stage` functions in `ai/review/stages/` had no caller: they duplicated the pipeline's logic and drifted from it, such as the static scan stage's misleading "completed" message. Tests imported them, which kept them looking alive.
- *Delivered*: The five unused stage modules and `run_reporting_stage` are removed. Their session-directory and file-path containment checks moved onto the pipeline, which lacked them: session directories are checked before writing, and review file paths stay inside the target and its repository.
- [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
@@ -0,0 +1,37 @@
# Task 530: Remove the Review Stage Modules the Pipeline Never Calls

**Issue**: [#530](https://github.com/dan-petty/devops-cli/issues/530)
**Status**: Done
**Milestone**: `v0.2.23`
**Priority**: `priority/p2-medium`
**Scope**: `type/refactor`, `scope/review`, `priority/p2-medium`

---

## 1. Description & Objectives

`src/devops_cli/ai/review/stages/` exported seven `run_*_stage` functions, of which the
orchestrated pipeline called only `run_adversarial_debate_stage`; from `stages/reporting.py` it
used only `synthesize_report_executive_summary`. The other six duplicated the pipeline's logic
and had drifted from it: `static_scan.py` still printed "Static analyzers completed (0 finding(s)
detected)" and never called Trivy (#516). Tests imported them, which kept them looking alive.

### Key Deliverables Completed:

- [x] **Removed**: `pre_analysis.py`, `static_scan.py`, `persona_review.py`, `verification.py`
and `reranking.py`, and `run_reporting_stage` from `reporting.py`. `stages` now exports
the adversarial debate and the report's executive summary, the parts the pipeline uses.
- [x] **Guards moved onto the pipeline**, which lacked them:
- The orchestrator refuses a session directory with a `..` component, or outside the reviews,
working or temporary directory, before writing to it. `run_reporting_stage` checked this.
- `_resolve_file_path` resolves only to files inside the review target or its repository.
A path outside both, absolute or through `..`, falls back to a missing in-target path, as
`_resolve_target_path` required. It used to return any existing absolute path.
- [x] **Automated Tests & Quality Gates**:
- Tests of the removed functions are gone; `tests/test_review_stages.py` keeps the adversarial
debate.
- `tests/test_subsystem_containment_and_redaction.py`: the session directory and file path
containment tests now exercise the pipeline.
- The duplicate executive-summary test through `run_reporting_stage` is removed; the
pipeline's own report tests cover it.
- 100% passing status across Gated CI validation suite (`uv run devops ci`).
69 changes: 41 additions & 28 deletions src/devops_cli/ai/review/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
DEFAULT_REVIEW_PERSONA_REPLY_MAX_TOKENS,
)
from devops_cli.core.binaries import check_binary
from devops_cli.exceptions import SecurityError
from devops_cli.models.ai import FileAnalysisMeta
from devops_cli.models.vulnerability import (
DependencySpec,
Expand Down Expand Up @@ -514,6 +515,27 @@ def _page_imports(page_text: str) -> list[tuple[str, str | None]]:
return extract_imports_from_source(text)


def _checked_session_dir(session_dir: Path) -> Path:
"""A review session directory, refused when it escapes the places sessions may be written.

No `..` component, and inside the reviews directory, the working directory or the system
temporary directory.
"""
import tempfile

if any(part == ".." for part in session_dir.parts):
raise SecurityError(f"Path traversal detected in session_dir: {session_dir}")
allowed = (
_get_reviews_base_dir().resolve(),
Path.cwd().resolve(),
Path(tempfile.gettempdir()).resolve(),
)
resolved = session_dir.resolve()
if not any(resolved.is_relative_to(root) for root in allowed):
raise SecurityError(f"Session directory {session_dir} is outside allowed root directories")
return session_dir


def _build_page_review_prompt(
fpath: str,
p_idx: int,
Expand Down Expand Up @@ -959,11 +981,9 @@ def __init__(
self.concurrency = concurrency
self.parallel = parallel
self.ground_contracts = ground_contracts
if session_dir is not None:
self.session_dir = session_dir
else:
base_dir = _get_reviews_base_dir().resolve()
self.session_dir = base_dir / self.session_id
self.session_dir = _checked_session_dir(
session_dir or _get_reviews_base_dir().resolve() / self.session_id
)
self.files_dir = self.session_dir / "files"
self.session_dir.mkdir(parents=True, exist_ok=True)
self.files_dir.mkdir(parents=True, exist_ok=True)
Expand All @@ -975,34 +995,27 @@ def __init__(
self._conventions_by_dir: dict[Path, str] = {}

def _resolve_file_path(self, fpath: str) -> Path:
"""Resolve fpath to an existing filesystem Path within target_dir or repo root."""
"""Resolve fpath to an existing file within target_dir or its repository, never outside.

A path naming a file outside both, absolute or through `..`, falls back to a sanitized
path inside the target, which scanners and verification then find missing.
"""
from devops_cli.core.repo import find_repo_root

target_root = self.target_dir.resolve()
repo = find_repo_root(self.target_dir)
repo = find_repo_root(self.target_dir).resolve()
p = Path(fpath)
if p.is_absolute() and p.exists():
return p.resolve()
if (target_root / p).exists():
return (target_root / p).resolve()
if (repo / p).exists():
return (repo / p).resolve()
if (target_root / p.name).exists():
return (target_root / p.name).resolve()

try:
candidate = p if p.is_absolute() else (target_root / p)
resolved = candidate.resolve()
if resolved.exists():
candidates = [p] if p.is_absolute() else [target_root / p, repo / p, target_root / p.name]
for candidate in candidates:
try:
resolved = candidate.resolve()
except (ValueError, OSError) as exc:
logger.debug("Failed resolving path %s: %s", fpath, exc)
continue
inside = resolved.is_relative_to(target_root) or resolved.is_relative_to(repo)
if inside and resolved.exists():
return resolved
if (repo / p).resolve().exists():
return (repo / p).resolve()
except (ValueError, OSError) as exc:
logger.debug("Failed resolving path %s: %s", fpath, exc)

# Fallback to sanitized in-target path
safe_rel = Path(fpath.lstrip("/\\")).name
return target_root / safe_rel
return target_root / Path(fpath.lstrip("/\\")).name

def _get_server_info(self, client: LLMClient | None = None) -> str:
"""Describe a client's provider, host and model; the analysis client by default."""
Expand Down
16 changes: 3 additions & 13 deletions src/devops_cli/ai/review/stages/__init__.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,11 @@
"""Modular review pipeline stages for multi-persona analysis, verification, and reporting."""
"""Review pipeline stages used by the orchestrator: adversarial debate and report summaries."""

from __future__ import annotations

from devops_cli.ai.review.stages.adversarial_debate import run_adversarial_debate_stage
from devops_cli.ai.review.stages.persona_review import run_persona_review_stage
from devops_cli.ai.review.stages.pre_analysis import run_pre_analysis_stage
from devops_cli.ai.review.stages.reporting import run_reporting_stage
from devops_cli.ai.review.stages.reranking import run_reranking_stage
from devops_cli.ai.review.stages.static_scan import run_static_scan_stage
from devops_cli.ai.review.stages.verification import run_verification_stage
from devops_cli.ai.review.stages.reporting import synthesize_report_executive_summary

__all__ = [
"run_adversarial_debate_stage",
"run_persona_review_stage",
"run_pre_analysis_stage",
"run_reporting_stage",
"run_reranking_stage",
"run_static_scan_stage",
"run_verification_stage",
"synthesize_report_executive_summary",
]
35 changes: 0 additions & 35 deletions src/devops_cli/ai/review/stages/persona_review.py

This file was deleted.

44 changes: 0 additions & 44 deletions src/devops_cli/ai/review/stages/pre_analysis.py

This file was deleted.

93 changes: 0 additions & 93 deletions src/devops_cli/ai/review/stages/reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,10 @@
from __future__ import annotations

import collections
import json
import re
from pathlib import Path

from devops_cli.ai.review.review_environment import _get_reviews_base_dir
from devops_cli.ai.review_schema import SavedFinding
from devops_cli.exceptions import SecurityError
from devops_cli.models.vulnerability import DependencySpec, NetworkReference
from devops_cli.output import print_info, print_success
from devops_cli.telemetry.tracer import trace_span

_SEVERITY_WEIGHTS: dict[str, int] = {
"CRITICAL": 0,
Expand Down Expand Up @@ -171,90 +165,3 @@ def synthesize_report_executive_summary(

lines.append("")
return lines


def run_reporting_stage(
session_id: str,
session_dir: Path,
reportable_findings: list[SavedFinding],
all_deps: list[DependencySpec],
all_nets: list[NetworkReference],
n_files: int,
) -> Path:
"""Execute consolidated report generation and persistence."""
with trace_span("review.reporting", attributes={"session_id": session_id}):
if any(p == ".." for p in session_dir.parts):
raise SecurityError(f"Path traversal detected in session_dir: {session_dir}")

import tempfile

allowed_roots = [
_get_reviews_base_dir().resolve(),
Path.cwd().resolve(),
Path(tempfile.gettempdir()).resolve(),
]
resolved_session_dir = session_dir.resolve()
if not any(
resolved_session_dir == root or resolved_session_dir.is_relative_to(root)
for root in allowed_roots
):
raise SecurityError(
f"Attempted to write report outside allowed root: {resolved_session_dir}"
)

print_info(
f"Generating report for session '{session_id}'...",
prefix=False,
)

session_dir.mkdir(parents=True, exist_ok=True)
report_path = session_dir / "review_report.md"
findings_json_path = session_dir / "findings.json"

# 1. Save findings JSON
findings_data = [f.model_dump() for f in reportable_findings]
findings_json_path.write_text(json.dumps(findings_data, indent=2), encoding="utf-8")

# 2. Save Markdown Report with Executive Summary at the top
md_lines = [
f"# Consolidated Code Review Report — Session {session_id}",
"",
f"- **Files Reviewed:** {n_files}",
f"- **Total Findings:** {len(reportable_findings)}",
"",
]
md_lines.extend(
synthesize_report_executive_summary(
reportable_findings=reportable_findings,
all_deps=all_deps,
all_nets=all_nets,
)
)
md_lines.extend(
[
"## Findings Summary",
"",
"| # | Severity | Location | Title | Status |",
"| :--- | :--- | :--- | :--- | :--- |",
]
)
for idx, f in enumerate(reportable_findings, 1):
clean_sev = (
(f.severity or "INFORMATIONAL").replace("|", "\\|").replace("\n", " ").strip()
)
clean_loc = f.location.strip("`").replace("|", "\\|").replace("\n", " ").strip()
clean_title = f.title.replace("|", "\\|").replace("\n", " ").strip()
if clean_title.count("`") % 2 != 0:
clean_title += "`"
clean_status = f.status.replace("|", "\\|").replace("\n", " ").strip()
md_lines.append(
f"| {idx} | {clean_sev} | `{clean_loc}` | {clean_title} | {clean_status} |"
)

report_path.write_text("\n".join(md_lines) + "\n", encoding="utf-8")

print_success(
f"Consolidated review completed for session {session_id} "
f"({len(reportable_findings)} finding(s) saved to {session_dir})"
)
return report_path
Loading
Loading