Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(ci): summarize every gate in one pull-request comment, job summary and verdict (#4313)
Raghav Chamadiyac21d834b9956
diff --git a/action.yml b/action.ymlindex 04ae98d6d..35befa74b 100644--- a/action.yml+++ b/action.yml@@ -111,6 +111,17 @@ inputs:recent commits by size and spread: a size gate, not a bug predictor.Empty reports the rank without gating.default: ""+ comment:+ description: >-+ "true" posts one pull-request comment summarizing every gate and updates+ it in place on each run. The workflow needs the pull-requests write+ permission; on a fork's pull request the comment is skipped with a warning.+ default: "false"+ github-token:+ description: >-+ Token the summary comment is posted with; a later run edits only the+ comment this token's own account posted.+ default: ${{ github.token }}upload-sarif:description: >-"true" uploads doc-drift, security and health findings to GitHub code scanning.@@ -144,6 +155,12 @@ outputs:risk:description: Exit code of the change-risk gate, empty when not run.value: ${{ steps.gates.outputs.risk }}+ verdict:+ description: >-+ All gates combined: "fail" when any gate failed or could not evaluate,+ "warn" when any passed with warnings or exited 0 without a result (an+ older Repowise), else "pass". Empty when no gate ran.+ value: ${{ steps.summary.outputs.verdict }}sarif-dir:description: Directory holding the SARIF files, when upload-sarif is on.value: ${{ steps.gates.outputs.sarif-dir }}@@ -206,9 +223,29 @@ runs:RISK_FAIL_ABOVE_PERCENTILE: ${{ inputs.risk-fail-above-percentile }}SARIF: ${{ inputs.upload-sarif }}SARIF_DIR: ${{ runner.temp }}/repowise-sarif+ REPOWISE_GATE_SUMMARY_DIR: ${{ runner.temp }}/repowise-gatesPYTHONUTF8: "1"run: bash "$GITHUB_ACTION_PATH/ci/github/run-gates.sh"+ - name: Summarize gates+ id: summary+ if: ${{ !cancelled() && steps.gates.outcome != 'skipped' }}+ shell: bash+ working-directory: ${{ inputs.working-directory }}+ env:+ EXIT_CODES: >-+ coverage=${{ steps.gates.outputs.coverage }}+ doc-drift=${{ steps.gates.outputs.doc-drift }}+ security=${{ steps.gates.outputs.security }}+ health=${{ steps.gates.outputs.health }}+ risk=${{ steps.gates.outputs.risk }}+ SUMMARY_DIR: ${{ runner.temp }}/repowise-gates+ WORKING_DIRECTORY: ${{ inputs.working-directory }}+ COMMENT: ${{ inputs.comment }}+ GH_TOKEN: ${{ inputs.github-token }}+ PYTHONUTF8: "1"+ run: bash "$GITHUB_ACTION_PATH/ci/github/summary.sh"+- name: Upload SARIFif: always() && inputs.upload-sarif == 'true' && steps.gates.outputs.sarif-dir != ''# A fork's pull request has a read-only token; the gates decide the check.diff --git a/ci/github/summary.sh b/ci/github/summary.shnew file mode 100644index 000000000..3066f2d6b--- /dev/null+++ b/ci/github/summary.sh@@ -0,0 +1,77 @@+#!/usr/bin/env bash+# Combines the gates' results for the composite action in action.yml: a verdict+# table in the job summary, the verdict step output and, with comment on, one+# pull-request comment that later runs update in place. It never fails the job:+# the gates decide that, and a summary that cannot be written leaves a warning.+# Inputs arrive as environment variables set by action.yml.++set -u++work=$(mktemp -d)+# gh is a native binary on Windows runners and does not read MSYS paths.+if command -v cygpath >/dev/null; then+ work=$(cygpath -m "$work")+fi+trap 'rm -rf "$work" "$SUMMARY_DIR"' EXIT++# EXIT_CODES lists every gate as name=code; a gate that did not run has no code.+gates=()+for pair in $EXIT_CODES; do+ [[ -n "${pair#*=}" ]] && gates+=(--gate "$pair")+done+((${#gates[@]})) || exit 0+args=("$SUMMARY_DIR" "${gates[@]}")++# One comment per working directory, so two uses of the action on one pull+# request keep their own. The key matches comment_marker in core/ci/summary.py.+key=""+if [[ -n "$WORKING_DIRECTORY" && "$WORKING_DIRECTORY" != "." ]]; then+ key=$(printf '%s' "$WORKING_DIRECTORY" | tr -c 'A-Za-z0-9_./' '_')+ args+=(--comment-key "$key")+fi+marker="<!-- repowise-ci-summary${key:+:$key} -->"++pr=""+comment_id=""+if [[ "$COMMENT" == "true" ]]; then+ pr=$(python -c 'import json, os+event = json.load(open(os.environ["GITHUB_EVENT_PATH"], encoding="utf-8"))+print((event.get("pull_request") or {}).get("number") or "")' 2>/dev/null)+ if [[ -z "$pr" ]]; then+ echo "::notice::This event has no pull request, so no summary comment is posted."+ elif ! command -v gh >/dev/null; then+ echo "::warning::The GitHub CLI (gh) is not installed, so no summary comment is posted."+ pr=""+ else+ # Only this token's own comment: anyone can post one that starts with the+ # marker. The default token cannot read /user; it posts as github-actions[bot].+ login=$(gh api user --jq .login 2>/dev/null)+ [[ "$login" =~ ^[A-Za-z0-9-]+(\[bot\])?$ ]] || login="github-actions[bot]"+ comment_id=$(gh api --paginate "repos/$GITHUB_REPOSITORY/issues/$pr/comments" \+ --jq ".[] | select(.user.login == \"$login\" and (.body | startswith(\"$marker\"))) | .id" \+ 2>/dev/null | head -n 1)+ if [[ -n "$comment_id" ]] && gh api "repos/$GITHUB_REPOSITORY/issues/comments/$comment_id" \+ --jq .body >"$work/previous.md" 2>/dev/null; then+ args+=(--previous "$work/previous.md")+ fi+ args+=(--comment-file "$work/comment.md")+ fi+fi++if ! verdict=$(repowise ci-summary "${args[@]}"); then+ echo "::warning::Could not combine the gate results; each gate's own output still stands."+ exit 0+fi+echo "verdict=$verdict" >>"$GITHUB_OUTPUT"++if [[ -n "$pr" && -s "$work/comment.md" ]]; then+ body=(-F "body=@$work/comment.md")+ # A comment that cannot be edited (deleted, or another bot's) is replaced by a new one.+ if [[ -z "$comment_id" ]] ||+ ! gh api --method PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$comment_id" "${body[@]}" >/dev/null; then+ # A pull request from a fork gets a read-only token; the gates still decide.+ gh api --method POST "repos/$GITHUB_REPOSITORY/issues/$pr/comments" "${body[@]}" >/dev/null ||+ echo "::warning::Could not post the summary comment. It needs the pull-requests write permission, which a fork's token lacks."+ fi+fi+exit 0diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 206594b6b..29ceb912d 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -2,7 +2,7 @@Every `repowise` command and flag. For a guided introduction, see the [Quickstart](../start/QUICKSTART.md).-Top-level commands (alphabetical): `agents`, `ask`, `attribution`, `augment`, `changes`, `check`, `components`,+Top-level commands (alphabetical): `agents`, `ask`, `attribution`, `augment`, `changes`, `check`, `ci-summary`, `components`,`config`, `context`, `corrections`, `costs`, `coverage`, `dead-code`, `decision`, `delete`, `distill`, `doc-drift`,`doctor`, `events`, `expand`, `export`, `generate`, `generate-claude-md`, `health`, `hook`, `impacted-tests`, `init`,`login`, `logout`, `mcp`, `next`, `overlap`, `packages`, `plugins`, `publish`, `reindex`, `report`, `restyle`, `risk`,@@ -29,7 +29,7 @@ Grouped by task; `PATH` and flags are in each command's section.[`next`](#repowise-next-path)- **Health and risk:** [`health`](#repowise-health-path), [`health check`](#repowise-health-check-revspec),[`risk`](#repowise-risk-revspec), [`overlap`](#repowise-overlap), [`dead-code`](#repowise-dead-code-path),- [`doc-drift`](#repowise-doc-drift-path), [`security`](#repowise-security), [`check`](#repowise-check-revspec),+ [`doc-drift`](#repowise-doc-drift-path), [`security`](#repowise-security), [`check`](#repowise-check-revspec), [`ci-summary`](#repowise-ci-summary-dir),[`impacted-tests`](#repowise-impacted-tests-revspec), [`coverage`](#repowise-coverage),[`components`](#repowise-components), [`packages`](#repowise-packages), [`changes`](#repowise-changes),[`suspects`](#repowise-suspects), [`events`](#repowise-events), [`report@@ -1393,6 +1393,16 @@ repowise check origin/main..HEAD --sarif-file check.sarif---+### `repowise ci-summary DIR`++Combines the gates a CI job ran into one verdict table, appended to the GitHub job summary, and prints the combined verdict (`pass`, `warn` or `fail`). Each gate run with `--format github` while `REPOWISE_GATE_SUMMARY_DIR` names a directory leaves its result there, and each `--gate NAME=EXIT_CODE` reconciles one with its exit code; a gate that left nothing reads as could not evaluate. `--comment-file` writes a pull-request comment that also lists each gate's findings, `--previous` (the comment it replaces) adds how many findings were resolved since, and `--comment-key` keeps one comment per working directory.++```bash+repowise ci-summary DIR --gate NAME=EXIT_CODE... [--comment-file FILE] [--previous FILE] [--comment-key KEY]+```++---+### `repowise events`List typed events recorded between consecutive index runs, oldest first.diff --git a/docs/start/CI.md b/docs/start/CI.mdindex d2e0f685d..aa2ea7a63 100644--- a/docs/start/CI.md+++ b/docs/start/CI.md@@ -111,16 +111,27 @@ jobs:| `working-directory` | `.` | Where to run from. || `base` | from the pull request | Range for coverage, security, health, risk and test selection; empty reads the target branch, else the default branch. || `upload-sarif` | `false` | Upload findings to [code scanning](#code-scanning-sarif). |+| `comment` | `false` | Post one pull-request comment summarizing every gate, updated in place on each run. |+| `github-token` | `github.token` | Token the summary comment is posted with; a later run edits only the comment this token's own account posted. |Gate inputs are in each gate's section.| Output | Holds ||--------|-------|| `coverage`, `doc-drift`, `security`, `health`, `risk` | each gate's exit code; empty when not run |+| `verdict` | `fail` when any gate failed or could not evaluate, `warn` when any passed with warnings, else `pass`; a gate that exits 0 without leaving a result (an older Repowise) counts as `warn` || `sarif-dir` | the SARIF directory, when `upload-sarif` is on and a gate wrote findings || `impacted-tests` | runner arguments for the selected tests, or `:all` || `run-all-tests` | `false` only when that subset is safe alone; `true` otherwise, also when selection could not run |+**Summary comment.** The job summary ends with a table of every gate and its+result. With `comment: true` the same table, plus each gate's findings, goes+into one pull-request comment that later runs edit rather than repeat; the job+needs `pull-requests: write`. Each working directory keeps its own comment.+Each finding carries a hidden+`repowise-fingerprint:v1` marker with its line-free id, so the comment counts+what a push resolved.+**Without the action**, run each gate as a step after `pip install repowise`,with `--format github` (commands as in [Other CI systems](#other-ci-systems)).On a pull request the gates read `GITHUB_BASE_REF` themselves; a `push`diff --git a/packages/cli/src/repowise/cli/ci.py b/packages/cli/src/repowise/cli/ci.pyindex e26cce637..078f4254b 100644--- a/packages/cli/src/repowise/cli/ci.py+++ b/packages/cli/src/repowise/cli/ci.py@@ -217,3 +217,29 @@ def append_step_summary(markdown: str, *, env: Mapping[str, str] | None = None)except OSError:return Falsereturn True+++#: Set by the GitHub Action: a directory where each gate run in ``github``+#: format leaves its row of the combined summary (``repowise ci-summary``).+GATE_SUMMARY_DIR_ENV = "REPOWISE_GATE_SUMMARY_DIR"+++def write_gate_summary(summary: Any, *, env: Mapping[str, str] | None = None) -> bool:+ """Write *summary* (a ``GateSummary``) to ``$REPOWISE_GATE_SUMMARY_DIR/<gate>.json``.++ ``False`` when the variable is unset or the file cannot be written; the+ combined summary then reads the gate as not evaluated, never as passed.+ """+ import json++ target = (os.environ if env is None else env).get(GATE_SUMMARY_DIR_ENV)+ if not target:+ return False+ try:+ Path(target).mkdir(parents=True, exist_ok=True)+ Path(target, f"{summary.gate}.json").write_text(+ json.dumps(summary.to_dict(), ensure_ascii=False), encoding="utf-8"+ )+ except OSError:+ return False+ return Truediff --git a/packages/cli/src/repowise/cli/commands/ci_summary_cmd.py b/packages/cli/src/repowise/cli/commands/ci_summary_cmd.pynew file mode 100644index 000000000..a8afbf1e7--- /dev/null+++ b/packages/cli/src/repowise/cli/commands/ci_summary_cmd.py@@ -0,0 +1,95 @@+"""``repowise ci-summary``: one summary over the gates a CI job ran.++The GitHub Action runs it after the gates. Each gate run in ``github`` format+leaves its row in ``$REPOWISE_GATE_SUMMARY_DIR``; this reads the rows back,+reconciles each with the gate's exit code, appends the verdict table to the+job summary, writes the sticky pull-request comment and prints the combined+verdict (``pass``, ``warn`` or ``fail``). Rendering is+:mod:`repowise.core.ci.summary`.+"""++from __future__ import annotations++import json+from pathlib import Path++import click++from repowise.cli.ci import append_step_summary+++def _gate_exit(value: str) -> tuple[str, int]:+ name, _, code = value.partition("=")+ if not name or not code.isdigit():+ raise click.UsageError(f"--gate expects NAME=EXIT_CODE, got {value!r}")+ return name, int(code)+++def _read(directory: Path, gate: str):+ """The row *gate* left, or ``None`` when it left none or an unreadable one."""+ from repowise.core.ci.summary import GateSummary++ try:+ doc = json.loads(Path(directory, f"{gate}.json").read_text(encoding="utf-8"))+ summary = GateSummary.from_dict(doc)+ except (OSError, ValueError, KeyError, TypeError):+ return None+ return summary if summary.gate == gate else None++[email protected]("ci-summary")[email protected]("summary_dir", type=click.Path(file_okay=False, path_type=Path))+ "--gate",+ "gates",+ multiple=True,+ required=True,+ metavar="NAME=EXIT_CODE",+ help="A gate that ran and its exit code, in the order to list them.",+)+ "--previous",+ type=click.Path(dir_okay=False, path_type=Path),+ default=None,+ help="The comment this run replaces; findings it listed that are gone count as resolved.",+)+ "--comment-file",+ type=click.Path(dir_okay=False, path_type=Path),+ default=None,+ help="Write the pull-request comment here.",+)+ "--comment-key",+ default="",+ help="Tells this comment apart from another run's on the same pull request "+ "(the Action passes its working directory).",+)+def ci_summary_command(+ summary_dir: Path,+ gates: tuple[str, ...],+ previous: Path | None,+ comment_file: Path | None,+ comment_key: str,+) -> None:+ """Combine the gates' results: job-summary table, PR comment, verdict on stdout."""+ from repowise.core.ci.summary import (+ combined_verdict,+ render_comment,+ render_job_summary,+ with_exit_code,+ )++ ran = [_gate_exit(g) for g in gates]+ rows = [with_exit_code(_read(summary_dir, name), name, code) for name, code in ran]+ append_step_summary(render_job_summary(rows))+ if comment_file is not None:+ earlier = None+ if previous is not None:+ try:+ earlier = previous.read_text(encoding="utf-8")+ except OSError:+ earlier = None+ body = render_comment(rows, previous=earlier, key=comment_key)+ comment_file.write_text(body, encoding="utf-8")+ click.echo(combined_verdict(rows))diff --git a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.pyindex b40d1c7eb..1ecd547d8 100644--- a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py+++ b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py@@ -45,6 +45,7 @@ from repowise.cli.ci import (change_lines,ci_notices,repo_root,+ write_gate_summary,)from repowise.cli.helpers import console, repo_index_session, run_asyncfrom repowise.cli.output import emit_json, format_option@@ -593,7 +594,11 @@ def _coverage_config(def _emit(pc, fmt: str) -> None:- from repowise.core.analysis.patch_coverage import github_annotations, render_markdown+ from repowise.core.analysis.patch_coverage import (+ gate_summary,+ github_annotations,+ render_markdown,+ )if fmt == "json":emit_json(pc.to_dict())@@ -603,6 +608,7 @@ def _emit(pc, fmt: str) -> None:for line in github_annotations(pc):click.echo(line)append_step_summary(render_markdown(pc))+ write_gate_summary(gate_summary(pc))_print_summary(pc)else:_print_summary(pc)diff --git a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.pyindex 22b098925..c0c5577ef 100644--- a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py+++ b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py@@ -23,6 +23,7 @@ from repowise.cli.ci import (ci_notices,ci_revspec,report_baseline_growth,+ write_gate_summary,)from repowise.cli.helpers import console, repo_index_session, resolve_command_target, run_asyncfrom repowise.cli.output import emit_json, emit_refusal, format_option@@ -235,6 +236,8 @@ def _emit(for line in render.render_github_annotations(findings, gate=gate):click.echo(line)append_step_summary(markdown)+ if gate is not None:+ write_gate_summary(render.gate_summary(gate))else:_render(payload)if gate is not None:diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/check.py b/packages/cli/src/repowise/cli/commands/health_cmd/check.pyindex 17d785d01..a78ca254c 100644--- a/packages/cli/src/repowise/cli/commands/health_cmd/check.py+++ b/packages/cli/src/repowise/cli/commands/health_cmd/check.py@@ -24,6 +24,7 @@ from repowise.cli.ci import (cannot_evaluate,ci_revspec,repo_root,+ write_gate_summary,)from repowise.cli.helpers import console, silence_logs_for_machine_output_until_closefrom repowise.cli.output import emit_json, format_option@@ -241,11 +242,12 @@ def _emit_markdown(v: _Verdict) -> None:def _emit_github(v: _Verdict) -> None:- from repowise.core.analysis.health_gate import github_annotations+ from repowise.core.analysis.health_gate import gate_summary, github_annotationsfor line in github_annotations(v.result):click.echo(line)append_step_summary(_markdown(v))+ write_gate_summary(gate_summary(v.result))_COLOUR = {"error": "red", "warning": "yellow", "note": "dim"}diff --git a/packages/cli/src/repowise/cli/commands/risk_cmd/change_render.py b/packages/cli/src/repowise/cli/commands/risk_cmd/change_render.pyindex a26734580..8cc9094c3 100644--- a/packages/cli/src/repowise/cli/commands/risk_cmd/change_render.py+++ b/packages/cli/src/repowise/cli/commands/risk_cmd/change_render.py@@ -9,7 +9,7 @@ import clickfrom rich.markup import escapefrom rich.table import Table-from repowise.cli.ci import append_step_summary+from repowise.cli.ci import append_step_summary, write_gate_summaryfrom repowise.cli.helpers import console, repo_index_session, run_asyncfrom repowise.core.analysis.change_risk import ChangeRiskResult, change_risk_payloadfrom repowise.core.analysis.change_risk.render import LIMITS, fix_history_text, size_text@@ -207,4 +207,5 @@ def _emit_machine(subject: _Subject, result: ChangeRiskResult) -> None:for line in render.github_annotations(result, fail_above):click.echo(line)append_step_summary(render.render_markdown(result, fail_above))+ write_gate_summary(render.gate_summary(result, fail_above))console.print(render.headline(result, fail_above, markdown=False), markup=False)diff --git a/packages/cli/src/repowise/cli/commands/security_cmd.py b/packages/cli/src/repowise/cli/commands/security_cmd.pyindex 8bcb26cf2..5e2ae1169 100644--- a/packages/cli/src/repowise/cli/commands/security_cmd.py+++ b/packages/cli/src/repowise/cli/commands/security_cmd.py@@ -34,6 +34,7 @@ from repowise.cli.ci import (ci_revspec,repo_root,report_baseline_growth,+ write_gate_summary,)from repowise.cli.helpers import (console,@@ -540,11 +541,12 @@ def _emit_markdown(v: _Verdict) -> None:def _emit_github(v: _Verdict) -> None:- from repowise.core.analysis.security_gate import github_annotations+ from repowise.core.analysis.security_gate import gate_summary, github_annotationsfor line in github_annotations(v.scan.findings, v.gate):click.echo(line)append_step_summary(_markdown(v))+ write_gate_summary(gate_summary(v.scan.findings, v.gate))_SEVERITY_COLOUR = {"high": "red", "med": "yellow", "low": "dim"}diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.pyindex 8e5af37b0..a6dd368f5 100644--- a/packages/cli/src/repowise/cli/main.py+++ b/packages/cli/src/repowise/cli/main.py@@ -76,6 +76,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (("changes", "changes_cmd:changes_group"),("suspects", "suspects_cmd:suspects_command"),("check", "check_cmd:check_command"),+ ("ci-summary", "ci_summary_cmd:ci_summary_command"),("events", "events_cmd:events_command"),("report", "report_cmd:report_group"),("impacted-tests", "impacted_tests_cmd:impacted_tests_command"),diff --git a/packages/core/src/repowise/core/analysis/change_risk/render.py b/packages/core/src/repowise/core/analysis/change_risk/render.pyindex e3a76d3a3..abbca0fb4 100644--- a/packages/core/src/repowise/core/analysis/change_risk/render.py+++ b/packages/core/src/repowise/core/analysis/change_risk/render.py@@ -16,6 +16,7 @@ from typing import Literalfrom ...ci import githubfrom ...ci.markdown import ROW_LIMIT, cell, more_line, plural+from ...ci.summary import FAIL, PASS, GateSummaryfrom .service import _MIN_BASELINE, ChangeRiskResultPercentileGate = Literal["pass", "fail", "no_data", "not_set"]@@ -168,6 +169,12 @@ def render_markdown(result: ChangeRiskResult, threshold: float | None = None) ->return "\n".join(out) + "\n"+def gate_summary(result: ChangeRiskResult, threshold: float | None = None) -> GateSummary:+ """The gate's row in the combined CI summary: the rank, with no findings."""+ verdict = FAIL if percentile_gate(result, threshold) == "fail" else PASS+ return GateSummary("risk", verdict, headline(result, threshold, markdown=False))++def github_annotations(result: ChangeRiskResult, threshold: float | None = None) -> list[str]:"""An ``::error::`` when the gate fails, else a ``::notice::`` naming the rank."""text = headline(result, threshold, markdown=False)diff --git a/packages/core/src/repowise/core/analysis/doc_drift/render.py b/packages/core/src/repowise/core/analysis/doc_drift/render.pyindex 2ccbd1d8c..a5c0c3f59 100644--- a/packages/core/src/repowise/core/analysis/doc_drift/render.py+++ b/packages/core/src/repowise/core/analysis/doc_drift/render.py@@ -25,6 +25,7 @@ from repowise.core.ci.markdown import (more_line,plural,)+from repowise.core.ci.summary import FAIL, PASS, GateSummary, SummaryFindingfrom .constants import DETECTION_BASIS, HIGH_CONFIDENCE_THRESHOLDfrom .gate import GateResult@@ -310,6 +311,29 @@ def render_sarif(return sarif.run(SARIF_TOOL_NAME, tool_version, _sarif_rules(), results)+# ---------------------------------------------------------------------------+# Combined CI summary+# ---------------------------------------------------------------------------+++def gate_summary(gate: GateResult) -> GateSummary:+ """The gate's row in the combined CI summary: its failing findings.++ Findings below the threshold are left out: the check reads the whole tree,+ so they are not this change's.+ """+ rows = tuple(+ SummaryFinding(+ "error", str(f["file_path"]), int(f["line_number"]), _message(f), fingerprint_of(f)+ )+ for f in _order(gate.failing)+ )+ if rows:+ headline = f"{plural(len(rows), 'finding')} at confidence {gate.fail_on:.2f} or above."+ return GateSummary("doc-drift", FAIL, headline, rows)+ return GateSummary("doc-drift", PASS, "No finding fails the gate.")++# ---------------------------------------------------------------------------# GitLab Code Quality# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/analysis/health_gate.py b/packages/core/src/repowise/core/analysis/health_gate.pyindex dad243ea9..251143d4b 100644--- a/packages/core/src/repowise/core/analysis/health_gate.py+++ b/packages/core/src/repowise/core/analysis/health_gate.py@@ -21,6 +21,7 @@ from typing import Anyfrom repowise.core.ci import github, gitlab, sariffrom repowise.core.ci.markdown import ROW_LIMIT, cell, details, more_line, plural+from repowise.core.ci.summary import GateSummary, SummaryFindingfrom ..test_paths import is_test_related_pathfrom .change_health.identity import severity_rank@@ -373,6 +374,21 @@ def github_annotations(result: GateResult) -> list[str]:return github.cap_annotations(out, noun="health findings")+def gate_summary(result: GateResult) -> GateSummary:+ """The gate's row in the combined CI summary: errors and warnings, notes left out."""+ 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]+ findings = tuple(+ SummaryFinding(f.level, f.path, f.line, f.message, f.fingerprint)+ for f in [*errors, *warnings]+ )+ return GateSummary(_SOURCE, result.verdict, headline, findings)++def render_sarif(result: GateResult, *, tool_version: str) -> dict:"""One SARIF 2.1.0 run over the errors and warnings; notes stay out of code scanning."""shown = [*result.at(ERROR), *result.at(WARNING)]diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.pyindex 7d3d57969..c30e8f9c8 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py@@ -40,6 +40,7 @@ from .render import (cause_words,fmt_pct,format_ranges,+ gate_summary,github_annotations,headline,indirect_row,@@ -105,6 +106,7 @@ __all__ = ["first_hint","fmt_pct","format_ranges",+ "gate_summary","github_annotations","headline","hint_phrase",diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/render.py b/packages/core/src/repowise/core/analysis/patch_coverage/render.pyindex c08b973ed..479d51727 100644--- a/packages/core/src/repowise/core/analysis/patch_coverage/render.py+++ b/packages/core/src/repowise/core/analysis/patch_coverage/render.py@@ -15,11 +15,13 @@ come from :mod:`repowise.core.ci`, shared with every other CI gate.from __future__ import annotations+import hashlibimport mathfrom collections.abc import Callable, Sequencefrom ...ci import githubfrom ...ci.markdown import ROW_LIMIT, cell, details, more_line, plural+from ...ci.summary import FAIL, PASS, GateSummary, SummaryFindingfrom .compute import UNMEASURED, FilePatchCoverage, PatchCoverage, PathGateResultfrom .delta import IndirectCause, IndirectChange, ProjectDeltafrom .hints import RANGE_LIMIT, TestHint, first_hint, hint_phrase@@ -624,6 +626,29 @@ def _outside_annotation(c: IndirectChange) -> str:)+def gate_summary(pc: PatchCoverage) -> GateSummary:+ """The gate's row in the combined CI summary: one finding per file with uncovered+ changes, an error when the gate failed and a warning otherwise.++ A coverage gap is a file's, not a line's, so its fingerprint is the path's.+ """+ verdict = FAIL if pc.gate == "fail" else PASS+ level = "error" if verdict == FAIL else "warning"+ rows = tuple(+ SummaryFinding(+ level,+ f.file_path,+ None,+ f"{plural(f.uncovered_line_count, 'changed line')} not covered: "+ f"{format_ranges(f.uncovered_ranges, RANGE_LIMIT)}.",+ hashlib.sha256(f"repowise.coverage.gap.v1\x1f{f.file_path}".encode()).hexdigest()[:32],+ )+ for f in attention_rows(pc)+ if f.status == "measured" and f.uncovered_line_count+ )+ return GateSummary("coverage", verdict, headline(pc, markdown=False), rows)++def format_ranges(ranges: Sequence[tuple[int, int]], limit: int | None = None) -> str:"""``((1, 3), (7, 7))`` -> ``"1-3, 7"``, with ``+N more`` past *limit*."""shown = ranges if limit is None else ranges[:limit]diff --git a/packages/core/src/repowise/core/analysis/security_gate.py b/packages/core/src/repowise/core/analysis/security_gate.pyindex 65921df99..1c0a80d02 100644--- a/packages/core/src/repowise/core/analysis/security_gate.py+++ b/packages/core/src/repowise/core/analysis/security_gate.py@@ -38,6 +38,7 @@ from typing import Anyfrom repowise.core.ci import baseline as ci_baselinefrom repowise.core.ci import github, gitlab, sariffrom repowise.core.ci.markdown import ROW_LIMIT, cell, details, more_line, plural+from repowise.core.ci.summary import FAIL, PASS, WARN, GateSummary, SummaryFindingfrom repowise.core.support_paths import DOC_EXTENSIONSfrom .change_risk.features import GIT_TIMEOUT_SECONDS, _git, revspec_head, split_revspec@@ -923,6 +924,37 @@ def github_annotations(findings: Sequence[Mapping[str, Any]], gate: GateResult)return github.cap_annotations(errors + warnings, noun="security findings")+def gate_summary(findings: Sequence[Mapping[str, Any]], gate: GateResult) -> GateSummary:+ """The gate's row in the combined CI summary, leveled as :func:`github_annotations` is."""+ failing = {f["fingerprint"] for f in gate.failing}+ accepted = {f["fingerprint"] for f in gate.baselined}+ rows = tuple(+ SummaryFinding(+ "error" if f["fingerprint"] in failing else "warning",+ str(f["file_path"]),+ None if f["commit"] else int(f["line_number"]),+ _message(f),+ str(f["fingerprint"]),+ )+ for f in _order(findings)+ if f["fingerprint"] not in accepted+ )+ below = sum(r.level == "warning" for r in rows)+ if not gate.passed:+ at = len(rows) - below+ headline = (+ f"{plural(at, 'new finding')} at {gate.fail_on} or above."+ if at+ else "Failed; see the job log for why."+ )+ verdict = FAIL+ elif below:+ verdict, headline = WARN, f"{plural(below, 'new finding')} below {gate.fail_on}."+ else:+ verdict, headline = PASS, "No new finding."+ return GateSummary("security", verdict, headline, rows)++def _rule_id(kind: str) -> str:"""The SARIF rule id / Code Quality check name: ``custom:<name>`` reads ``custom/<name>``."""return kind.replace(":", "/", 1)diff --git a/packages/core/src/repowise/core/ci/summary.py b/packages/core/src/repowise/core/ci/summary.pynew file mode 100644index 000000000..205404439--- /dev/null+++ b/packages/core/src/repowise/core/ci/summary.py@@ -0,0 +1,256 @@+"""One summary over every gate a CI run judged: a sticky pull-request comment,+a job-summary table and a combined verdict.++Each gate maps its own result to a :class:`GateSummary` (a ``gate_summary``+function beside it); this module renders any list of them. Everything is a+pure function over in-memory values, so a caller that builds gate results+without a checkout renders the same comment the Action posts.++Every finding line in the comment ends in a hidden marker naming the gate and+the finding's line-free fingerprint, so a later run, or any other reader of+the comment, can tell which findings are gone (:func:`fingerprints_in`).+"""++from __future__ import annotations++import re+from collections.abc import Iterable, Mapping, Sequence+from dataclasses import dataclass+from typing import Any++from .markdown import ROW_LIMIT, cell, code, more_line, plural++PASS, WARN, FAIL = "pass", "warn", "fail"+#: The gate could not run (exit code 2); the combined verdict counts it as a fail.+ERROR = "error"+#: The gate exited 0 but left no result to read; the combined verdict counts it as a warning.+NO_RESULT = "no_result"+VERDICTS = (PASS, WARN, FAIL, ERROR, NO_RESULT)+#: Verdicts of a gate that judged nothing this run.+_NOT_JUDGED = frozenset({ERROR, NO_RESULT})++#: Finding levels, as SARIF names them.+LEVELS = ("error", "warning", "note")++#: Opens the sticky comment; a run finds its earlier comment by it.+COMMENT_MARKER = "<!-- repowise-ci-summary -->"+#: Kept out of a comment key, so a shell can derive the same key with ``tr``.+_KEY_UNSAFE = re.compile(r"[^A-Za-z0-9_./]")+#: Longest message or headline shown. With :data:`ROW_LIMIT` rows per gate this+#: keeps a comment far under GitHub's 65,536 characters.+MESSAGE_LIMIT = 300+_FINGERPRINT_TAG = "repowise-fingerprint:v1:"+_FINGERPRINT_RE = re.compile(r"<!-- " + re.escape(_FINGERPRINT_TAG) + r"([A-Za-z0-9_.:-]+) -->")+#: Kept out of a marker: anything that could end the HTML comment early.+_UNSAFE = re.compile(r"[^A-Za-z0-9_.:-]")++_TITLES = {+ "coverage": "Coverage",+ "doc-drift": "Doc drift",+ "security": "Security",+ "health": "Health",+ "risk": "Change risk",+}+_VERDICT_WORDS = {+ PASS: "Pass",+ WARN: "Warn",+ FAIL: "Fail",+ ERROR: "Could not evaluate",+ NO_RESULT: "Could not evaluate",+}+++@dataclass(frozen=True)+class SummaryFinding:+ """One finding as the summary lists it."""++ level: str+ path: str+ line: int | None+ message: str+ #: Line-free, as the gate's SARIF ``partialFingerprints`` carries it.+ fingerprint: str++ def to_dict(self) -> dict[str, Any]:+ return {+ "level": self.level,+ "file_path": self.path,+ "line_number": self.line,+ "message": self.message,+ "fingerprint": self.fingerprint,+ }++ @classmethod+ def from_dict(cls, d: Mapping[str, Any]) -> SummaryFinding:+ line = d.get("line_number")+ return cls(+ str(d["level"]),+ str(d["file_path"]),+ int(line) if line else None,+ str(d["message"]),+ str(d["fingerprint"]),+ )+++@dataclass(frozen=True)+class GateSummary:+ """One gate's verdict, a one-line headline, and the findings worth listing."""++ gate: str+ verdict: str+ headline: str+ findings: tuple[SummaryFinding, ...] = ()++ def __post_init__(self) -> None:+ if self.verdict not in VERDICTS:+ raise ValueError(f"unknown gate verdict {self.verdict!r}")++ def to_dict(self) -> dict[str, Any]:+ return {+ "gate": self.gate,+ "verdict": self.verdict,+ "headline": self.headline,+ "findings": [f.to_dict() for f in self.findings],+ }++ @classmethod+ def from_dict(cls, d: Mapping[str, Any]) -> GateSummary:+ return cls(+ str(d["gate"]),+ str(d["verdict"]),+ str(d.get("headline") or ""),+ tuple(SummaryFinding.from_dict(f) for f in d.get("findings") or ()),+ )+++def with_exit_code(summary: GateSummary | None, gate: str, exit_code: int) -> GateSummary:+ """*summary* reconciled with the gate's exit code, which decides fail and error.++ A gate that exits 1 failed even when its own result reads as a pass (a check+ layered on top, such as a grown baseline); exit 2, or no summary at all,+ means it could not be evaluated. A gate that exits 0 with no summary (an+ older release) reads as not evaluated too, but warns rather than fails.+ """+ if exit_code == 0 and summary is None:+ return GateSummary(gate, NO_RESULT, "Exited 0 but left no result to read.")+ if exit_code not in (0, 1) or summary is None:+ headline = summary.headline if summary else "See the job log for why."+ findings = summary.findings if summary else ()+ return GateSummary(gate, ERROR, headline, findings)+ if exit_code == 1 and summary.verdict != FAIL:+ headline = f"{summary.headline} The gate exited 1; see the job log for why.".lstrip()+ return GateSummary(gate, FAIL, headline, summary.findings)+ if exit_code == 0 and summary.verdict in (FAIL, *_NOT_JUDGED):+ return GateSummary(gate, WARN, summary.headline, summary.findings)+ return summary+++def combined_verdict(gates: Iterable[GateSummary]) -> str:+ """``fail`` when any gate failed or could not run, else ``warn`` on any warning+ or a gate that left no result, else ``pass``."""+ verdicts = {g.verdict for g in gates}+ if verdicts & {FAIL, ERROR}:+ return FAIL+ return WARN if verdicts & {WARN, NO_RESULT} else PASS+++def comment_marker(key: str = "") -> str:+ """The marker opening the comment; *key* (a working directory) keeps two+ uses of the Action on one pull request apart."""+ key = _KEY_UNSAFE.sub("_", key)+ return f"<!-- repowise-ci-summary:{key} -->" if key else COMMENT_MARKER+++def fingerprint_marker(gate: str, fingerprint: str) -> str:+ """The hidden ``<!-- repowise-fingerprint:v1:<gate>:<id> -->`` marker for one finding."""+ return f"<!-- {_FINGERPRINT_TAG}{marker_key(gate, fingerprint)} -->"+++def marker_key(gate: str, fingerprint: str) -> str:+ """``<gate>:<id>``, the key :func:`fingerprints_in` returns, safe inside a marker."""+ return f"{_safe(gate)}:{_safe(fingerprint)}"+++def _safe(text: str) -> str:+ return re.sub(r"-{2,}", "-", _UNSAFE.sub("_", text))+++def fingerprints_in(body: str) -> frozenset[str]:+ """The ``<gate>:<id>`` keys an earlier comment's finding markers carry."""+ return frozenset(_FINGERPRINT_RE.findall(body or ""))+++def render_comment(+ gates: Sequence[GateSummary], *, previous: str | None = None, key: str = ""+) -> str:+ """The sticky comment: its marker (:func:`comment_marker`), the verdict+ table, then each gate's findings.++ Each gate lists its first :data:`~.markdown.ROW_LIMIT` findings, errors+ first. With *previous* (the comment this replaces), findings it listed+ that a gate judged this run no longer reports are counted as resolved; a+ gate that judged nothing resolves nothing.+ """+ lines = [comment_marker(key), *_table(gates)]+ for g in gates:+ if g.findings:+ lines += ["", f"#### {cell(_title(g.gate))}", *_finding_lines(g)]+ if previous is not None:+ judged = {_safe(g.gate) for g in gates if g.verdict not in _NOT_JUDGED}+ current = {marker_key(g.gate, f.fingerprint) for g in gates for f in g.findings}+ earlier = {k for k in fingerprints_in(previous) if k.split(":", 1)[0] in judged}+ resolved = len(earlier - current)+ if resolved:+ lines += ["", f"Resolved since the last run: {plural(resolved, 'finding')}."]+ return "\n".join(lines) + "\n"+++def render_job_summary(gates: Sequence[GateSummary]) -> str:+ """The verdict table alone; each gate writes its own details to the job summary."""+ return "\n".join(_table(gates)) + "\n"+++def _table(gates: Sequence[GateSummary]) -> list[str]:+ verdict = combined_verdict(gates)+ lines = [f"### Repowise gates: {_VERDICT_WORDS[verdict].lower()}", ""]+ if not gates:+ return [*lines, "No gate ran."]+ lines += ["| Gate | Result | Summary |", "| --- | --- | --- |"]+ lines += [+ f"| {cell(_title(g.gate))} | {_VERDICT_WORDS[g.verdict]} | {_text(g.headline)} |"+ for g in gates+ ]+ return lines+++_LEVEL_ORDER = {level: i for i, level in enumerate(LEVELS)}+++def _finding_lines(g: GateSummary) -> list[str]:+ ordered = sorted(+ g.findings, key=lambda f: (_LEVEL_ORDER.get(f.level, len(LEVELS)), f.path, f.line or 0)+ )+ out = [+ f"- {f.level} {code(f'{f.path}:{f.line}' if f.line else f.path)} {_text(f.message)} "+ f"{fingerprint_marker(g.gate, f.fingerprint)}"+ for f in ordered[:ROW_LIMIT]+ ]+ if rest := more_line(len(ordered) - ROW_LIMIT, "findings"):+ out.append(f"- {rest[0].upper()}{rest[1:]} See the job summary.")+ return out+++def _text(text: str) -> str:+ """*text* from the change itself made inert: one line, capped, escaped, no mentions.++ A zero-width space after ``@`` stops a team or user mention, and after ``[``+ a link or an image.+ """+ text = " ".join(text.split())+ if len(text) > MESSAGE_LIMIT:+ text = text[: MESSAGE_LIMIT - 1].rstrip() + "\u2026"+ return cell(text).replace("@", "@\u200b").replace("[", "[\u200b")+++def _title(gate: str) -> str:+ return _TITLES.get(gate, gate)diff --git a/packages/core/src/repowise/core/policy/report.py b/packages/core/src/repowise/core/policy/report.pyindex 11dea992f..9a60b381c 100644--- a/packages/core/src/repowise/core/policy/report.py+++ b/packages/core/src/repowise/core/policy/report.py@@ -64,7 +64,8 @@ def render_sarif(if res.evidence:properties["evidence"] = res.evidencefor path, line, own in res.locations or [(anchor, None, None)]:- ident = own or f"{path}:{line or 0}"+ # Line-free like every gate's own fingerprint, so an edit above keeps it.+ ident = own or pathout.append(sarif.result(_rule_id(res.rule.name),diff --git a/tests/unit/cli/test_coverage_check_cmd.py b/tests/unit/cli/test_coverage_check_cmd.pyindex eec4637f3..0766bdb5a 100644--- a/tests/unit/cli/test_coverage_check_cmd.py+++ b/tests/unit/cli/test_coverage_check_cmd.py@@ -96,7 +96,8 @@ def test_threshold_defaults_to_repo_config(repo) -> None:def test_github_format_writes_annotations_and_step_summary(repo, tmp_path_factory) -> None:report = _lcov(repo, {2: 1, 3: 0})- summary = tmp_path_factory.mktemp("gh") / "summary.md"+ out = tmp_path_factory.mktemp("gh")+ summary = out / "summary.md"result = _run(repo,@@ -105,12 +106,16 @@ def test_github_format_writes_annotations_and_step_summary(repo, tmp_path_factorreport,"--format","github",- env={"GITHUB_STEP_SUMMARY": str(summary)},+ env={"GITHUB_STEP_SUMMARY": str(summary), "REPOWISE_GATE_SUMMARY_DIR": str(out)},)assert result.exit_code == 0, result.outputassert "::warning file=src/app.py,line=3,endLine=3" in result.stdoutassert summary.read_text(encoding="utf-8").startswith("**Patch coverage 50.0%**")+ # The row the combined CI summary reads: one file with an uncovered changed line.+ row = json.loads((out / "coverage.json").read_text(encoding="utf-8"))+ assert (row["gate"], row["verdict"]) == ("coverage", "pass")+ assert [f["file_path"] for f in row["findings"]] == ["src/app.py"]def test_default_base_comes_from_ci_variables(repo) -> None:diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.pyindex 92cb4b338..f08e0b74e 100644--- a/tests/unit/cli/test_lazy_commands.py+++ b/tests/unit/cli/test_lazy_commands.py@@ -33,7 +33,7 @@ from repowise.core.registry import CLIRegistry, LazyCommand#: command is meant to require editing it._EXPECTED_NAMES = frozenset({- "agents", "ask", "attribution", "augment", "changes", "check", "components", "config", "context", "corrections",+ "agents", "ask", "attribution", "augment", "changes", "check", "ci-summary", "components", "config", "context", "corrections","costs", "coverage","dead-code", "decision", "delete", "distill", "doc-drift", "doctor","events", "expand",diff --git a/tests/unit/test_ci_action.py b/tests/unit/test_ci_action.pyindex d5e24bd19..0640fc107 100644--- a/tests/unit/test_ci_action.py+++ b/tests/unit/test_ci_action.py@@ -23,6 +23,7 @@ import yamlROOT = Path(__file__).resolve().parents[2]ACTION = ROOT / "action.yml"RUNNER = ROOT / "ci" / "github" / "run-gates.sh"+SUMMARY = ROOT / "ci" / "github" / "summary.sh"GUIDE = ROOT / "docs" / "start" / "CI.md"GITLAB = ROOT / "ci" / "gitlab" / "repowise.gitlab-ci.yml"@@ -43,11 +44,29 @@ def test_every_variable_the_runner_reads_is_passed_by_the_action() -> None:script = RUNNER.read_text(encoding="utf-8")read = set(re.findall(r"\$\{?([A-Z][A-Z_]+)", script))runner_env = {"GITHUB_OUTPUT", "GITHUB_BASE_REF"}- for_python = {"PYTHONUTF8"}+ for_python = {"PYTHONUTF8", "REPOWISE_GATE_SUMMARY_DIR"}assert read - runner_env <= passedassert passed - for_python <= read+def test_the_summary_step_reads_what_the_gates_step_writes() -> None:+ steps = {s.get("id"): s for s in _action()["runs"]["steps"]}+ gates, summary = steps["gates"], steps["summary"]+ assert summary["env"]["SUMMARY_DIR"] == gates["env"]["REPOWISE_GATE_SUMMARY_DIR"]+ # Every gate the runner accepts hands its exit code on.+ accepted = re.search(r"^\s+(coverage \|[^)]*)\)", RUNNER.read_text(encoding="utf-8"), re.M)+ names = {n.strip() for n in accepted.group(1).split("|")}+ pairs = re.findall(r"(\S+)=\$\{\{ steps\.gates\.outputs\.(\S+) \}\}", summary["env"]["EXIT_CODES"])+ assert all(name == output for name, output in pairs)+ assert {name for name, _ in pairs} == names+ read = set(re.findall(r"\$\{?([A-Z][A-Z_]+)", SUMMARY.read_text(encoding="utf-8")))+ from_github = {"GITHUB_OUTPUT", "GITHUB_EVENT_PATH", "GITHUB_REPOSITORY"}+ for_tools = {"PYTHONUTF8", "GH_TOKEN"}+ assert read - from_github <= set(summary["env"])+ assert set(summary["env"]) - for_tools <= read+ assert _action()["outputs"]["verdict"]["value"] == "${{ steps.summary.outputs.verdict }}"++def test_the_gitlab_template_parses() -> None:jobs = yaml.safe_load(GITLAB.read_text(encoding="utf-8"))assert {@@ -590,3 +609,161 @@ def test_the_gitlab_job_runs_everything_when_the_cache_cannot_update(assert code == 0assert report == "RUN_ALL_TESTS=true\n" and written == ":all\n"assert (tmp_path / "log").read_text(encoding="utf-8").strip() == "update --index-only"+++def fake_tools(tmp_path: Path) -> Path:+ """``repowise`` and ``gh`` stand-ins that log their arguments.++ ``repowise ci-summary`` prints ``$FAKE_VERDICT`` and exits ``$FAKE_SUMMARY``,+ writing a body to ``--comment-file``; ``gh`` prints ``$FAKE_GH_LOGIN`` as the+ token's login (and fails without one, as the default token does), prints+ ``$FAKE_GH_ID`` for the comment search and exits ``$FAKE_GH`` for a post.+ """+ bin_dir = tmp_path / "tools"+ bin_dir.mkdir()+ scripts = {+ "repowise": (+ 'echo "$*" >> "$FAKE_LOG"\n'+ 'prev=""\n'+ 'for a in "$@"; do [ "$prev" = --comment-file ] && echo body > "$a"; prev=$a; done\n'+ 'echo "${FAKE_VERDICT-pass}"\n'+ 'exit "${FAKE_SUMMARY:-0}"\n'+ ),+ "gh": (+ 'echo "gh $*" >> "$FAKE_LOG"\n'+ 'case "$*" in\n'+ ' "api user --jq .login") [ -n "${FAKE_GH_LOGIN:-}" ] || exit 1\n'+ ' echo "$FAKE_GH_LOGIN" ;;\n'+ ' *"--jq .body"*) echo "<!-- earlier -->" ;;\n'+ ' *--jq*) echo "${FAKE_GH_ID:-}" ;;\n'+ ' *) exit "${FAKE_GH:-0}" ;;\n'+ "esac\n"+ ),+ }+ for name, body in scripts.items():+ tool = bin_dir / name+ tool.write_text("#!/usr/bin/env bash\n" + body, encoding="utf-8", newline="\n")+ tool.chmod(tool.stat().st_mode | stat.S_IEXEC)+ return bin_dir+++def _summarize(tmp_path: Path, bin_dir: Path, **env: str) -> tuple[str, list[str], str]:+ """Run ``summary.sh``: ``(outputs, logged calls, stdout)``."""+ bash = _bash()+ if bash is None:+ pytest.skip("bash is not available")+ out = tmp_path / "out"+ log = tmp_path / "log"+ event = tmp_path / "event.json"+ event.write_text(env.pop("EVENT", "{}"), encoding="utf-8")+ full = {+ **os.environ,+ "PATH": os.pathsep.join([str(bin_dir), str(Path(sys.executable).parent), os.environ["PATH"]]),+ "GITHUB_OUTPUT": str(out),+ "GITHUB_EVENT_PATH": str(event),+ "GITHUB_REPOSITORY": "o/r",+ "FAKE_LOG": str(log),+ "EXIT_CODES": "coverage= doc-drift=0 security=1 health= risk=",+ "SUMMARY_DIR": str(tmp_path / "rows"),+ "WORKING_DIRECTORY": ".",+ "COMMENT": "false",+ **env,+ }+ proc = subprocess.run([bash, str(SUMMARY)], cwd=tmp_path, env=full, capture_output=True, text=True)+ assert proc.returncode == 0, proc.stderr+ calls = log.read_text(encoding="utf-8").splitlines() if log.exists() else []+ return (out.read_text(encoding="utf-8") if out.exists() else ""), calls, proc.stdout+++_PR = '{"pull_request": {"number": 7}}'+++def test_the_summary_passes_each_gate_that_ran_and_sets_the_verdict(tmp_path, fake_tools) -> None:+ (tmp_path / "rows").mkdir()+ outputs, calls, _ = _summarize(tmp_path, fake_tools, FAKE_VERDICT="fail")+ (call,) = calls+ assert call.split()[0] == "ci-summary"+ assert call.split()[2:] == ["--gate", "doc-drift=0", "--gate", "security=1"]+ assert outputs.split() == ["verdict=fail"]+ # Read once, so a second use of the action in the job starts clean.+ assert not (tmp_path / "rows").exists()+++def test_the_summary_is_skipped_when_no_gate_ran(tmp_path, fake_tools) -> None:+ outputs, calls, _ = _summarize(+ tmp_path, fake_tools, EXIT_CODES="coverage= doc-drift= security= health= risk="+ )+ assert (outputs, calls) == ("", [])+++def test_a_failed_summary_never_fails_the_job(tmp_path, fake_tools) -> None:+ outputs, _, stdout = _summarize(tmp_path, fake_tools, FAKE_SUMMARY="1", COMMENT="true", EVENT=_PR)+ assert outputs == ""+ assert "::warning::Could not combine the gate results" in stdout+++def test_no_comment_outside_a_pull_request(tmp_path, fake_tools) -> None:+ outputs, calls, stdout = _summarize(tmp_path, fake_tools, COMMENT="true")+ assert not any(c.startswith("gh ") or "--comment-file" in c for c in calls)+ assert outputs.split() == ["verdict=pass"]+ assert "::notice::This event has no pull request" in stdout+++def test_the_first_run_posts_the_comment(tmp_path, fake_tools) -> None:+ _, calls, _ = _summarize(tmp_path, fake_tools, COMMENT="true", EVENT=_PR)+ login, search, summary, post = calls+ assert login == "gh api user --jq .login"+ assert search.startswith("gh api --paginate repos/o/r/issues/7/comments --jq")+ # The default token cannot read its login; it posts as github-actions[bot].+ assert '.user.login == "github-actions[bot]"' in search+ assert 'startswith("<!-- repowise-ci-summary -->")' in search+ assert "--comment-file" in summary and "--previous" not in summary+ assert post.startswith("gh api --method POST repos/o/r/issues/7/comments -F body=@")+++def test_a_later_run_edits_the_comment_in_place(tmp_path, fake_tools) -> None:+ _, calls, _ = _summarize(tmp_path, fake_tools, COMMENT="true", EVENT=_PR, FAKE_GH_ID="42")+ _, _, previous, summary, edit = calls+ assert previous == "gh api repos/o/r/issues/comments/42 --jq .body"+ assert "--previous" in summary+ assert edit.startswith("gh api --method PATCH repos/o/r/issues/comments/42 -F body=@")+++def test_a_personal_token_finds_its_own_comment(tmp_path, fake_tools) -> None:+ _, calls, _ = _summarize(+ tmp_path, fake_tools, COMMENT="true", EVENT=_PR, FAKE_GH_LOGIN="octo-cat"+ )+ assert '.user.login == "octo-cat"' in calls[1]+++def test_an_unexpected_login_falls_back_to_the_actions_bot(tmp_path, fake_tools) -> None:+ _, calls, _ = _summarize(+ tmp_path, fake_tools, COMMENT="true", EVENT=_PR, FAKE_GH_LOGIN='x" or true'+ )+ assert '.user.login == "github-actions[bot]"' in calls[1]+++def test_a_comment_that_cannot_be_edited_is_replaced(tmp_path, fake_tools) -> None:+ _, calls, _ = _summarize(+ tmp_path, fake_tools, COMMENT="true", EVENT=_PR, FAKE_GH_ID="42", FAKE_GH="1"+ )+ assert calls[-2].startswith("gh api --method PATCH repos/o/r/issues/comments/42")+ assert calls[-1].startswith("gh api --method POST repos/o/r/issues/7/comments")+++def test_each_working_directory_keeps_its_own_comment(tmp_path, fake_tools) -> None:+ from repowise.core.ci.summary import comment_marker++ _, calls, _ = _summarize(+ tmp_path, fake_tools, COMMENT="true", EVENT=_PR, WORKING_DIRECTORY="apps/my web"+ )+ _, search, summary, _ = calls+ assert f'startswith("{comment_marker("apps/my web")}")' in search+ assert summary.endswith("--comment-key apps/my_web") or "--comment-key apps/my_web " in summary+++def test_a_read_only_token_warns_and_keeps_the_verdict(tmp_path, fake_tools) -> None:+ outputs, _, stdout = _summarize(tmp_path, fake_tools, COMMENT="true", EVENT=_PR, FAKE_GH="1")+ assert outputs.split() == ["verdict=pass"]+ assert "::warning::Could not post the summary comment" in stdoutdiff --git a/tests/unit/test_ci_summary.py b/tests/unit/test_ci_summary.pynew file mode 100644index 000000000..9fe16fc9b--- /dev/null+++ b/tests/unit/test_ci_summary.py@@ -0,0 +1,295 @@+"""The combined CI summary: each gate's row, the verdict, the sticky comment."""++from __future__ import annotations++import json++import pytest+from click.testing import CliRunner++from repowise.cli.ci import write_gate_summary+from repowise.cli.commands.ci_summary_cmd import ci_summary_command+from repowise.core.analysis import health_gate, security_gate+from repowise.core.analysis.doc_drift import render as doc_drift_render+from repowise.core.analysis.doc_drift.gate import evaluate_gate+from repowise.core.analysis.health.coverage import file_coverage+from repowise.core.analysis.patch_coverage import compute_patch_coverage+from repowise.core.analysis.patch_coverage import gate_summary as coverage_summary+from repowise.core.ci.markdown import ROW_LIMIT+from repowise.core.ci.summary import (+ COMMENT_MARKER,+ MESSAGE_LIMIT,+ GateSummary,+ SummaryFinding,+ combined_verdict,+ comment_marker,+ fingerprint_marker,+ fingerprints_in,+ render_comment,+ render_job_summary,+ with_exit_code,+)+++def _finding(fp: str = "abc", level: str = "error", line: int | None = 3) -> SummaryFinding:+ return SummaryFinding(level, "src/a.py", line, "Too complex", fp)+++ ("verdicts", "expected"),+ [+ ((), "pass"),+ (("pass", "pass"), "pass"),+ (("pass", "warn"), "warn"),+ (("warn", "fail"), "fail"),+ (("pass", "error"), "fail"),+ ],+)+def test_combined_verdict(verdicts, expected) -> None:+ assert combined_verdict(GateSummary(f"g{i}", v, "") for i, v in enumerate(verdicts)) == expected+++def test_the_exit_code_decides_fail_and_could_not_evaluate() -> None:+ passing = GateSummary("security", "pass", "No new finding.")+ assert with_exit_code(passing, "security", 0) is passing+ # A check layered on the gate (a grown baseline) fails it without a failing finding.+ assert with_exit_code(passing, "security", 1).verdict == "fail"+ assert with_exit_code(passing, "security", 2).verdict == "error"+ crashed = with_exit_code(None, "health", 1)+ assert (crashed.gate, crashed.verdict) == ("health", "error")+++def test_an_overridden_pass_says_the_exit_code_failed_it() -> None:+ row = with_exit_code(GateSummary("security", "pass", "No new finding."), "security", 1)+ assert row.headline == "No new finding. The gate exited 1; see the job log for why."+++def test_a_gate_that_exits_0_with_no_result_warns_rather_than_fails() -> None:+ row = with_exit_code(None, "health", 0)+ assert (row.gate, row.verdict) == ("health", "no_result")+ assert combined_verdict([row, GateSummary("security", "pass", "")]) == "warn"+ assert "| Health | Could not evaluate |" in render_job_summary([row])+++def test_comment_lists_findings_with_a_fingerprint_marker_each() -> None:+ gates = [+ GateSummary("health", "fail", "Fails on 1 finding.", (_finding("f1"),)),+ GateSummary("security", "pass", "No new finding."),+ ]+ body = render_comment(gates)+ assert body.startswith(COMMENT_MARKER + "\n")+ assert "### Repowise gates: fail" in body+ assert "| Health | Fail | Fails on 1 finding. |" in body+ assert "| Security | Pass | No new finding. |" in body+ assert "#### Security" not in body+ line = next(x for x in body.splitlines() if "Too complex" in x)+ assert line.startswith("- error `src/a.py:3`")+ assert line.endswith(fingerprint_marker("health", "f1"))+ assert fingerprints_in(body) == {"health:f1"}+++def test_comment_caps_each_gate_and_counts_the_rest() -> None:+ findings = tuple(_finding(f"f{i}", line=i + 1) for i in range(ROW_LIMIT + 3))+ body = render_comment([GateSummary("health", "fail", "x", findings)])+ assert len(fingerprints_in(body)) == ROW_LIMIT+ assert "And 3 more findings. See the job summary." in body+++def test_comment_counts_findings_resolved_since_the_previous_one() -> None:+ before = render_comment(+ [GateSummary("health", "fail", "x", (_finding("kept"), _finding("gone")))]+ )+ after = render_comment(+ [GateSummary("health", "fail", "x", (_finding("kept"),))], previous=before+ )+ assert "Resolved since the last run: 1 finding." in after+ again = render_comment(+ [GateSummary("health", "fail", "x", (_finding("kept"),))], previous=after+ )+ assert "Resolved" not in again+++def test_a_gate_that_judged_nothing_resolves_nothing() -> None:+ before = render_comment(+ [+ GateSummary("health", "fail", "x", (_finding("h1"),)),+ GateSummary("security", "fail", "x", (_finding("s1"),)),+ ]+ )+ after = render_comment(+ [+ GateSummary("health", "error", "crashed"),+ with_exit_code(None, "security", 0),+ ],+ previous=before,+ )+ assert "Resolved" not in after+++def test_untrusted_text_stays_one_inert_line() -> None:+ message = "Line one\nline two @org/team see [x](https://e.test) "+ finding = SummaryFinding("error", "d.md", 1, message, "f")+ body = render_comment([GateSummary("doc-drift", "fail", "@someone", (finding,))])+ (line,) = [x for x in body.splitlines() if "Line one" in x]+ assert "line two" in line+ assert "@org" not in line and "@\u200borg" in line+ assert "[x]" not in line and "![i]" not in line+ assert "@someone" not in body+++def test_a_long_message_is_capped() -> None:+ short = GateSummary("health", "fail", "x", (_finding(),))+ huge = SummaryFinding("error", "a.py", 1, "y" * 5000, "f")+ long = GateSummary("health", "fail", "x", (huge,))+ assert len(render_comment([long])) < len(render_comment([short])) + MESSAGE_LIMIT + 50+++def test_each_working_directory_keeps_its_own_comment() -> None:+ assert comment_marker() == COMMENT_MARKER == comment_marker("")+ assert comment_marker("apps/web") == "<!-- repowise-ci-summary:apps/web -->"+ assert comment_marker("a b-->") == "<!-- repowise-ci-summary:a_b___ -->"+ body = render_comment([GateSummary("health", "pass", "")], key="apps/web")+ assert body.startswith("<!-- repowise-ci-summary:apps/web -->\n")+++def test_a_marker_never_closes_its_html_comment_early() -> None:+ marker = fingerprint_marker("doc-drift", "a-->b <x>")+ assert marker.count("-->") == 1 and marker.endswith(" -->")+ assert fingerprints_in(marker) == {"doc-drift:a-_b__x_"}+++def test_job_summary_is_the_table_alone() -> None:+ text = render_job_summary([GateSummary("health", "warn", "Passed with 1 warning.", (_finding(),))])+ assert "| Health | Warn | Passed with 1 warning. |" in text+ assert "Too complex" not in text and COMMENT_MARKER not in text+++def test_summary_round_trips_through_json() -> None:+ summary = GateSummary("health", "warn", "h", (_finding(line=None),))+ assert GateSummary.from_dict(json.loads(json.dumps(summary.to_dict()))) == summary+++# -- each gate's row ----------------------------------------------------------+++def test_health_row_lists_errors_and_warnings_but_not_notes() -> None:+ def gf(level: str, fp: str) -> health_gate.GateFinding:+ return health_gate.GateFinding("health", "nesting", level, "a.py", 4, "Deep", fp)++ result = health_gate.assemble(+ [gf("error", "e"), gf("warning", "w"), gf("note", "n")], fail_on="introduced"+ )+ row = health_gate.gate_summary(result)+ assert (row.gate, row.verdict) == ("health", "fail")+ assert [(f.level, f.fingerprint) for f in row.findings] == [("error", "e"), ("warning", "w")]+++def _security_row(kind="eval_call", severity="high", snippet="eval(x)", line=1):+ return {+ "file_path": "a.py",+ "line_number": line,+ "kind": kind,+ "severity": severity,+ "snippet": snippet,+ "fingerprint": security_gate.fingerprint_of("a.py", kind, snippet),+ "commit": None,+ }+++def test_security_row_warns_below_the_threshold_and_skips_the_baseline() -> None:+ low = _security_row("weak_hash", "low", "md5")+ high = _security_row()+ gate = security_gate.evaluate([low], fail_on="high")+ row = security_gate.gate_summary([low], gate)+ assert row.verdict == "warn" and [f.level for f in row.findings] == ["warning"]++ failed = security_gate.GateResult(passed=False, fail_on="high")+ assert security_gate.gate_summary([], failed).headline == "Failed; see the job log for why."++ gate = security_gate.evaluate([high, low], fail_on="high")+ row = security_gate.gate_summary([high, low], gate)+ assert row.verdict == "fail" and row.headline == "1 new finding at high or above."+ assert row.findings[0].fingerprint == high["fingerprint"]++ accepted = security_gate.evaluate([high], baseline=frozenset({high["fingerprint"]}))+ assert security_gate.gate_summary([high], accepted).findings == ()+++def test_doc_drift_row_lists_failing_findings_only() -> None:+ finding = {+ "file_path": "docs/a.md",+ "line_number": 7,+ "kind": "path",+ "target": "src/gone.py",+ "confidence": 0.95,+ "reason": "src/gone.py does not exist.",+ "origin": "markdown_link",+ }+ weak = {**finding, "target": "src/maybe.py", "confidence": 0.1}+ row = doc_drift_render.gate_summary(evaluate_gate([finding, weak]))+ assert row.verdict == "fail"+ assert [f.path for f in row.findings] == ["docs/a.md"]+ moved = doc_drift_render.gate_summary(evaluate_gate([{**finding, "line_number": 40}]))+ assert moved.findings[0].fingerprint == row.findings[0].fingerprint+ assert doc_drift_render.gate_summary(evaluate_gate([weak])).verdict == "pass"+++def test_coverage_row_names_each_file_with_uncovered_changes_by_path() -> None:+ coverage = {"src/a.py": file_coverage("src/a.py", [1], [1, 2, 3])}+ pc = compute_patch_coverage({"src/a.py": {1, 2, 3}}, coverage, threshold=80)+ row = coverage_summary(pc)+ assert row.verdict == "fail"+ (f,) = row.findings+ assert (f.level, f.path, f.line) == ("error", "src/a.py", None)+ assert "2 changed lines not covered" in f.message+ other = compute_patch_coverage({"src/a.py": {2}}, coverage)+ assert coverage_summary(other).findings[0].fingerprint == f.fingerprint+ assert coverage_summary(other).verdict == "pass"+ assert coverage_summary(other).findings[0].level == "warning"+++# -- the CLI side -------------------------------------------------------------+++def test_each_gate_leaves_its_row_only_when_the_action_asks(tmp_path) -> None:+ row = GateSummary("security", "pass", "No new finding.")+ assert not write_gate_summary(row, env={})+ env = {"REPOWISE_GATE_SUMMARY_DIR": str(tmp_path / "rows")}+ assert write_gate_summary(row, env=env)+ saved = json.loads((tmp_path / "rows" / "security.json").read_text(encoding="utf-8"))+ assert GateSummary.from_dict(saved) == row+++def test_ci_summary_command_writes_the_comment_and_prints_the_verdict(tmp_path) -> None:+ rows = tmp_path / "rows"+ env = {"REPOWISE_GATE_SUMMARY_DIR": str(rows)}+ write_gate_summary(GateSummary("health", "warn", "w", (_finding(level="warning"),)), env=env)+ write_gate_summary(GateSummary("security", "pass", "ok"), env=env)+ step_summary = tmp_path / "step.md"+ comment = tmp_path / "comment.md"+ previous = tmp_path / "previous.md"+ previous.write_text(fingerprint_marker("security", "old"), encoding="utf-8")+ result = CliRunner().invoke(+ ci_summary_command,+ [+ str(rows),+ "--gate", "health=0",+ "--gate", "security=0",+ "--gate", "doc-drift=2",+ "--previous", str(previous),+ "--comment-file", str(comment),+ ],+ env={"GITHUB_STEP_SUMMARY": str(step_summary)},+ ) # fmt: skip+ assert result.exit_code == 0, result.output+ assert result.output.strip() == "fail"+ body = comment.read_text(encoding="utf-8")+ assert "| Doc drift | Could not evaluate |" in body+ assert "Resolved since the last run: 1 finding." in body+ assert "| Health | Warn | w |" in step_summary.read_text(encoding="utf-8")+++def test_ci_summary_command_rejects_a_malformed_gate(tmp_path) -> None:+ result = CliRunner().invoke(ci_summary_command, [str(tmp_path), "--gate", "health"])+ assert result.exit_code == 2+ assert "NAME=EXIT_CODE" in result.outputdiff --git a/tests/unit/test_policy_report.py b/tests/unit/test_policy_report.pyindex 738d8d57d..621a3e8d5 100644--- a/tests/unit/test_policy_report.py+++ b/tests/unit/test_policy_report.py@@ -128,3 +128,14 @@ def test_a_policy_outside_the_repository_locates_on_a_repo_file():)(res,) = log["runs"][0]["results"]assert res["locations"][0]["physicalLocation"]["artifactLocation"]["uri"] == "src/a.py"+++def test_a_finding_without_its_own_fingerprint_keeps_one_when_its_line_moves():+ policy = parse_policy("rules: [{name: sec, gate: security}]")++ def prints(line: int) -> set[str]:+ run = GateRun(1, "x", (("a.py", line, None),))+ log = render_sarif(policy, evaluate(policy, None, {"sec": run}), tool_version="1", revspec="")+ return {r["partialFingerprints"]["repowisePolicy/v1"] for r in log["runs"][0]["results"]}++ assert prints(3) == prints(30)