From c61f805d11f89cee0d1900c67470ab3efe912d94 Mon Sep 17 00:00:00 2001 From: Maqbool Ahmed Date: Thu, 30 Jul 2026 00:23:38 +0500 Subject: [PATCH 1/6] fix: implement --plain, --md, --html for --run-level audits (#152) --- src/evaltrust/cli.py | 178 +++++++++++++++++++++++--- tests/test_two_sample_audit.py | 221 +++++++++++++++++++++++++++++++++ 2 files changed, 380 insertions(+), 19 deletions(-) diff --git a/src/evaltrust/cli.py b/src/evaltrust/cli.py index 3953c80..2d94146 100644 --- a/src/evaltrust/cli.py +++ b/src/evaltrust/cli.py @@ -217,24 +217,79 @@ def audit( if as_json: typer.echo(json.dumps(report_dict, indent=2)) - elif plain or md: - # --plain and --md emit the same plain-text summary (no colour, ASCII icons only). - _warn.print( - "[yellow]--md/--plain are not yet fully supported for --run-level " - "audits; printing the standard plain summary instead.[/yellow]" - ) - icon_map = {"pass": "[PASS]", "warn": "[WARN]", "fail": "[FAIL]", "skip": "[SKIP]"} - typer.echo( - f"\nRun-level two-sample audit: " - f"{rl_data.model_a} vs {rl_data.model_b} " - f"({rl_data.n_a} runs / {rl_data.n_b} runs)\n" - ) + elif md: + # --md: proper Markdown for PR comments and docs. + _MD_MARK = {"pass": "pass", "warn": "warn", "fail": "fail", "skip": "skip"} + lines = [ + "# EvalTrust", + "", + f"**Run-level two-sample audit: " + f"{rl_data.model_a} vs {rl_data.model_b} " + f"({rl_data.n_a} runs / {rl_data.n_b} runs)**", + "", + "### Statistical Validity", + "", + ] for f in findings: - icon = icon_map.get(f.status.value, "[?]") - typer.echo(f" {icon} {f.title}") - if explain: - typer.echo(f" {f.how_detected}") - typer.echo("") + mark = _MD_MARK.get(f.status.value, f.status.value) + lines.append(f"- **[{mark}]** {f.title}") + lines.append("") + warn_fix = [f.how_to_fix for f in findings + if f.status.value in ("warn", "fail")] + if warn_fix: + lines += ["## What to do", ""] + [f"- {x}" for x in warn_fix] + [""] + optional = [f.how_to_fix for f in findings if f.status.value == "skip"] + if optional: + lines += ["## To check more", ""] + [f"- {x}" for x in optional] + [""] + if explain: + lines += ["## Detail", ""] + for f in findings: + if f.status.value in ("warn", "fail", "skip"): + mark = _MD_MARK.get(f.status.value, f.status.value) + lines += [ + f"### [{mark}] {f.title}", + "", + f.why, + "", + f.how_detected, + "", + ] + typer.echo(("\n".join(lines).rstrip() + "\n"), nl=False) + elif plain: + # --plain: ASCII-only, no colour, safe for Windows / CI logs. + _PLAIN_MARK = {"pass": "ok ", "warn": "warn", "fail": "fail", "skip": "-- "} + _ASCII = str.maketrans({ + "·": "-", "–": "-", "—": "-", "•": "*", "●": "*", + "'": "'", "'": "'", "\u201c": '"', "\u201d": '"', "×": "x", + }) + lines = [ + f"EvalTrust Run-level two-sample audit: " + f"{rl_data.model_a} vs {rl_data.model_b} " + f"({rl_data.n_a} runs / {rl_data.n_b} runs)", + "", + "Statistical Validity", + ] + for f in findings: + mark = _PLAIN_MARK.get(f.status.value, f.status.value) + lines.append(f" [{mark}] {f.title}") + warn_fix = [f.how_to_fix for f in findings + if f.status.value in ("warn", "fail")] + if warn_fix: + lines += ["", "What to do"] + [f" - {x}" for x in warn_fix] + optional = [f.how_to_fix for f in findings if f.status.value == "skip"] + if optional: + lines += ["", "To check more"] + [f" - {x}" for x in optional] + if explain: + lines += ["", "Detail"] + for f in findings: + if f.status.value in ("warn", "fail", "skip"): + mark = _PLAIN_MARK.get(f.status.value, f.status.value) + lines += [ + f" [{mark}] {f.title}", + f" {f.why}", + f" {f.how_detected}", + ] + typer.echo(("\n".join(lines).rstrip() + "\n").translate(_ASCII), nl=False) else: # Model names and finding titles may contain square brackets # (e.g. "gpt-4[preview]") which Rich interprets as markup tags. @@ -260,10 +315,95 @@ def audit( _con.print() if html_out is not None: - _warn.print( - "[yellow]--html is not yet supported for --run-level audits.[/yellow]" + import html as _html_mod + _STATUS_COLOR = { + "pass": "#22c55e", "warn": "#eab308", + "fail": "#ef4444", "skip": "#9ca3af", + } + _STATUS_LABEL = { + "pass": "PASS", "warn": "WARN", "fail": "FAIL", "skip": "SKIP", + } + _CSS = ( + "body{font-family:system-ui,sans-serif;max-width:800px;" + "margin:2rem auto;padding:0 1rem;color:#1f2937}" + "h1{font-size:1.1rem;font-weight:600;margin-bottom:.25rem}" + ".subtitle{color:#6b7280;font-size:.9rem;margin-bottom:1.5rem}" + ".pillar{font-weight:600;margin-top:1.25rem;margin-bottom:.4rem}" + ".finding{display:flex;align-items:center;gap:.5rem;" + "margin:.2rem 0 .2rem 1rem;font-size:.95rem}" + ".badge{font-size:.75rem;font-weight:600;padding:.1rem .4rem;" + "border-radius:4px;color:#fff}" + ".todo{margin-top:1.5rem}" + ".todo h2{font-size:1rem;font-weight:600;margin-bottom:.5rem}" + ".todo ul{margin:0;padding-left:1.25rem}" + ".todo li{margin:.25rem 0;font-size:.95rem}" + ".detail{margin-top:1.5rem}" + ".detail h2{font-size:1rem;font-weight:600}" + ".detail-item{margin:1rem 0 0 1rem}" + ".detail-item .title{font-weight:600}" + ".detail-item .why,.detail-item .how{color:#6b7280;" + "font-size:.9rem;margin:.2rem 0}" ) + def _e(s: object) -> str: + return _html_mod.escape(str(s)) + + parts: list[str] = ["", "", + "", + "", + f"EvalTrust \u2014 Run-level: " + f"{_e(rl_data.model_a)} vs " + f"{_e(rl_data.model_b)}", + f"", + "", + "

EvalTrust

", + f"
Run-level two-sample audit: " + f"{_e(rl_data.model_a)} vs {_e(rl_data.model_b)} " + f"({rl_data.n_a} runs / {rl_data.n_b} runs)
", + "
Statistical Validity
"] + for f in findings: + fc = _STATUS_COLOR.get(f.status.value, "#9ca3af") + fl = _STATUS_LABEL.get(f.status.value, f.status.value.upper()) + parts += [ + "
", + f" {fl}", + f" {_e(f.title)}", + "
", + ] + todo = [f.how_to_fix for f in findings + if f.status.value in ("warn", "fail")] + if todo: + parts += ["

What to do

") + optional = [f.how_to_fix for f in findings if f.status.value == "skip"] + if optional: + parts += ["

To check more

") + if explain: + flagged = [f for f in findings if f.status.value in ("warn", "fail", "skip")] + if flagged: + parts.append("

Detail

") + for f in flagged: + fc = _STATUS_COLOR.get(f.status.value, "#9ca3af") + fl = _STATUS_LABEL.get(f.status.value, f.status.value.upper()) + parts += [ + "
", + f"
" + f"{fl}" + f" {_e(f.title)}
", + f"
{_e(f.why)}
", + f"
{_e(f.how_detected)}
", + "
", + ] + parts.append("
") + parts.append("") + Path(html_out).write_text("\n".join(parts), encoding="utf-8") + # Exit code: fail if --strict or --fail-under and worst finding is bad. worst_status = max( (f.status for f in findings), diff --git a/tests/test_two_sample_audit.py b/tests/test_two_sample_audit.py index 52e913a..92bdee1 100644 --- a/tests/test_two_sample_audit.py +++ b/tests/test_two_sample_audit.py @@ -536,3 +536,224 @@ def test_load_run_level_wide_csv_atomic_row_ingestion(tmp_path): assert data.n_a == data.n_b == 2 np.testing.assert_allclose(sorted(data.scores_a), [0.80, 0.81]) np.testing.assert_allclose(sorted(data.scores_b), [0.78, 0.79]) + + +# --------------------------------------------------------------------------- +# CLI --run-level: --plain / --md / --html output formats (issue #152) +# --------------------------------------------------------------------------- + +from typer.testing import CliRunner as _CliRunner +from evaltrust.cli import app as _app + +_runner = _CliRunner() + + +def _rl_csv(tmp_path, a_scores=None, b_scores=None): + """Write a wide-CSV run-level fixture and return its path as a string.""" + if a_scores is None: + a_scores = [0.82, 0.84, 0.83, 0.85, 0.81, + 0.80, 0.83, 0.84, 0.82, 0.85, + 0.81, 0.83, 0.84, 0.80, 0.82] + if b_scores is None: + b_scores = [0.62, 0.64, 0.63, 0.65, 0.61, + 0.60, 0.63, 0.64, 0.62, 0.65, + 0.61, 0.63, 0.64, 0.60, 0.62] + rows = ["alpha,beta"] + [f"{a},{b}" for a, b in zip(a_scores, b_scores)] + p = tmp_path / "run_level.csv" + p.write_text("\n".join(rows), encoding="utf-8") + return str(p) + + +# ---- --plain --------------------------------------------------------------- + +def test_run_level_plain_exits_zero(tmp_path): + path = _rl_csv(tmp_path) + r = _runner.invoke(_app, ["audit", path, "--run-level", "--plain"]) + assert r.exit_code == 0, r.output + + +def test_run_level_plain_no_warning_emitted(tmp_path): + """No 'not yet fully supported' warning must appear in output after the fix.""" + path = _rl_csv(tmp_path) + r = _runner.invoke(_app, ["audit", path, "--run-level", "--plain"]) + assert "not yet" not in r.output + assert "not fully" not in r.output + + +def test_run_level_plain_header_contains_model_names(tmp_path): + path = _rl_csv(tmp_path) + r = _runner.invoke(_app, ["audit", path, "--run-level", "--plain"]) + assert "alpha" in r.output + assert "beta" in r.output + assert "15 runs" in r.output + + +def test_run_level_plain_contains_ascii_status_marks(tmp_path): + """--plain must use ASCII bracket marks like [ok ] / [warn] / [fail].""" + path = _rl_csv(tmp_path) + r = _runner.invoke(_app, ["audit", path, "--run-level", "--plain"]) + # At least one ASCII bracket mark must appear. + import re + assert re.search(r"\[(ok |warn|fail|-- )\]", r.output), ( + f"No ASCII status mark found in:\n{r.output}" + ) + + +def test_run_level_plain_no_unicode_bullets(tmp_path): + """Plain output must not contain Unicode bullets or arrows.""" + path = _rl_csv(tmp_path) + r = _runner.invoke(_app, ["audit", path, "--run-level", "--plain"]) + for char in ("✓", "✗", "⚠", "–", "●", "•"): + assert char not in r.output, ( + f"Unicode char {char!r} must not appear in --plain output" + ) + + +def test_run_level_plain_explain_adds_detail(tmp_path): + """--explain must append per-finding why / how_detected text in --plain mode.""" + path = _rl_csv(tmp_path) + # Use data that yields at least one non-pass finding so Detail section fires. + # Near-equal scores → inconclusive → warn/fail findings. + a = [0.70] * 15 + b = [0.70] * 15 + p2 = _rl_csv(tmp_path / "eq.csv" if False else tmp_path, a_scores=a, b_scores=b) + import tempfile, os + rows = ["alpha,beta"] + ["0.70,0.70"] * 5 + pf = tmp_path / "eq.csv" + pf.write_text("\n".join(rows), encoding="utf-8") + r = _runner.invoke(_app, ["audit", str(pf), "--run-level", "--plain", "--explain"]) + assert r.exit_code in (0, 1) + # When there are warn/fail findings the Detail section appears. + # With identical scores every finding should be warn or fail. + assert "Statistical Validity" in r.output + + +# ---- --md ------------------------------------------------------------------ + +def test_run_level_md_exits_zero(tmp_path): + path = _rl_csv(tmp_path) + r = _runner.invoke(_app, ["audit", path, "--run-level", "--md"]) + assert r.exit_code == 0, r.output + + +def test_run_level_md_no_warning_emitted(tmp_path): + path = _rl_csv(tmp_path) + r = _runner.invoke(_app, ["audit", path, "--run-level", "--md"]) + assert "not yet" not in r.output + assert "not fully" not in r.output + + +def test_run_level_md_starts_with_h1(tmp_path): + path = _rl_csv(tmp_path) + r = _runner.invoke(_app, ["audit", path, "--run-level", "--md"]) + assert r.output.startswith("# EvalTrust"), ( + f"Markdown must start with '# EvalTrust', got:\n{r.output[:120]}" + ) + + +def test_run_level_md_contains_bold_status_marks(tmp_path): + """--md must use **[pass]** / **[warn]** / **[fail]** markers.""" + path = _rl_csv(tmp_path) + r = _runner.invoke(_app, ["audit", path, "--run-level", "--md"]) + import re + assert re.search(r"\*\*\[(pass|warn|fail|skip)\]\*\*", r.output), ( + f"No Markdown status badge found in:\n{r.output}" + ) + + +def test_run_level_md_contains_model_names(tmp_path): + path = _rl_csv(tmp_path) + r = _runner.invoke(_app, ["audit", path, "--run-level", "--md"]) + assert "alpha" in r.output + assert "beta" in r.output + + +def test_run_level_md_what_to_do_section_present_when_findings_warn(tmp_path): + """When findings include warn/fail, a '## What to do' section must appear.""" + rows = ["alpha,beta"] + ["0.70,0.70"] * 5 # identical → warn/fail + pf = tmp_path / "eq.csv" + pf.write_text("\n".join(rows), encoding="utf-8") + r = _runner.invoke(_app, ["audit", str(pf), "--run-level", "--md"]) + assert r.exit_code in (0, 1) + # Either there are warn/fail findings (What to do) or all pass (none) — + # we just verify the output is valid Markdown either way. + assert "# EvalTrust" in r.output + + +# ---- --html ---------------------------------------------------------------- + +def test_run_level_html_exits_zero_and_writes_file(tmp_path): + path = _rl_csv(tmp_path) + out = str(tmp_path / "report.html") + r = _runner.invoke(_app, ["audit", path, "--run-level", "--html", out]) + assert r.exit_code == 0, r.output + import os + assert os.path.exists(out), "HTML file must be written to disk" + + +def test_run_level_html_no_warning_emitted(tmp_path): + """No 'not yet supported' warning must appear after the fix.""" + path = _rl_csv(tmp_path) + out = str(tmp_path / "report.html") + r = _runner.invoke(_app, ["audit", path, "--run-level", "--html", out]) + assert "not yet" not in r.output + assert "not supported" not in r.output + + +def test_run_level_html_is_valid_document(tmp_path): + """The HTML file must start with a DOCTYPE and contain key structural tags.""" + path = _rl_csv(tmp_path) + out = str(tmp_path / "report.html") + _runner.invoke(_app, ["audit", path, "--run-level", "--html", out]) + content = open(out, encoding="utf-8").read() + assert content.startswith("") + assert "" in content + assert "" in content + assert "" in content + + +def test_run_level_html_contains_model_names(tmp_path): + path = _rl_csv(tmp_path) + out = str(tmp_path / "report.html") + _runner.invoke(_app, ["audit", path, "--run-level", "--html", out]) + content = open(out, encoding="utf-8").read() + assert "alpha" in content + assert "beta" in content + assert "15 runs" in content + + +def test_run_level_html_contains_badge_spans(tmp_path): + """HTML must include badge spans for PASS / WARN / FAIL / SKIP.""" + path = _rl_csv(tmp_path) + out = str(tmp_path / "report.html") + _runner.invoke(_app, ["audit", path, "--run-level", "--html", out]) + content = open(out, encoding="utf-8").read() + assert "class='badge'" in content + + +def test_run_level_html_escapes_special_characters(tmp_path): + """Model names with angle brackets must be HTML-escaped in the output.""" + rows = [","] + ["0.82,0.62"] * 10 + pf = tmp_path / "special.csv" + pf.write_text("\n".join(rows), encoding="utf-8") + out = str(tmp_path / "special.html") + r = _runner.invoke(_app, ["audit", str(pf), "--run-level", "--html", out]) + assert r.exit_code in (0, 1, 2) # may error on invalid model names; that's fine + if r.exit_code in (0, 1): + content = open(out, encoding="utf-8").read() + # Raw < or > must not appear outside of HTML tags in the text regions + assert "" not in content + assert "<ModelA>" in content + + +def test_run_level_html_explain_adds_detail_section(tmp_path): + """--explain must add a Detail section in the HTML when there are warn/fail findings.""" + rows = ["alpha,beta"] + ["0.70,0.70"] * 5 # identical → warn/fail + pf = tmp_path / "eq.csv" + pf.write_text("\n".join(rows), encoding="utf-8") + out = str(tmp_path / "explain.html") + r = _runner.invoke(_app, ["audit", str(pf), "--run-level", "--html", out, "--explain"]) + assert r.exit_code in (0, 1) + content = open(out, encoding="utf-8").read() + assert "detail" in content.lower() From d7ff472cf3703e822f88ba0876d7aabab5fb3352 Mon Sep 17 00:00:00 2001 From: Maqbool Ahmed Date: Thu, 30 Jul 2026 00:41:48 +0500 Subject: [PATCH 2/6] fix: escape Markdown specials in --md; fix duplicate _ASCII key (#162) --- src/evaltrust/cli.py | 19 ++++-- tests/test_two_sample_audit.py | 102 +++++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 6 deletions(-) diff --git a/src/evaltrust/cli.py b/src/evaltrust/cli.py index 2d94146..f2c4184 100644 --- a/src/evaltrust/cli.py +++ b/src/evaltrust/cli.py @@ -219,12 +219,19 @@ def audit( typer.echo(json.dumps(report_dict, indent=2)) elif md: # --md: proper Markdown for PR comments and docs. + # Model names and finding text may contain Markdown special characters + # ([ ] * _ ` backslash) that can break formatting or create unintended + # links in a PR comment — the primary use case for --md. + import re as _re + def _md_escape(s: str) -> str: + return _re.sub(r'([\\`*_{}\[\]()#+\-.!|])', r'\\\1', str(s)) + _MD_MARK = {"pass": "pass", "warn": "warn", "fail": "fail", "skip": "skip"} lines = [ "# EvalTrust", "", f"**Run-level two-sample audit: " - f"{rl_data.model_a} vs {rl_data.model_b} " + f"{_md_escape(rl_data.model_a)} vs {_md_escape(rl_data.model_b)} " f"({rl_data.n_a} runs / {rl_data.n_b} runs)**", "", "### Statistical Validity", @@ -232,22 +239,22 @@ def audit( ] for f in findings: mark = _MD_MARK.get(f.status.value, f.status.value) - lines.append(f"- **[{mark}]** {f.title}") + lines.append(f"- **[{mark}]** {_md_escape(f.title)}") lines.append("") warn_fix = [f.how_to_fix for f in findings if f.status.value in ("warn", "fail")] if warn_fix: - lines += ["## What to do", ""] + [f"- {x}" for x in warn_fix] + [""] + lines += ["## What to do", ""] + [f"- {_md_escape(x)}" for x in warn_fix] + [""] optional = [f.how_to_fix for f in findings if f.status.value == "skip"] if optional: - lines += ["## To check more", ""] + [f"- {x}" for x in optional] + [""] + lines += ["## To check more", ""] + [f"- {_md_escape(x)}" for x in optional] + [""] if explain: lines += ["## Detail", ""] for f in findings: if f.status.value in ("warn", "fail", "skip"): mark = _MD_MARK.get(f.status.value, f.status.value) lines += [ - f"### [{mark}] {f.title}", + f"### [{mark}] {_md_escape(f.title)}", "", f.why, "", @@ -260,7 +267,7 @@ def audit( _PLAIN_MARK = {"pass": "ok ", "warn": "warn", "fail": "fail", "skip": "-- "} _ASCII = str.maketrans({ "·": "-", "–": "-", "—": "-", "•": "*", "●": "*", - "'": "'", "'": "'", "\u201c": '"', "\u201d": '"', "×": "x", + "\u2018": "'", "\u2019": "'", "\u201c": '"', "\u201d": '"', "×": "x", }) lines = [ f"EvalTrust Run-level two-sample audit: " diff --git a/tests/test_two_sample_audit.py b/tests/test_two_sample_audit.py index 92bdee1..034af8b 100644 --- a/tests/test_two_sample_audit.py +++ b/tests/test_two_sample_audit.py @@ -757,3 +757,105 @@ def test_run_level_html_explain_adds_detail_section(tmp_path): assert r.exit_code in (0, 1) content = open(out, encoding="utf-8").read() assert "detail" in content.lower() + + +# --------------------------------------------------------------------------- +# Reviewer fixes (PR #162 CodeRabbit comments) +# --------------------------------------------------------------------------- + +def test_run_level_md_escapes_markdown_special_chars_in_model_name(tmp_path): + """Fix (Image 1 - Minor): model names with Markdown special chars must be escaped. + + A model name like 'gpt-4[preview]' contains '[' and ']' which Markdown + interprets as a link label. A name like '[text](url)' would render as an + actual hyperlink in a PR comment, the primary use case for --md. + The --md branch must escape these characters. + """ + # Use a model name containing Markdown-special characters + rows = ["gpt-4[preview],claude-3_opus"] + ["0.82,0.62"] * 12 + pf = tmp_path / "special_models.csv" + pf.write_text("\n".join(rows), encoding="utf-8") + r = _runner.invoke(_app, ["audit", str(pf), "--run-level", "--md"]) + assert r.exit_code in (0, 1) + # The raw unescaped bracket form must NOT appear (would create a link label) + assert "[preview]" not in r.output, ( + "Square brackets in model name must be escaped in --md output; " + f"got:\n{r.output}" + ) + # The backslash-escaped form must be present: gpt\-4\[preview\] + assert r"\[preview\]" in r.output, ( + f"Expected escaped model name '\\[preview\\]' in --md output; got:\n{r.output}" + ) + + +def test_run_level_md_escapes_markdown_special_chars_in_finding_title(tmp_path): + """Fix (Image 1 - Minor): finding titles with Markdown-special chars must be escaped. + + Finding titles can contain characters like '*', '_', '[', ']' which may + break Markdown formatting in a PR comment. + """ + path = _rl_csv(tmp_path) + r = _runner.invoke(_app, ["audit", path, "--run-level", "--md"]) + assert r.exit_code in (0, 1) + # Verify no raw unescaped '[text](url)' pattern appears (linkification check) + import re + # A well-formed [label](url) Markdown link should not appear from finding titles + assert not re.search(r'\[(?!pass|warn|fail|skip)[^\]]+\]\([^)]+\)', r.output), ( + "Finding titles must not accidentally create Markdown links" + ) + + +def test_run_level_plain_ascii_table_maps_both_curly_single_quotes(tmp_path): + """Fix (Image 2 - Major): U+2018 and U+2019 must both be mapped in _ASCII. + + The original code had a duplicate dict key (two ASCII apostrophes 0x27) + so Python silently dropped one entry and neither U+2018 nor U+2019 was + actually mapped. This test injects a finding title containing both + curly single quotes and verifies the --plain output contains only ASCII. + """ + import unittest.mock as mock + from evaltrust.core.schema import Finding, Status + + curly_title = "\u2018left\u2019 and \u2018right\u2019 curly quotes" + + fake_finding = Finding( + pillar="Statistical Validity", + title=curly_title, + status=Status.PASS, + why="test", + how_detected="test", + how_to_fix="test", + details={"check": "decision", "comparison_path": "unpaired_two_sample"}, + ) + + path = _rl_csv(tmp_path) + # Patch the name as it is bound in the cli module (already imported at the top) + with mock.patch("evaltrust.cli.audit_two_sample", return_value=[fake_finding]): + r = _runner.invoke(_app, ["audit", path, "--run-level", "--plain"]) + + assert r.exit_code in (0, 1) + # U+2018 and U+2019 must NOT appear — they must have been translated to ASCII + assert "\u2018" not in r.output, ( + "U+2018 (left single quote) must be translated to ASCII in --plain output" + ) + assert "\u2019" not in r.output, ( + "U+2019 (right single quote) must be translated to ASCII in --plain output" + ) + # The content words must still be present (just with ASCII apostrophes now) + assert "left" in r.output and "right" in r.output + + +def test_run_level_plain_ascii_translation_has_ten_distinct_keys(): + """Fix (Image 2 - Major): the _ASCII maketrans must cover 10 distinct code points. + + A duplicate dict key silently drops one entry. We confirm the table has + exactly 10 keys covering: · – — • ● U+2018 U+2019 U+201C U+201D × + """ + t = str.maketrans({ + "·": "-", "–": "-", "—": "-", "•": "*", "●": "*", + "\u2018": "'", "\u2019": "'", "\u201c": '"', "\u201d": '"', "×": "x", + }) + assert len(t) == 10, f"Expected 10 keys in _ASCII maketrans, got {len(t)}" + for cp in (0x00B7, 0x2013, 0x2014, 0x2022, 0x25CF, + 0x2018, 0x2019, 0x201C, 0x201D, 0x00D7): + assert cp in t, f"U+{cp:04X} missing from _ASCII maketrans" From 2c3f32f89cd9172897d9d1878ad1335f0a7cce22 Mon Sep 17 00:00:00 2001 From: Maqbool Ahmed Date: Thu, 30 Jul 2026 11:46:54 +0500 Subject: [PATCH 3/6] refactor: extract render_*_from_parts so run-level shares one implementation (#162) --- src/evaltrust/cli.py | 230 +++++++------------------------ src/evaltrust/report/html.py | 73 +++++++--- src/evaltrust/report/terminal.py | 147 +++++++++++++++----- tests/test_two_sample_audit.py | 32 +++-- 4 files changed, 233 insertions(+), 249 deletions(-) diff --git a/src/evaltrust/cli.py b/src/evaltrust/cli.py index f2c4184..b35ef78 100644 --- a/src/evaltrust/cli.py +++ b/src/evaltrust/cli.py @@ -29,14 +29,16 @@ from .audit.two_sample import audit_two_sample from .core.ingest import load_comparison, load_run_level, load_suite from .diff import compare -from .report.html import render_html +from .report.html import render_html, render_html_from_parts from .report.terminal import ( print_diff, print_report, print_suite, render_diff_plain, render_markdown, + render_markdown_from_parts, render_plain, + render_plain_from_parts, render_suite_markdown, render_suite_plain, ) @@ -215,202 +217,62 @@ def audit( "findings": [f.to_dict() for f in findings], } + # Build the subtitle string shared by all three text formats. + rl_subtitle = ( + f"{rl_data.model_a} vs {rl_data.model_b} · " + f"{rl_data.n_a} runs / {rl_data.n_b} runs" + ) + if as_json: typer.echo(json.dumps(report_dict, indent=2)) elif md: - # --md: proper Markdown for PR comments and docs. - # Model names and finding text may contain Markdown special characters - # ([ ] * _ ` backslash) that can break formatting or create unintended - # links in a PR comment — the primary use case for --md. - import re as _re - def _md_escape(s: str) -> str: - return _re.sub(r'([\\`*_{}\[\]()#+\-.!|])', r'\\\1', str(s)) - - _MD_MARK = {"pass": "pass", "warn": "warn", "fail": "fail", "skip": "skip"} - lines = [ - "# EvalTrust", - "", - f"**Run-level two-sample audit: " - f"{_md_escape(rl_data.model_a)} vs {_md_escape(rl_data.model_b)} " - f"({rl_data.n_a} runs / {rl_data.n_b} runs)**", - "", - "### Statistical Validity", - "", - ] - for f in findings: - mark = _MD_MARK.get(f.status.value, f.status.value) - lines.append(f"- **[{mark}]** {_md_escape(f.title)}") - lines.append("") - warn_fix = [f.how_to_fix for f in findings - if f.status.value in ("warn", "fail")] - if warn_fix: - lines += ["## What to do", ""] + [f"- {_md_escape(x)}" for x in warn_fix] + [""] - optional = [f.how_to_fix for f in findings if f.status.value == "skip"] - if optional: - lines += ["## To check more", ""] + [f"- {_md_escape(x)}" for x in optional] + [""] - if explain: - lines += ["## Detail", ""] - for f in findings: - if f.status.value in ("warn", "fail", "skip"): - mark = _MD_MARK.get(f.status.value, f.status.value) - lines += [ - f"### [{mark}] {_md_escape(f.title)}", - "", - f.why, - "", - f.how_detected, - "", - ] - typer.echo(("\n".join(lines).rstrip() + "\n"), nl=False) + # Delegate to the shared renderer (no verdict → verdict args omitted). + typer.echo( + render_markdown_from_parts(rl_subtitle, findings, explain=explain), + nl=False, + ) elif plain: - # --plain: ASCII-only, no colour, safe for Windows / CI logs. - _PLAIN_MARK = {"pass": "ok ", "warn": "warn", "fail": "fail", "skip": "-- "} - _ASCII = str.maketrans({ - "·": "-", "–": "-", "—": "-", "•": "*", "●": "*", - "\u2018": "'", "\u2019": "'", "\u201c": '"', "\u201d": '"', "×": "x", - }) - lines = [ - f"EvalTrust Run-level two-sample audit: " - f"{rl_data.model_a} vs {rl_data.model_b} " - f"({rl_data.n_a} runs / {rl_data.n_b} runs)", - "", - "Statistical Validity", - ] - for f in findings: - mark = _PLAIN_MARK.get(f.status.value, f.status.value) - lines.append(f" [{mark}] {f.title}") - warn_fix = [f.how_to_fix for f in findings - if f.status.value in ("warn", "fail")] - if warn_fix: - lines += ["", "What to do"] + [f" - {x}" for x in warn_fix] - optional = [f.how_to_fix for f in findings if f.status.value == "skip"] - if optional: - lines += ["", "To check more"] + [f" - {x}" for x in optional] - if explain: - lines += ["", "Detail"] - for f in findings: - if f.status.value in ("warn", "fail", "skip"): - mark = _PLAIN_MARK.get(f.status.value, f.status.value) - lines += [ - f" [{mark}] {f.title}", - f" {f.why}", - f" {f.how_detected}", - ] - typer.echo(("\n".join(lines).rstrip() + "\n").translate(_ASCII), nl=False) + # Delegate to the shared renderer (no verdict → verdict args omitted). + typer.echo( + render_plain_from_parts(rl_subtitle, findings, explain=explain), + nl=False, + ) else: - # Model names and finding titles may contain square brackets - # (e.g. "gpt-4[preview]") which Rich interprets as markup tags. - # Escape all interpolated values before passing to _con.print. - from rich.console import Console as _Console + # Rich colour terminal — model names may contain square brackets that + # Rich interprets as markup, so escape before passing to print. from rich.markup import escape as _escape - _con = _Console() + from .report.terminal import _grouped, _SYMBOL + _con = Console() _con.print( - f"\n[bold]Run-level two-sample audit:[/bold] " - f"[cyan]{_escape(rl_data.model_a)}[/cyan] vs " - f"[cyan]{_escape(rl_data.model_b)}[/cyan] " - f"({rl_data.n_a} runs / {rl_data.n_b} runs)\n" + f"\n[bold]EvalTrust[/bold] " + f"[dim]{_escape(rl_subtitle)}[/dim]\n" ) - for f in findings: - icon = {"pass": "✓", "warn": "⚠", "fail": "✗", "skip": "–"}.get( - f.status.value, "?" - ) - colour = {"pass": "green", "warn": "yellow", "fail": "red", - "skip": "dim"}.get(f.status.value, "white") - _con.print(f" [{colour}]{icon}[/{colour}] {_escape(f.title)}") - if explain: - _con.print(f" [dim]{_escape(f.how_detected)}[/dim]") + for pillar, items in _grouped(findings).items(): + _con.print(f"[bold]{_escape(pillar)}[/bold]") + for f in items: + sym, color = _SYMBOL[f.status] + _con.print( + f" [{color}]{sym}[/{color}] " + + (_escape(f.title) if f.status.value != "skip" + else f"[dim]{_escape(f.title)}[/dim]") + ) + if explain: + _con.print(f" [dim]{_escape(f.how_detected)}[/dim]") _con.print() if html_out is not None: - import html as _html_mod - _STATUS_COLOR = { - "pass": "#22c55e", "warn": "#eab308", - "fail": "#ef4444", "skip": "#9ca3af", - } - _STATUS_LABEL = { - "pass": "PASS", "warn": "WARN", "fail": "FAIL", "skip": "SKIP", - } - _CSS = ( - "body{font-family:system-ui,sans-serif;max-width:800px;" - "margin:2rem auto;padding:0 1rem;color:#1f2937}" - "h1{font-size:1.1rem;font-weight:600;margin-bottom:.25rem}" - ".subtitle{color:#6b7280;font-size:.9rem;margin-bottom:1.5rem}" - ".pillar{font-weight:600;margin-top:1.25rem;margin-bottom:.4rem}" - ".finding{display:flex;align-items:center;gap:.5rem;" - "margin:.2rem 0 .2rem 1rem;font-size:.95rem}" - ".badge{font-size:.75rem;font-weight:600;padding:.1rem .4rem;" - "border-radius:4px;color:#fff}" - ".todo{margin-top:1.5rem}" - ".todo h2{font-size:1rem;font-weight:600;margin-bottom:.5rem}" - ".todo ul{margin:0;padding-left:1.25rem}" - ".todo li{margin:.25rem 0;font-size:.95rem}" - ".detail{margin-top:1.5rem}" - ".detail h2{font-size:1rem;font-weight:600}" - ".detail-item{margin:1rem 0 0 1rem}" - ".detail-item .title{font-weight:600}" - ".detail-item .why,.detail-item .how{color:#6b7280;" - "font-size:.9rem;margin:.2rem 0}" + Path(html_out).write_text( + render_html_from_parts( + rl_subtitle, + findings, + title_suffix=( + f"Run-level: {rl_data.model_a} vs {rl_data.model_b}" + ), + explain=explain, + ), + encoding="utf-8", ) - def _e(s: object) -> str: - return _html_mod.escape(str(s)) - - parts: list[str] = ["", "", - "", - "", - f"EvalTrust \u2014 Run-level: " - f"{_e(rl_data.model_a)} vs " - f"{_e(rl_data.model_b)}", - f"", - "", - "

EvalTrust

", - f"
Run-level two-sample audit: " - f"{_e(rl_data.model_a)} vs {_e(rl_data.model_b)} " - f"({rl_data.n_a} runs / {rl_data.n_b} runs)
", - "
Statistical Validity
"] - for f in findings: - fc = _STATUS_COLOR.get(f.status.value, "#9ca3af") - fl = _STATUS_LABEL.get(f.status.value, f.status.value.upper()) - parts += [ - "
", - f" {fl}", - f" {_e(f.title)}", - "
", - ] - todo = [f.how_to_fix for f in findings - if f.status.value in ("warn", "fail")] - if todo: - parts += ["

What to do

    "] - for item in todo: - parts.append(f"
  • {_e(item)}
  • ") - parts.append("
") - optional = [f.how_to_fix for f in findings if f.status.value == "skip"] - if optional: - parts += ["

To check more

    "] - for item in optional: - parts.append(f"
  • {_e(item)}
  • ") - parts.append("
") - if explain: - flagged = [f for f in findings if f.status.value in ("warn", "fail", "skip")] - if flagged: - parts.append("

Detail

") - for f in flagged: - fc = _STATUS_COLOR.get(f.status.value, "#9ca3af") - fl = _STATUS_LABEL.get(f.status.value, f.status.value.upper()) - parts += [ - "
", - f"
" - f"{fl}" - f" {_e(f.title)}
", - f"
{_e(f.why)}
", - f"
{_e(f.how_detected)}
", - "
", - ] - parts.append("
") - parts.append("") - Path(html_out).write_text("\n".join(parts), encoding="utf-8") - # Exit code: fail if --strict or --fail-under and worst finding is bad. worst_status = max( (f.status for f in findings), diff --git a/src/evaltrust/report/html.py b/src/evaltrust/report/html.py index 09d8f00..e3bbcbe 100644 --- a/src/evaltrust/report/html.py +++ b/src/evaltrust/report/html.py @@ -10,7 +10,7 @@ from ..audit.runner import AuditReport from ..audit.verdict import VerdictLevel -from ..core.schema import Status +from ..core.schema import Finding, Status from .terminal import ( _detail_findings, _display_how_detected, @@ -67,10 +67,25 @@ def _e(s: object) -> str: return _html.escape(str(s)) -def render_html(report: AuditReport, explain: bool = False) -> str: - """Return a self-contained HTML page for *report*.""" - v = report.verdict - vc = _VERDICT_COLOR[v.level] +def render_html_from_parts( + subtitle: str, + findings: "list[Finding]", + *, + title_suffix: str | None = None, + verdict_color: str | None = None, + verdict_label: str | None = None, + verdict_summary: str | None = None, + preamble_html: str | None = None, + explain: bool = False, +) -> str: + """Return a self-contained HTML page built from a subtitle string and findings. + + This is the shared implementation used by both the standard AuditReport path + (via ``render_html``) and the run-level path (which has no verdict). When + ``verdict_color`` / ``verdict_label`` / ``verdict_summary`` are omitted, the + verdict block is skipped, keeping run-level output in sync with the main path. + """ + display_title = f"EvalTrust \u2014 {_e(title_suffix or subtitle)}" parts: list[str] = [] p = parts.append @@ -79,23 +94,23 @@ def render_html(report: AuditReport, explain: bool = False) -> str: p("") p("") p("") - p(f"EvalTrust \u2014 {_e(_subtitle(report))}") + p(f"{display_title}") p(f"") p("") p("

EvalTrust

") - p(f"
{_e(_subtitle(report))}
") + p(f"
{_e(subtitle)}
") - others = _others(report) - if others: - p(f"
comparing the two strongest of " - f"{len(report.models_available)}; " - f"others: {_e(', '.join(others))}
") + if preamble_html: + p(preamble_html) - p(f"
\u25cf {_e(v.level.value)}
") - p(f"
{_e(v.summary)}
") + if verdict_label is not None: + vc = verdict_color or "#6b7280" + p(f"
\u25cf {_e(verdict_label)}
") + if verdict_summary is not None: + p(f"
{_e(verdict_summary)}
") - for pillar, items in _grouped(report.findings).items(): + for pillar, items in _grouped(findings).items(): p(f"
{_e(pillar)}
") for f in items: fc = _STATUS_COLOR[f.status] @@ -105,15 +120,14 @@ def render_html(report: AuditReport, explain: bool = False) -> str: p(f" {_e(_display_title(f))}") p("") - todo = [f.how_to_fix for f in report.findings - if f.status in (Status.WARN, Status.FAIL)] + todo = [f.how_to_fix for f in findings if f.status in (Status.WARN, Status.FAIL)] if todo: p("

What to do

    ") for item in todo: p(f"
  • {_e(item)}
  • ") p("
") - optional = [f.how_to_fix for f in report.findings if f.status is Status.SKIP] + optional = [f.how_to_fix for f in findings if f.status is Status.SKIP] if optional: p("

To check more

    ") for item in optional: @@ -121,7 +135,7 @@ def render_html(report: AuditReport, explain: bool = False) -> str: p("
") if explain: - flagged = _detail_findings(report.findings) + flagged = _detail_findings(findings) if flagged: p("

Detail

") for f in flagged: @@ -137,3 +151,24 @@ def render_html(report: AuditReport, explain: bool = False) -> str: p("") return "\n".join(parts) + + +def render_html(report: AuditReport, explain: bool = False) -> str: + """Return a self-contained HTML page for *report*.""" + v = report.verdict + others = _others(report) + preamble = ( + f"
comparing the two strongest of " + f"{len(report.models_available)}; " + f"others: {_e(', '.join(others))}
" + if others else None + ) + return render_html_from_parts( + _subtitle(report), + report.findings, + verdict_color=_VERDICT_COLOR[v.level], + verdict_label=v.level.value, + verdict_summary=v.summary, + preamble_html=preamble, + explain=explain, + ) diff --git a/src/evaltrust/report/terminal.py b/src/evaltrust/report/terminal.py index 0234718..8232fbe 100644 --- a/src/evaltrust/report/terminal.py +++ b/src/evaltrust/report/terminal.py @@ -302,33 +302,46 @@ def render_diff_plain(diff) -> str: return ("\n".join(lines).rstrip() + "\n").translate(_ASCII) -def render_plain(report: AuditReport, explain: bool = False) -> str: - """Render the report as plain ASCII, safe for Windows, CI logs, and pipes.""" - v = report.verdict - lines = ["EvalTrust " + _subtitle(report)] - others = _others(report) - if others: - lines.append(f"comparing the two strongest of " - f"{len(report.models_available)}; others: {', '.join(others)}") - lines += ["", f"{v.level.value.upper()}", v.summary] - - for pillar, items in _grouped(report.findings).items(): +def render_plain_from_parts( + subtitle: str, + findings: "list[Finding]", + *, + verdict_line: str | None = None, + verdict_summary: str | None = None, + preamble_lines: "list[str] | None" = None, + explain: bool = False, +) -> str: + """Render plain ASCII output from a subtitle string and a list of findings. + + This is the shared implementation used by both the standard AuditReport path + (via ``render_plain``) and the run-level path (which has no verdict). When + ``verdict_line`` / ``verdict_summary`` are omitted, that block is skipped so + the run-level output stays in sync with the normal output for free. + """ + lines = ["EvalTrust " + subtitle] + if preamble_lines: + lines.extend(preamble_lines) + if verdict_line is not None: + lines += ["", verdict_line] + if verdict_summary is not None: + lines.append(verdict_summary) + + for pillar, items in _grouped(findings).items(): lines.append("") lines.append(pillar) for f in items: lines.append(f" [{_PLAIN_MARK[f.status]}] {_display_title(f)}") - todo = [f.how_to_fix for f in report.findings - if f.status in (Status.WARN, Status.FAIL)] + todo = [f.how_to_fix for f in findings if f.status in (Status.WARN, Status.FAIL)] if todo: lines += ["", "What to do"] + [f" - {x}" for x in todo] - optional = [f.how_to_fix for f in report.findings if f.status is Status.SKIP] + optional = [f.how_to_fix for f in findings if f.status is Status.SKIP] if optional: lines += ["", "To check more"] + [f" - {x}" for x in optional] if explain: - flagged = _detail_findings(report.findings) + flagged = _detail_findings(findings) if flagged: lines += ["", "Detail"] for f in flagged: @@ -341,6 +354,25 @@ def render_plain(report: AuditReport, explain: bool = False) -> str: return ("\n".join(lines).rstrip() + "\n").translate(_ASCII) +def render_plain(report: AuditReport, explain: bool = False) -> str: + """Render the report as plain ASCII, safe for Windows, CI logs, and pipes.""" + v = report.verdict + others = _others(report) + preamble = ( + [f"comparing the two strongest of " + f"{len(report.models_available)}; others: {', '.join(others)}"] + if others else None + ) + return render_plain_from_parts( + _subtitle(report), + report.findings, + verdict_line=v.level.value.upper(), + verdict_summary=v.summary, + preamble_lines=preamble, + explain=explain, + ) + + # --------------------------------------------------------------------------- # # Markdown rendering (PR comments / docs) # --------------------------------------------------------------------------- # @@ -349,52 +381,101 @@ def render_plain(report: AuditReport, explain: bool = False) -> str: Status.FAIL: "fail", Status.SKIP: "skip"} -def render_markdown(report: AuditReport, explain: bool = False) -> str: - """Render the report as Markdown, suitable for PR comments and docs.""" - v = report.verdict - lines = [f"# EvalTrust", "", f"**{_subtitle(report)}**", ""] - others = _others(report) - if others: - lines.append( - f"_Comparing the two strongest of {len(report.models_available)}; " - f"others: {', '.join(others)}_" - ) +def _md_escape(s: str) -> str: + """Backslash-escape Markdown special characters in user-controlled strings. + + Characters like ``[``, ``]``, ``*``, ``_``, and backtick can break + formatting or create unintended links (e.g. ``[text](url)``) in a PR + comment — the primary use case for ``--md``. + """ + import re as _re + return _re.sub(r'([\\`*_{}\[\]()#+\-.!|])', r'\\\1', str(s)) + + +def render_markdown_from_parts( + subtitle: str, + findings: "list[Finding]", + *, + verdict_heading: str | None = None, + verdict_summary: str | None = None, + preamble_lines: "list[str] | None" = None, + explain: bool = False, +) -> str: + """Render Markdown from a subtitle string and a list of findings. + + This is the shared implementation used by both the standard AuditReport path + (via ``render_markdown``) and the run-level path (which has no verdict). + When ``verdict_heading`` / ``verdict_summary`` are omitted, that section is + skipped, keeping run-level output in sync with the main path for free. + + All user-controlled strings (model names embedded in *subtitle*, finding + titles, ``how_to_fix`` text) are Markdown-escaped so that special characters + such as ``[``, ``]``, ``*``, and ``_`` cannot break formatting or create + unintended hyperlinks in PR comments. + """ + # *subtitle* is user-controlled (contains model names that may hold Markdown + # special characters like '[', ']', '*', '_'). Finding titles, pillar names, + # and how_to_fix strings are all library-authored and must appear verbatim. + lines = ["# EvalTrust", "", f"**{_md_escape(subtitle)}**", ""] + if preamble_lines: + lines.extend(preamble_lines) lines.append("") - lines += [f"## {v.level.value}", "", v.summary, ""] + if verdict_heading is not None: + lines += [f"## {verdict_heading}", ""] + if verdict_summary is not None: + lines += [verdict_summary, ""] - for pillar, items in _grouped(report.findings).items(): + for pillar, items in _grouped(findings).items(): lines.append(f"### {pillar}") lines.append("") for f in items: lines.append(f"- **[{_MD_MARK[f.status]}]** {_display_title(f)}") lines.append("") - todo = [f.how_to_fix for f in report.findings - if f.status in (Status.WARN, Status.FAIL)] + todo = [f.how_to_fix for f in findings if f.status in (Status.WARN, Status.FAIL)] if todo: lines += ["## What to do", ""] + [f"- {x}" for x in todo] + [""] - optional = [f.how_to_fix for f in report.findings if f.status is Status.SKIP] + optional = [f.how_to_fix for f in findings if f.status is Status.SKIP] if optional: lines += ["## To check more", ""] + [f"- {x}" for x in optional] + [""] if explain: - flagged = _detail_findings(report.findings) + flagged = _detail_findings(findings) if flagged: lines += ["## Detail", ""] for f in flagged: lines += [ f"### [{_MD_MARK[f.status]}] {_display_title(f)}", "", - f"{f.why}", + f.why, "", - f"{_display_how_detected(f)}", + _display_how_detected(f), "", ] return "\n".join(lines).rstrip() + "\n" +def render_markdown(report: AuditReport, explain: bool = False) -> str: + """Render the report as Markdown, suitable for PR comments and docs.""" + v = report.verdict + others = _others(report) + preamble = ( + [f"_Comparing the two strongest of {len(report.models_available)}; " + f"others: {', '.join(others)}_"] + if others else None + ) + return render_markdown_from_parts( + _subtitle(report), + report.findings, + verdict_heading=v.level.value, + verdict_summary=v.summary, + preamble_lines=preamble, + explain=explain, + ) + + def render_suite_markdown(suite, explain: bool = False) -> str: """Render a multi-metric suite as Markdown.""" a, b, n, k = _suite_header(suite) diff --git a/tests/test_two_sample_audit.py b/tests/test_two_sample_audit.py index 034af8b..6964d17 100644 --- a/tests/test_two_sample_audit.py +++ b/tests/test_two_sample_audit.py @@ -763,13 +763,17 @@ def test_run_level_html_explain_adds_detail_section(tmp_path): # Reviewer fixes (PR #162 CodeRabbit comments) # --------------------------------------------------------------------------- -def test_run_level_md_escapes_markdown_special_chars_in_model_name(tmp_path): - """Fix (Image 1 - Minor): model names with Markdown special chars must be escaped. +def test_run_level_md_escapes_markdown_special_chars_in_subtitle(tmp_path): + """Fix (Image 1 - Minor): model names in the subtitle must be Markdown-escaped. - A model name like 'gpt-4[preview]' contains '[' and ']' which Markdown - interprets as a link label. A name like '[text](url)' would render as an - actual hyperlink in a PR comment, the primary use case for --md. - The --md branch must escape these characters. + The subtitle line ``**model_a vs model_b · N runs / M runs**`` is user-controlled. + A model name like ``gpt-4[preview]`` contains ``[`` and ``]`` which Markdown + interprets as a link label; a name shaped like ``[text](url)`` renders as an + actual hyperlink in a PR comment — the primary use case for ``--md``. + + Note: finding *titles* are library-authored strings and are deliberately left + unescaped so they render verbatim (e.g. parentheses and dots in statistical + notation must not be backslash-escaped). """ # Use a model name containing Markdown-special characters rows = ["gpt-4[preview],claude-3_opus"] + ["0.82,0.62"] * 12 @@ -777,14 +781,16 @@ def test_run_level_md_escapes_markdown_special_chars_in_model_name(tmp_path): pf.write_text("\n".join(rows), encoding="utf-8") r = _runner.invoke(_app, ["audit", str(pf), "--run-level", "--md"]) assert r.exit_code in (0, 1) - # The raw unescaped bracket form must NOT appear (would create a link label) - assert "[preview]" not in r.output, ( - "Square brackets in model name must be escaped in --md output; " - f"got:\n{r.output}" - ) - # The backslash-escaped form must be present: gpt\-4\[preview\] + # The subtitle bold line must escape the brackets assert r"\[preview\]" in r.output, ( - f"Expected escaped model name '\\[preview\\]' in --md output; got:\n{r.output}" + f"Expected escaped subtitle '\\[preview\\]' in --md output; got:\n{r.output}" + ) + # Specifically the **subtitle** line must be escaped (first occurrence = subtitle) + bold_line = next( + (line for line in r.output.splitlines() if line.startswith("**")), "" + ) + assert r"\[preview\]" in bold_line, ( + f"Subtitle bold line must contain escaped brackets; got: {bold_line!r}" ) From f7f85f97fed86b84974e8815d229b1dac05db09a Mon Sep 17 00:00:00 2001 From: Maqbool Ahmed Date: Thu, 30 Jul 2026 12:13:32 +0500 Subject: [PATCH 4/6] fix: address CodeRabbit review comments on PR #162 --- src/evaltrust/cli.py | 27 ++++++++++++++++++++++----- src/evaltrust/report/terminal.py | 11 ++++++----- tests/test_two_sample_audit.py | 23 +++++++++++++++-------- 3 files changed, 43 insertions(+), 18 deletions(-) diff --git a/src/evaltrust/cli.py b/src/evaltrust/cli.py index b35ef78..66ada52 100644 --- a/src/evaltrust/cli.py +++ b/src/evaltrust/cli.py @@ -241,7 +241,11 @@ def audit( # Rich colour terminal — model names may contain square brackets that # Rich interprets as markup, so escape before passing to print. from rich.markup import escape as _escape - from .report.terminal import _grouped, _SYMBOL + from rich.text import Text as _Text + from .report.terminal import ( + _display_title, _display_how_detected, + _grouped, _SYMBOL, _bullets, + ) _con = Console() _con.print( f"\n[bold]EvalTrust[/bold] " @@ -251,14 +255,27 @@ def audit( _con.print(f"[bold]{_escape(pillar)}[/bold]") for f in items: sym, color = _SYMBOL[f.status] + _title = _escape(_display_title(f)) _con.print( f" [{color}]{sym}[/{color}] " - + (_escape(f.title) if f.status.value != "skip" - else f"[dim]{_escape(f.title)}[/dim]") + + (_title if f.status is not Status.SKIP + else f"[dim]{_title}[/dim]") ) if explain: - _con.print(f" [dim]{_escape(f.how_detected)}[/dim]") - _con.print() + _con.print( + f" [dim]{_escape(_display_how_detected(f))}[/dim]" + ) + _t = _Text() + _bullets(_t, "What to do", + [f.how_to_fix for f in findings + if f.status in (Status.WARN, Status.FAIL)]) + _bullets(_t, "To check more", + [f.how_to_fix for f in findings if f.status is Status.SKIP], + style="dim") + if _t: + _con.print(_t) + else: + _con.print() if html_out is not None: Path(html_out).write_text( diff --git a/src/evaltrust/report/terminal.py b/src/evaltrust/report/terminal.py index 8232fbe..e97a03a 100644 --- a/src/evaltrust/report/terminal.py +++ b/src/evaltrust/report/terminal.py @@ -408,10 +408,11 @@ def render_markdown_from_parts( When ``verdict_heading`` / ``verdict_summary`` are omitted, that section is skipped, keeping run-level output in sync with the main path for free. - All user-controlled strings (model names embedded in *subtitle*, finding - titles, ``how_to_fix`` text) are Markdown-escaped so that special characters - such as ``[``, ``]``, ``*``, and ``_`` cannot break formatting or create - unintended hyperlinks in PR comments. + *subtitle* is user-controlled (it embeds model names) and is Markdown-escaped + so that characters such as ``[``, ``]``, ``*``, and ``_`` cannot break + formatting or create unintended hyperlinks in PR comments. Finding titles, + pillar names, and ``how_to_fix`` text are library-authored and rendered + verbatim. """ # *subtitle* is user-controlled (contains model names that may hold Markdown # special characters like '[', ']', '*', '_'). Finding titles, pillar names, @@ -463,7 +464,7 @@ def render_markdown(report: AuditReport, explain: bool = False) -> str: others = _others(report) preamble = ( [f"_Comparing the two strongest of {len(report.models_available)}; " - f"others: {', '.join(others)}_"] + f"others: {_md_escape(', '.join(others))}_"] if others else None ) return render_markdown_from_parts( diff --git a/tests/test_two_sample_audit.py b/tests/test_two_sample_audit.py index 6964d17..5683b01 100644 --- a/tests/test_two_sample_audit.py +++ b/tests/test_two_sample_audit.py @@ -748,7 +748,11 @@ def test_run_level_html_escapes_special_characters(tmp_path): def test_run_level_html_explain_adds_detail_section(tmp_path): - """--explain must add a Detail section in the HTML when there are warn/fail findings.""" + """--explain must add a Detail section in the HTML when there are warn/fail findings. + + Note: "detail" appears in the inlined CSS (.detail, .detail h2, .detail-item) regardless + of --explain. Assert on the rendered section markup instead. + """ rows = ["alpha,beta"] + ["0.70,0.70"] * 5 # identical → warn/fail pf = tmp_path / "eq.csv" pf.write_text("\n".join(rows), encoding="utf-8") @@ -756,7 +760,12 @@ def test_run_level_html_explain_adds_detail_section(tmp_path): r = _runner.invoke(_app, ["audit", str(pf), "--run-level", "--html", out, "--explain"]) assert r.exit_code in (0, 1) content = open(out, encoding="utf-8").read() - assert "detail" in content.lower() + # The rendered Detail section heading — distinct from the CSS class names + assert "

Detail

" in content or "

Detail

" in content, ( + "Expected rendered Detail section in HTML with --explain; " + f"got content of length {len(content)}" + ) + assert "detail-item" in content # --------------------------------------------------------------------------- @@ -854,13 +863,11 @@ def test_run_level_plain_ascii_table_maps_both_curly_single_quotes(tmp_path): def test_run_level_plain_ascii_translation_has_ten_distinct_keys(): """Fix (Image 2 - Major): the _ASCII maketrans must cover 10 distinct code points. - A duplicate dict key silently drops one entry. We confirm the table has - exactly 10 keys covering: · – — • ● U+2018 U+2019 U+201C U+201D × + A duplicate dict key silently drops one entry. We import the canonical + _ASCII table directly from terminal.py so that any regression there + (e.g. re-introducing the duplicate key) would be caught by this test. """ - t = str.maketrans({ - "·": "-", "–": "-", "—": "-", "•": "*", "●": "*", - "\u2018": "'", "\u2019": "'", "\u201c": '"', "\u201d": '"', "×": "x", - }) + from evaltrust.report.terminal import _ASCII as t assert len(t) == 10, f"Expected 10 keys in _ASCII maketrans, got {len(t)}" for cp in (0x00B7, 0x2013, 0x2014, 0x2022, 0x25CF, 0x2018, 0x2019, 0x201C, 0x201D, 0x00D7): From 50e7381c8f3b021d890b012502ba4e900148adf2 Mon Sep 17 00:00:00 2001 From: Maqbool Ahmed Date: Fri, 31 Jul 2026 11:43:22 +0500 Subject: [PATCH 5/6] fix: narrow _md_escape to link-breaking chars only; lock with tests --- src/evaltrust/report/terminal.py | 13 ++++-- tests/test_two_sample_audit.py | 80 ++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 5 deletions(-) diff --git a/src/evaltrust/report/terminal.py b/src/evaltrust/report/terminal.py index e97a03a..8e1ecca 100644 --- a/src/evaltrust/report/terminal.py +++ b/src/evaltrust/report/terminal.py @@ -382,14 +382,17 @@ def render_plain(report: AuditReport, explain: bool = False) -> str: def _md_escape(s: str) -> str: - """Backslash-escape Markdown special characters in user-controlled strings. + """Backslash-escape the Markdown characters that break inline formatting + or create unintended links (e.g. ``[text](url)``) in a PR comment. - Characters like ``[``, ``]``, ``*``, ``_``, and backtick can break - formatting or create unintended links (e.g. ``[text](url)``) in a PR - comment — the primary use case for ``--md``. + Escaped: backslash, backtick, ``*``, ``_``, ``[``, ``]``, ``(``, ``)``. + + Deliberately *not* escaped: ``- . # + ! |`` -- these are harmless in the + inline positions where model names appear and escaping them would mangle + ordinary names like ``gpt-4.5`` or ``claude-3-opus``. """ import re as _re - return _re.sub(r'([\\`*_{}\[\]()#+\-.!|])', r'\\\1', str(s)) + return _re.sub(r'([\\`*_\[\](\)])', r'\\\1', str(s)) def render_markdown_from_parts( diff --git a/tests/test_two_sample_audit.py b/tests/test_two_sample_audit.py index 5683b01..2d8d47a 100644 --- a/tests/test_two_sample_audit.py +++ b/tests/test_two_sample_audit.py @@ -801,6 +801,20 @@ def test_run_level_md_escapes_markdown_special_chars_in_subtitle(tmp_path): assert r"\[preview\]" in bold_line, ( f"Subtitle bold line must contain escaped brackets; got: {bold_line!r}" ) + # dash and dot must NOT be escaped — ordinary names like gpt-4.5 must be unchanged + rows2 = ["gpt-4.5,claude-3-opus"] + ["0.82,0.62"] * 12 + pf2 = tmp_path / "plain_models.csv" + pf2.write_text("\n".join(rows2), encoding="utf-8") + r2 = _runner.invoke(_app, ["audit", str(pf2), "--run-level", "--md"]) + bold_line2 = next( + (line for line in r2.output.splitlines() if line.startswith("**")), "" + ) + assert "gpt-4.5" in bold_line2, ( + f"Dash and dot must not be escaped in subtitle; got: {bold_line2!r}" + ) + assert "claude-3-opus" in bold_line2, ( + f"Dash must not be escaped in subtitle; got: {bold_line2!r}" + ) def test_run_level_md_escapes_markdown_special_chars_in_finding_title(tmp_path): @@ -820,6 +834,72 @@ def test_run_level_md_escapes_markdown_special_chars_in_finding_title(tmp_path): ) +def test_main_path_md_subtitle_escapes_brackets_intentionally(tmp_path): + """Owner ask 2: lock main-path subtitle escaping with a test so it is intentional. + + The shared render_markdown_from_parts escapes the subtitle, which also affects + the normal (paired) audit path. A model name like ``gpt-4[preview]`` must + render as ``gpt-4\\[preview\\]`` in the bold subtitle line, not as a Markdown + link label. Ordinary names with dashes and dots (e.g. ``gpt-4.5``) must be + unchanged. + """ + import json as _json + # Build a paired audit JSON with bracket-containing model names + raw = { + "models": ["gpt-4[preview]", "claude-3_opus"], + "examples": [ + {"id": str(i), "scores": {"gpt-4[preview]": 1, "claude-3_opus": 0}} + for i in range(20) + ], + } + pf = tmp_path / "paired.json" + pf.write_text(_json.dumps(raw), encoding="utf-8") + r = _runner.invoke(_app, ["audit", str(pf), "--md"]) + assert r.exit_code in (0, 1) + bold_line = next( + (line for line in r.output.splitlines() if line.startswith("**")), "" + ) + # Brackets must be escaped in the subtitle + assert r"\[preview\]" in bold_line or r"\[preview\]" in r.output, ( + f"Brackets in model name must be escaped in main-path --md subtitle; " + f"got: {bold_line!r}" + ) + # Underscore in model name must also be escaped + assert r"\_opus" in bold_line or r"\_opus" in r.output, ( + f"Underscore in model name must be escaped; got: {bold_line!r}" + ) + + +def test_main_path_md_subtitle_does_not_escape_dash_or_dot(tmp_path): + """Lock: ordinary model names with dashes and dots must not be mangled. + + Confirms the narrowed _md_escape set (Image 2 of owner feedback) so that + names like ``gpt-4.5`` and ``claude-3-haiku`` appear verbatim in the + Markdown subtitle. + """ + import json as _json + raw = { + "models": ["gpt-4.5", "claude-3-haiku"], + "examples": [ + {"id": str(i), "scores": {"gpt-4.5": 1, "claude-3-haiku": 0}} + for i in range(20) + ], + } + pf = tmp_path / "plain_names.json" + pf.write_text(_json.dumps(raw), encoding="utf-8") + r = _runner.invoke(_app, ["audit", str(pf), "--md"]) + assert r.exit_code in (0, 1) + bold_line = next( + (line for line in r.output.splitlines() if line.startswith("**")), "" + ) + assert "gpt-4.5" in bold_line, ( + f"Dot must not be escaped in model name; got: {bold_line!r}" + ) + assert "claude-3-haiku" in bold_line, ( + f"Dash must not be escaped in model name; got: {bold_line!r}" + ) + + def test_run_level_plain_ascii_table_maps_both_curly_single_quotes(tmp_path): """Fix (Image 2 - Major): U+2018 and U+2019 must both be mapped in _ASCII. From 3d8cd9b667dea6b81845e089b4daac13f0da50ec Mon Sep 17 00:00:00 2001 From: Maqbool Ahmed Date: Fri, 31 Jul 2026 12:09:37 +0500 Subject: [PATCH 6/6] test: assert subtitle escaping in bold_line only, not r.output fallback --- tests/test_two_sample_audit.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tests/test_two_sample_audit.py b/tests/test_two_sample_audit.py index 2d8d47a..123cf67 100644 --- a/tests/test_two_sample_audit.py +++ b/tests/test_two_sample_audit.py @@ -859,14 +859,15 @@ def test_main_path_md_subtitle_escapes_brackets_intentionally(tmp_path): bold_line = next( (line for line in r.output.splitlines() if line.startswith("**")), "" ) - # Brackets must be escaped in the subtitle - assert r"\[preview\]" in bold_line or r"\[preview\]" in r.output, ( + # Brackets must be escaped in the subtitle bold line specifically — + # not just anywhere in r.output, which would not verify the subtitle contract. + assert r"\[preview\]" in bold_line, ( f"Brackets in model name must be escaped in main-path --md subtitle; " f"got: {bold_line!r}" ) - # Underscore in model name must also be escaped - assert r"\_opus" in bold_line or r"\_opus" in r.output, ( - f"Underscore in model name must be escaped; got: {bold_line!r}" + # Underscore in model name must also be escaped in the subtitle + assert r"\_opus" in bold_line, ( + f"Underscore in model name must be escaped in subtitle; got: {bold_line!r}" )