ariadne/ariadne/services/hermes_code_candidates.py
codex f8a529e196
All checks were successful
Tests / Declarative: Post Actions passed: 1348
feat(hermes): propose fixes for SonarQube findings on a schedule
Triage has only ever entered on a failure. Static analysis is the opposite
shape - a standing backlog that never fails a build and so never asks anyone
for attention. On this instance that backlog is 139 open findings on Ariadne
alone, each already naming its file, its line, its rule and what is wrong.
That is better-located evidence than the console text the code-repair flow
normally mines, and it was being thrown away.

This is a second way into the same flow, not a second flow. A scheduled sweep
picks one finding and hands it to the existing proposal path, which is
unchanged: Hermes returns a patch as data, Ariadne validates it against the
file it names, pushes a branch, opens a pull request nobody merges. A finding
arriving from outside the build is not a reason to relax the gates that make a
proposal worth reading, so it does not.

Three deliberate limits. Security hotspots are never fetched: SonarQube models
them as needing human review, the quality gate here fails on exactly that
condition, and an automation that resolved them would be marking them
reviewed without review - defeating the control rather than satisfying it.
Findings already marked won't-fix carry a judgement someone made, and
reopening it produces pull requests that argue with a person. And the sweep
proposes one fix per run by default, because 139 pull requests nobody reads
would make the review gate theatre.

Selection is by SonarQube's own effort estimate rather than severity: effort
is the closest available proxy for the one-anchor change the patch validator
can actually check, so a trivial CRITICAL beats an involved MINOR. An
unparseable estimate is treated as ineligible, not as free.

Off by default. Triage reacts to a failure someone already cares about; this
opens pull requests nobody asked for, and that is a decision an operator makes
deliberately rather than inherits on upgrade.

Branch naming now sanitizes its token, since it arrives from a finding key as
well as a build number and a ref is one of the few places where an unexpected
character stops being cosmetic.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 22:08:42 -03:00

359 lines
14 KiB
Python

"""Select which source files a build's failures implicate.
The code-repair flow used to patch one hardcoded file. Real service
repositories hold many, and the failing console output is the only evidence
that says which of them are in play: pytest tracebacks, Rust diagnostics, and
JS/TS stack frames all name a `path:line`. This module turns those references
into a short, ranked, safety-filtered candidate list.
`FILE_REFERENCE_PATTERNS` is deliberately reviewable: every entry is a named
regex an operator can read, grep for, and test in isolation.
Ranking is tiered rather than a single score, because the two signals answer
different questions. The console failure region a path first appears in says
*which failure* implicates it, and the earliest enforced failure is the one
worth repairing; reference count and "is this a test file" only break ties
inside one region. A test file stays a candidate - sometimes the test is the
thing that is wrong - it just loses to a source file that the same failure
implicates equally.
"""
from __future__ import annotations
import re
from typing import Any
DEFAULT_MAX_CANDIDATES = 3
DEFAULT_TEST_PATH_MARKERS: tuple[str, ...] = ("tests/", "test_", "_test.")
# Path characters accepted inside a console file reference. Deliberately
# excludes the backslash, whitespace, quotes, and brackets so a match stops at
# the surrounding console punctuation instead of swallowing it.
_PATH_CHARS = r"[A-Za-z0-9_./+\-]"
_FILE_REF = _PATH_CHARS + r"+\.[A-Za-z0-9]{1,6}"
# Bundler and code-host references carry a query or anchor between the file
# and its line number (`src/panel.tsx?t=1699:10:5`); it is consumed here so
# the reference is still recognised, and never captured as part of the path.
_NOISE = r"(?:[?#][^\s:]*)?"
FILE_REFERENCE_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
# python: File "path/to/file.py", line 123
("python_traceback", re.compile(r'File "(' + _FILE_REF + r')", line \d+')),
# pytest: FAILED tests/test_x.py::test_y / ERROR tests/test_x.py
("pytest_summary", re.compile(r"(?:FAILED|ERROR)\s+(" + _FILE_REF + r")(?=::|\s|$)")),
# rust: --> src/lib.rs:20:5
("rust_diagnostic", re.compile(r"-->\s+(" + _FILE_REF + r")" + _NOISE + r":\d+:\d+")),
# js/ts: at fn (path/to/file.ts:10:5) / at path/to/file.tsx:10:5
(
"js_stack_frame",
re.compile(r"\bat\s+(?:[^\s()]+\s+\()?(" + _FILE_REF + r")" + _NOISE + r":\d+:\d+"),
),
# generic: path/to/file.<ext>[?query|#anchor]:<line>[:<col>]
("path_with_line", re.compile(r"(" + _FILE_REF + r")" + _NOISE + r":\d+(?::\d+)?")),
)
# Anything up to and including a `/workspace/<something>/` segment is the build
# agent's checkout directory, not part of the repository-relative path.
_WORKSPACE_PREFIX = re.compile(r"^.*?/workspace/[^/]+/")
_REPEATED_SLASHES = re.compile(r"/{2,}")
_NOISE_SEPARATORS = ("?", "#")
# Absolute imports only. A relative import gives no repository-root path, and
# guessing one would fetch the wrong file.
_IMPORT_RE = re.compile(
r"^[ \t]*(?:from[ \t]+(?P<module>[A-Za-z_][\w.]*)[ \t]+import[ \t]+(?P<names>[^\n#]+)"
r"|import[ \t]+(?P<plain>[A-Za-z_][\w.]*))",
re.MULTILINE,
)
_NAME_SPLIT = re.compile(r"[ \t]*,[ \t]*")
_IMPORT_FANOUT = 4
def extract_candidate_paths(bundle: dict, cfg: dict) -> list[str]:
"""Rank the repository files that a build's console failures implicate.
Inputs: an evidence bundle from `collect_evidence` (the
`jenkins.console_failures` regions in chronological order, then
`jenkins.console_tail`) and a cfg carrying `allowed_suffixes`,
`allowed_path_prefixes`, `max_candidates` (default 3), and optional
`test_path_markers`.
Outputs: at most `max_candidates` repository-relative paths, best first:
earliest failure region wins, then more references, then non-test paths.
Paths outside the allowed prefixes/suffixes and any traversal, absolute,
backslash, or NUL-bearing path are dropped. Never raises; returns [] when
nothing matches.
A bundle carrying `sonarqube.issues` leads with the files those findings
name. Ranking console references is inference about where a failure came
from; a static-analysis finding is a direct statement of which file and
line are wrong, so guessing alongside it would only add noise.
"""
try:
named = sonar_paths(bundle, cfg)
references = _references(_search_texts(bundle), cfg)
ranked = sorted(references, key=lambda path: _rank_key(path, references[path], cfg))
ordered = named + [path for path in ranked if path not in named]
return ordered[: _max_candidates(cfg)]
except Exception:
return []
def sonar_paths(bundle: dict, cfg: dict) -> list[str]:
"""Return the writable files named by the bundle's SonarQube findings.
Inputs: an evidence bundle whose optional `sonarqube.issues` entries carry
a `path`, and the code cfg. Outputs: the distinct allowed paths in the
order the findings arrived. Never raises.
"""
try:
sonar = bundle.get("sonarqube") if isinstance(bundle.get("sonarqube"), dict) else {}
issues = sonar.get("issues")
found: list[str] = []
for issue in issues if isinstance(issues, list) else []:
if not isinstance(issue, dict):
continue
path = str(issue.get("path") or "")
if path and path not in found and _is_allowed(path, cfg) and _is_safe(path):
found.append(path)
return found
except Exception:
return []
def is_test_path(path: str, cfg: dict) -> bool:
"""Report whether a repository path looks like a test file.
Inputs: a repository-relative path and a cfg whose optional
`test_path_markers` overrides `DEFAULT_TEST_PATH_MARKERS`. A marker ending
in "/" matches a directory segment; any other marker matches the file name
at a non-alphanumeric boundary, so "test_" hits `test_x.py` but not
`latest_run.py`.
Outputs: True when any marker matches. Never raises.
"""
try:
segments = str(path).split("/")
name = segments[-1]
directories = segments[:-1]
return any(
_marker_hit(marker, name, directories) for marker in _test_markers(cfg)
)
except Exception:
return False
def _test_markers(cfg: dict) -> tuple[str, ...]:
"""Return the configured test-path markers, or the module defaults."""
markers = cfg.get("test_path_markers") if isinstance(cfg, dict) else None
if not markers:
return DEFAULT_TEST_PATH_MARKERS
return tuple(str(marker) for marker in markers if str(marker))
def _marker_hit(marker: str, name: str, directories: list[str]) -> bool:
"""Match one test marker against a file name or its directories."""
if marker.endswith("/"):
return marker.rstrip("/") in directories
if not marker[0].isalnum():
return marker in name
index = name.find(marker)
while index >= 0:
if index == 0 or not name[index - 1].isalnum():
return True
index = name.find(marker, index + 1)
return False
def _search_texts(bundle: dict) -> list[str]:
"""Return the console texts to scan, earliest failure region first."""
if not isinstance(bundle, dict):
return []
jenkins = bundle.get("jenkins")
if not isinstance(jenkins, dict):
return []
regions = jenkins.get("console_failures")
texts = [
str(region.get("text") or "")
for region in (regions if isinstance(regions, list) else [])
if isinstance(region, dict)
]
texts.append(str(jenkins.get("console_tail") or ""))
return texts
def _references(texts: list[str], cfg: dict) -> dict[str, dict[str, Any]]:
"""Collect every allowed path reference with where it first appeared."""
found: dict[str, dict[str, Any]] = {}
for region_index, text in enumerate(texts):
for line_index, line in enumerate(text.splitlines()):
for path, column in _line_paths(line, cfg):
entry = found.setdefault(
path, {"first": (region_index, line_index, column), "lines": set()}
)
entry["lines"].add((region_index, line_index))
return found
def _line_paths(line: str, cfg: dict) -> list[tuple[str, int]]:
"""Return the allowed paths one console line names, leftmost first.
A single line can match several patterns (a generic `path:line` hit and a
language-specific one), so hits are collapsed per path here; that keeps
the reference count a count of *lines*, not of regexes that fired.
"""
columns: dict[str, int] = {}
for _name, pattern in FILE_REFERENCE_PATTERNS:
for match in pattern.finditer(line):
path = _normalize(match.group(1))
if not _is_allowed(path, cfg, readable=True):
continue
column = match.start(1)
if column < columns.get(path, column + 1):
columns[path] = column
return sorted(columns.items(), key=lambda item: (item[1], item[0]))
def _normalize(raw: str) -> str:
"""Reduce a raw console file reference to a repository-relative path."""
path = raw.strip()
for separator in _NOISE_SEPARATORS:
path = path.split(separator)[0]
path = _REPEATED_SLASHES.sub("/", path)
path = _WORKSPACE_PREFIX.sub("", path)
while path.startswith("./"):
path = path[2:]
return path
def imported_source_paths(text: str, cfg: dict) -> list[str]:
"""Return the in-repo modules a Python source file imports.
Inputs: the contents of a fetched file (in practice the failing test) and
the same cfg used for candidate selection. Outputs: repository-relative
paths derived from its import statements, in first-seen order, filtered by
the configured prefixes and suffixes exactly like any other candidate.
A pytest assertion that fails inside a test names only the test file, so
the defective source is often absent from the console entirely. Its import
list is the one deterministic link back to the module under test. Never
raises; returns [] on any parse problem.
"""
try:
seen: list[str] = []
for match in _IMPORT_RE.finditer(str(text)):
for path in _module_paths(match):
if _is_allowed(path, cfg) and path not in seen:
seen.append(path)
return seen
except Exception:
return []
def _module_paths(match: re.Match[str]) -> list[str]:
"""Turn one import statement into the repository paths it could name.
`from a.b import c` may mean either the module `a/b.py` or the submodule
`a/b/c.py`, and both conventions are common, so both are offered and the
allowlist and the fetch decide which exists.
"""
plain = match.group("plain")
if plain:
return [f"{plain.replace('.', '/')}.py"]
module = match.group("module")
base = module.replace(".", "/")
paths = [f"{base}.py"]
for name in _NAME_SPLIT.split(match.group("names") or ""):
cleaned = name.strip().split(" as ")[0].strip().strip("()")
if cleaned and cleaned.isidentifier():
paths.append(f"{base}/{cleaned}.py")
return paths
def queue_imported_sources(
cfg: dict, path: str, contents: str, queue: list[str], queued: set[str]
) -> None:
"""Follow a failing test's imports back to the module it exercises.
Inputs: the candidate cfg, the path and contents just fetched, and the
caller's fetch queue plus the set of paths already queued, both mutated in
place. Only test files are followed, and only into paths the write
allowlist already permits, so this widens which files may be read and
never which files may be written. Never raises.
"""
if not is_test_path(path, cfg):
return
# Both import conventions are guessed, so a busy test file can name more
# modules than are worth fetching. The context budget already bounds what
# is kept; this bounds what is asked for.
room = max(0, _max_candidates(cfg) * _IMPORT_FANOUT - len(queued))
for extra in imported_source_paths(contents, cfg)[:room]:
if extra not in queued:
queued.add(extra)
queue.append(extra)
def _is_allowed(path: str, cfg: dict, *, readable: bool = False) -> bool:
"""Gate one normalized path on safety and the configured allowlists.
`readable` additionally admits test files. A failing test is the evidence
that explains the defect and is often the only file the console names, but
the patch validator gates writes on `allowed_path_prefixes` alone, so a
test admitted here can be read and never patched.
"""
if not _is_safe(path):
return False
suffixes = [str(item) for item in (cfg.get("allowed_suffixes") or [])]
prefixes = [str(item) for item in (cfg.get("allowed_path_prefixes") or [])]
if not any(path.endswith(suffix) for suffix in suffixes):
return False
if any(path.startswith(prefix) for prefix in prefixes):
return True
return readable and is_test_path(path, cfg)
def _is_safe(path: str) -> bool:
"""Reject traversal, absolute, backslash, and NUL-bearing paths."""
if not path or "\x00" in path or "\\" in path:
return False
if path.startswith("/"):
return False
return ".." not in path
def _rank_key(path: str, entry: dict[str, Any], cfg: dict) -> tuple:
"""Build the deterministic sort key for one candidate path."""
region_index, line_index, column = entry["first"]
return (
region_index,
-len(entry["lines"]),
is_test_path(path, cfg),
line_index,
column,
path,
)
def _max_candidates(cfg: dict) -> int:
"""Return the configured candidate cap, defaulting when it is unusable."""
try:
value = int(cfg.get("max_candidates"))
except (TypeError, ValueError):
return DEFAULT_MAX_CANDIDATES
return value if value > 0 else DEFAULT_MAX_CANDIDATES