Two capabilities that make triage useful outside the demo surface. Issues: when triage concludes a human is needed, file an issue in the failing service's own repository carrying classification, confidence, the facts with their sources, the inferences and a Jenkins link, plus a footer stating Hermes has no write access and nothing was changed. Opt-in per job via a repo map, deduplicated by job+classification so a repeatedly failing job yields one issue per kind of failure rather than one per build, and capped per tick. Disabled by default. Real-repo patches: candidate files are selected from the console failure regions (Python, Rust and JS/TS reference patterns), filtered to each repo's allowed prefixes and suffixes, ranked earliest-failure-first with source preferred over test files, and fetched whole - never truncated, because a patch anchor must match exactly. Per-job owner/repo/base-branch resolution; the patch is validated against the file the model actually chose, and an unlisted path is rejected. Legacy single-repo demo behaviour is preserved unchanged. 131 new tests; 472 pass in the hermes suite. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
241 lines
9.0 KiB
Python
241 lines
9.0 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 = ("?", "#")
|
|
|
|
|
|
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.
|
|
"""
|
|
|
|
try:
|
|
references = _references(_search_texts(bundle), cfg)
|
|
ranked = sorted(references, key=lambda path: _rank_key(path, references[path], cfg))
|
|
return ranked[: _max_candidates(cfg)]
|
|
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):
|
|
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 _is_allowed(path: str, cfg: dict) -> bool:
|
|
"""Gate one normalized path on safety and the configured allowlists."""
|
|
|
|
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
|
|
return any(path.startswith(prefix) for prefix in prefixes)
|
|
|
|
|
|
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
|