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.

feat(health): fix hints and a local reproduce command on failing gate runs (#4642)

Raghav Chamadiya55a42fb370d8
diff --git a/docs/start/CI.md b/docs/start/CI.md
index 1e7228bb6..1bf034a32 100644
--- a/docs/start/CI.md
+++ b/docs/start/CI.md
@@ -563,6 +563,9 @@ health-fail-at: medium
| `health-fail-at` | `REPOWISE_HEALTH_FAIL_AT` | `--fail-at` | Lowest failing severity: `medium`, `high` (default), `critical`. |
Findings that do not fail warn. On GitLab, set `REPOWISE_HEALTH: "true"`.
+With `--format github`, each failing finding's annotation ends in a one-line
+fix hint, and a failing run names the `repowise health check` command that
+reproduces it locally, in the job log and the summary.
### Before an agent commits or pushes
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/check.py b/packages/cli/src/repowise/cli/commands/health_cmd/check.py
index a78ca254c..9e8780053 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/check.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/check.py
@@ -8,7 +8,7 @@ ones (:mod:`repowise.cli.ci`).
from __future__ import annotations
from collections.abc import Callable
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from typing import TYPE_CHECKING
import click
@@ -123,7 +123,7 @@ def health_check(
except Exception as exc:
# A crash must never read as a failed gate.
cannot_evaluate(fmt, "internal_error", f"health check failed unexpectedly: {exc!r}")
- _EMITTERS.get(fmt, _print_table)(verdict)
+ _EMITTERS.get(fmt, _print_table)(replace(verdict, diff_risk=diff_risk))
if not verdict.result.passed:
raise click.exceptions.Exit(EXIT_GATE_FAILED)
@@ -135,6 +135,14 @@ class _Verdict:
result: GateResult
delta: ChangeHealthDelta
label: str
+ #: ``--diff-risk`` as given, so the reproduce command matches the run.
+ diff_risk: tuple[str, ...] = ()
+
+ @property
+ def reproduce(self) -> str:
+ from repowise.core.analysis.health_gate import reproduce_command
+
+ return reproduce_command(self.label, self.result, self.diff_risk)
def _diff_risk_levels(values: tuple[str, ...]) -> dict[str, str]:
@@ -215,7 +223,9 @@ def _not_evaluated(code: str, message: str) -> CannotEvaluateError:
def _markdown(v: _Verdict) -> str:
from repowise.core.analysis.health_gate import render_markdown, scope_line
- return render_markdown(v.result, label=v.label, scope=scope_line(v.delta))
+ return render_markdown(
+ v.result, label=v.label, scope=scope_line(v.delta), reproduce=v.reproduce
+ )
def _emit_json(v: _Verdict) -> None:
@@ -244,10 +254,10 @@ def _emit_markdown(v: _Verdict) -> None:
def _emit_github(v: _Verdict) -> None:
from repowise.core.analysis.health_gate import gate_summary, github_annotations
- for line in github_annotations(v.result):
+ for line in github_annotations(v.result, reproduce=v.reproduce):
click.echo(line)
append_step_summary(_markdown(v))
- write_gate_summary(gate_summary(v.result))
+ write_gate_summary(gate_summary(v.result, reproduce=v.reproduce))
_COLOUR = {"error": "red", "warning": "yellow", "note": "dim"}
diff --git a/packages/core/src/repowise/core/analysis/health/suggestions.py b/packages/core/src/repowise/core/analysis/health/suggestions.py
index 7c1cfe4e7..386bca64d 100644
--- a/packages/core/src/repowise/core/analysis/health/suggestions.py
+++ b/packages/core/src/repowise/core/analysis/health/suggestions.py
@@ -51,9 +51,9 @@ _TEMPLATES: dict[str, str] = {
"if/elif ladder with polymorphism or a lookup table."
),
"repeated_nesting": (
- "Several nested blocks side by side usually mean the function "
- "does several jobs. Split it into stages so each stage stays at "
- "a single level of abstraction."
+ "Split the function into stages. Several nested blocks side by side "
+ "usually mean it does several jobs; give each stage its own helper "
+ "at a single level of abstraction."
),
"large_method": (
"Shorten the function. Extract paragraphs (each comment block "
@@ -355,6 +355,18 @@ def suggestion_for(biomarker_type: str) -> str:
)
+def hint_for(biomarker_type: str) -> str | None:
+ """The first sentence of the marker's template, for a one-line fix hint.
+
+ ``None`` when the marker has no template: the generic fallback is no hint.
+ """
+ template = _TEMPLATES.get(canonical_biomarker(biomarker_type))
+ if template is None:
+ return None
+ head, dot, _ = template.partition(". ")
+ return head + "." if dot else template
+
+
def annotate_finding(finding: dict[str, Any]) -> dict[str, Any]:
"""Return *finding* with a ``suggestion`` field added (immutable copy)."""
biomarker = str(finding.get("biomarker_type", ""))
diff --git a/packages/core/src/repowise/core/analysis/health_gate.py b/packages/core/src/repowise/core/analysis/health_gate.py
index c2f30e789..3cb3e6200 100644
--- a/packages/core/src/repowise/core/analysis/health_gate.py
+++ b/packages/core/src/repowise/core/analysis/health_gate.py
@@ -15,12 +15,13 @@ how it is judged or rendered.
from __future__ import annotations
import hashlib
+import shlex
from collections.abc import Iterable, Mapping
from dataclasses import dataclass, field
from typing import Any
from repowise.core.ci import github, gitlab, sarif
-from repowise.core.ci.markdown import ROW_LIMIT, cell, details, more_line, plural
+from repowise.core.ci.markdown import ROW_LIMIT, cell, code, details, more_line, plural
from repowise.core.ci.summary import GateSummary, SummaryFinding
from ..test_paths import is_test_related_path
@@ -29,6 +30,7 @@ from .change_health.models import INCIDENTAL_BASES, ChangeFinding, ChangeHealthD
from .diff_risk import DiffRiskFinding
from .health.biomarker_labels import biomarker_label
from .health.scoring import is_code_shape
+from .health.suggestions import hint_for
#: ``--fail-on`` values, least to most severe: a level fails it and every level above.
FAIL_ON = ("worsened", "introduced")
@@ -328,8 +330,23 @@ _HEADLINE = {
}
-def render_markdown(result: GateResult, *, label: str, scope: str) -> str:
- """Step-summary / PR-comment markdown: verdict first, then a capped table."""
+def reproduce_command(label: str, result: GateResult, diff_risk: Iterable[str] = ()) -> str:
+ """The ``repowise health check`` command that reaches *result* again locally."""
+ args = ["repowise", "health", "check", label, "--fail-on", result.fail_on]
+ args += ["--fail-at", result.fail_at]
+ for value in diff_risk:
+ args += ["--diff-risk", value]
+ return shlex.join(args)
+
+
+def render_markdown(
+ result: GateResult, *, label: str, scope: str, reproduce: str | None = None
+) -> str:
+ """Step-summary / PR-comment markdown: verdict first, then a capped table.
+
+ A failing verdict with *reproduce* (:func:`reproduce_command`) says how to
+ run the same check locally.
+ """
errors, warnings = result.at(ERROR), result.at(WARNING)
lines = [
_HEADLINE[result.verdict].format(
@@ -355,33 +372,61 @@ def render_markdown(result: GateResult, *, label: str, scope: str) -> str:
context = [f"{cell(location(f))}: {cell(f.message)}" for f in result.at(NOTE)]
if context:
lines += ["", *details("Context (moved, incidental or not code shape; never fails)", context)]
+ if reproduce and not result.passed:
+ lines += ["", f"Reproduce locally: {code(_INSTALL)}, then {code(reproduce)}"]
lines += ["", f"_{FINDINGS_BASIS}_"]
return "\n".join(lines) + "\n"
-def github_annotations(result: GateResult) -> list[str]:
- """``::error`` for failing findings and ``::warning`` for warnings, capped."""
+def github_annotations(result: GateResult, *, reproduce: str | None = None) -> list[str]:
+ """``::error`` for failing findings and ``::warning`` for warnings, capped.
+
+ A failing health finding carries its fix hint; a failing verdict with
+ *reproduce* ends in one ``::notice`` naming the local command.
+ """
out = [
github.annotation(
f.level,
- f.message,
+ _with_hint(f),
file=f.path,
line=f.line,
title=f"Health: {biomarker_label(f.rule)}",
)
for f in [*result.at(ERROR), *result.at(WARNING)]
]
- return github.cap_annotations(out, noun="health findings")
+ out = github.cap_annotations(out, noun="health findings")
+ if reproduce and not result.passed:
+ out.append(github.notice(_reproduce_line(reproduce)))
+ return out
+
+#: How the gate is installed outside the Action, as docs/start/CI.md has it.
+_INSTALL = "pip install repowise"
-def gate_summary(result: GateResult) -> GateSummary:
- """The gate's row in the combined CI summary: errors and warnings, notes left out."""
+
+def _reproduce_line(reproduce: str) -> str:
+ return f"Reproduce locally: {_INSTALL}, then {reproduce}"
+
+
+def _with_hint(f: GateFinding) -> str:
+ """*f*'s message, plus the first sentence of its fix when it fails the gate."""
+ hint = hint_for(f.rule) if f.level == ERROR and f.source == _SOURCE else None
+ return f"{f.message}. {hint}" if hint else f.message
+
+
+def gate_summary(result: GateResult, *, reproduce: str | None = None) -> GateSummary:
+ """The gate's row in the combined CI summary: errors and warnings, notes left out.
+
+ A failing row with *reproduce* names the local command in its headline.
+ """
errors, warnings = result.at(ERROR), result.at(WARNING)
headline = {
PASS: "Nothing this change wrote fails the gate.",
WARN: f"Passed with {plural(len(warnings), 'warning')}.",
FAIL: f"Fails on {plural(len(errors), 'finding')} the change wrote.",
}[result.verdict]
+ if reproduce and not result.passed:
+ headline = f"{headline} {_reproduce_line(reproduce)}"
findings = tuple(
SummaryFinding(f.level, f.path, f.line, f.message, f.fingerprint)
for f in [*errors, *warnings]
diff --git a/tests/unit/analysis/test_health_gate.py b/tests/unit/analysis/test_health_gate.py
index 9046ba049..b8463b397 100644
--- a/tests/unit/analysis/test_health_gate.py
+++ b/tests/unit/analysis/test_health_gate.py
@@ -20,10 +20,12 @@ from repowise.core.analysis.health_gate import (
as_json,
assemble,
evaluate,
+ gate_summary,
github_annotations,
render_gitlab,
render_markdown,
render_sarif,
+ reproduce_command,
)
@@ -220,6 +222,46 @@ def test_github_annotates_errors_and_warnings_only():
assert lines[0].startswith("::error file=app.py,line=5,")
+def test_a_failing_annotation_carries_the_first_sentence_of_its_fix():
+ error, warning = github_annotations(mixed())
+ assert error.endswith(
+ "::tangle has cyclomatic complexity 26 (introduced, high). Reduce cyclomatic complexity."
+ )
+ assert "Reduce cyclomatic complexity" not in warning
+
+
+def test_a_failing_run_ends_in_one_reproduce_notice():
+ result = mixed()
+ command = reproduce_command("origin/main...HEAD", result, ("error",))
+ assert command == (
+ "repowise health check origin/main...HEAD --fail-on introduced --fail-at high "
+ "--diff-risk error"
+ )
+ lines = github_annotations(result, reproduce=command)
+ assert lines[-1] == f"::notice::Reproduce locally: pip install repowise, then {command}"
+ assert sum(line.startswith("::notice") for line in lines) == 1
+ assert "Reproduce locally" in gate_summary(result, reproduce=command).headline
+ text = render_markdown(result, label="x", scope="s", reproduce=command)
+ assert f"Reproduce locally: `pip install repowise`, then `{command}`" in text
+
+
+def test_a_passing_run_carries_no_hint_or_reproduce_line():
+ result = evaluate(delta(finding(change_kind="worsened")))
+ assert result.passed
+ command = reproduce_command("main...HEAD", result)
+ lines = github_annotations(result, reproduce=command)
+ assert [line.split(" ", 1)[0] for line in lines] == ["::warning"]
+ assert lines[0].endswith("(worsened, high)")
+ assert "Reproduce" not in render_markdown(result, label="x", scope="s", reproduce=command)
+ assert "Reproduce" not in gate_summary(result, reproduce=command).headline
+
+
+def test_a_diff_risk_error_keeps_its_own_message():
+ risk = GateFinding("diff-risk", "added-suppression", ERROR, "a.py", 1, "Adds a noqa.", "f")
+ (line,) = github_annotations(assemble([risk], fail_on="introduced"))
+ assert line.endswith("::Adds a noqa.")
+
+
def test_sarif_levels_follow_the_gate_with_line_free_fingerprints():
log = render_sarif(mixed(), tool_version="0")
results = log["runs"][0]["results"]
diff --git a/tests/unit/cli/test_health_check_cmd.py b/tests/unit/cli/test_health_check_cmd.py
index c717312a6..a79c5ee20 100644
--- a/tests/unit/cli/test_health_check_cmd.py
+++ b/tests/unit/cli/test_health_check_cmd.py
@@ -70,7 +70,19 @@ def test_github_format_annotates_and_fills_the_step_summary(repo, tmp_path):
result = check(repo, "--format", "github", env={"GITHUB_STEP_SUMMARY": str(summary)})
assert result.exit_code == 1
assert result.stdout.startswith("::error file=app.py,")
- assert "fails the gate" in summary.read_text(encoding="utf-8")
+ command = "repowise health check main...HEAD --fail-on introduced --fail-at high"
+ assert result.stdout.splitlines()[-1].endswith(f"then {command}")
+ text = summary.read_text(encoding="utf-8")
+ assert "fails the gate" in text and f"`{command}`" in text
+
+
+def test_github_format_on_a_passing_change_prints_no_reproduce_line(repo, tmp_path):
+ repo.commit("docs", {"README.md": "# hi\n"})
+ summary = tmp_path / "summary.md"
+ result = check(repo, "--format", "github", env={"GITHUB_STEP_SUMMARY": str(summary)})
+ assert result.exit_code == 0, result.output
+ assert "Reproduce" not in result.stdout
+ assert "Reproduce" not in summary.read_text(encoding="utf-8")
def test_sarif_and_gitlab_are_valid_documents(repo):