hermes-agent/tests/ci/test_live_comment.py
ethernet b9f82ed39f ci: live-updating PR review comment with structured job statuses
Replace the static comment-pending + comment-results two-job pattern
with a live-updating comment system that polls the GitHub Actions API
every 15s, re-assembles the review comment from whatever results are
available, and upserts it via the <!-- hermes-ci-review-bot --> marker.
The comment updates in real time as each job finishes — no waiting for
the full pipeline.

Every CI job that wants to appear in the review comment emits a
review_status output — a JSON array of objects, each with a source
and a results array:

    [
      {
        "source": "review-label-gate",
        "results": [
          {"kind": "action_required", "title": "...", "summary": "...",
           "how_to_fix": "..."},
          {"kind": "info", "title": "...", "summary": "..."}
        ]
      },
      {
        "source": "ci timing",
        "results": [
          {"kind": "warning", "title": "CI timings", "summary": "...",
           "detail": "...", "link": "..."}
        ]
      }
    ]

One job can emit multiple results of different kinds. The source field
is used to exclude the corresponding job from the synthesized error
list (case-insensitive, hyphen-normalized matching against GitHub
Actions job display names).

| job                        | source                   | kind (on failure)         | section              |
|----------------------------|--------------------------|---------------------------|----------------------|
| review-labels              | review label gate        | action_required / info    | Action required      |
| lockfile-diff              | lockfile-diff            | action_required           | Action required      |
| ci-timings                 | ci timing                | warning / info            | Warnings             |
| supply-chain scan          | supply chain             | error / (none)            | Job failures         |
| supply-chain dep-bounds    | supply chain             | action_required / (none)  | Action required      |
| osv-scanner                | osv scan                 | warning / (none)          | Warnings             |
| uv-lockfile-check          | uv.lock check            | action_required / (none)  | Action required      |
| history-check              | unrelated histories      | action_required           | Action required      |
| contributor-check          | contributor attribution  | action_required           | Action required      |

Jobs that find nothing emit [] (empty array) — no noise info items.

A single comment-live job polls the GitHub Actions API every 15s,
classifies jobs into (completed, pending), assembles the comment, and
upserts it. Merges review_status outputs from all needs jobs via
toJSON(needs.*.outputs.review_status), and downloads the ci-timings
artifact when it becomes available. Shows commit SHA + message below
the header.

The assembler has ZERO job-specific knowledge. It just:
1. collect_from_statuses() — flattens all nested status objects into ReviewItems
2. collect_failed_jobs() — synthesizes errors for failed jobs with no declared status
3. _attach_job_urls() — fills in per-job log links for ALL items
4. render_comment() — groups by severity, renders with group headers

Each item shows links inline next to the title: View report (job-emitted
URL) and View job (auto-attached logs link). Each info item is its own
collapsible <details> block.

    # ૮ >ﻌ< ა ci review

    running on abc1234 — commit message first line

    ##  Job failures
    ### {title} · [View job](url)
    {summary}

    ## ⚠️ Action required
    ### {title} · [View job](url)
    {summary}
    **How to fix:**
    {how_to_fix}

    ## ⚠️ Warnings
    ### {title} · [View report](url) · [View job](url)
    {summary}
    {detail}

    <details><summary>{title}</summary>
    {content}
    </details>

    Still running 3 jobs: ci-timings, docker

- test_assemble_review_comment.py (48 tests): collect_from_statuses,
  collect_failed_jobs with exclude_sources, _attach_job_urls,
  render_comment (group headers, inline links, commit info, per-item
  details, pending footer), assemble integration
- test_live_comment.py (16 tests): classify_jobs pure function
- test_timings_report.py (10 tests): generate_review_status nested format
- test_lockfile_diff.py (6 tests)
- test_classify_changes.py (32 tests, pre-existing)
2026-07-20 16:48:25 -04:00

162 lines
5.6 KiB
Python

"""Tests for scripts/ci/live_comment.py — classify_jobs().
The poller's core logic is a pure function: take raw GitHub API job dicts
and split them into (completed, pending). The API wrapper + polling loop
are tested via E2E in CI, not here.
"""
from __future__ import annotations
import importlib.util
import sys
from pathlib import Path
_PATH = Path(__file__).resolve().parents[2] / "scripts" / "ci" / "live_comment.py"
_spec = importlib.util.spec_from_file_location("live_comment", _PATH)
if _spec is None or _spec.loader is None:
raise ImportError("Failed to load live_comment.py")
_mod = importlib.util.module_from_spec(_spec)
sys.modules["live_comment"] = _mod
_spec.loader.exec_module(_mod)
def _job(name: str, status: str, conclusion: str | None = None, workflow: str = "") -> dict:
"""Build a raw API job dict."""
j = {"name": name, "status": status, "conclusion": conclusion}
if workflow:
j["_workflow_name"] = workflow
return j
def test_classify_empty():
completed, pending, job_urls = _mod.classify_jobs([])
assert completed == {}
assert pending == []
assert job_urls == {}
def test_classify_success():
jobs = [_job("Python tests", "completed", "success")]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {"Python tests": "success"}
assert pending == []
def test_classify_failure():
jobs = [_job("Python tests", "completed", "failure")]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {"Python tests": "failure"}
assert pending == []
def test_classify_skipped():
jobs = [_job("Python tests", "completed", "skipped")]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {"Python tests": "skipped"}
assert pending == []
def test_classify_in_progress():
jobs = [_job("Python tests", "in_progress", None)]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {}
assert pending == ["Python tests"]
def test_classify_queued():
jobs = [_job("Python tests", "queued", None)]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {}
assert pending == ["Python tests"]
def test_classify_waiting():
jobs = [_job("Python tests", "waiting", None)]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {}
assert pending == ["Python tests"]
def test_classify_mixed():
jobs = [
_job("Python tests", "completed", "success"),
_job("Python lints", "completed", "failure"),
_job("JS & TS checks", "in_progress", None),
_job("Desktop E2E", "queued", None),
]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {"Python tests": "success", "Python lints": "failure"}
assert set(pending) == {"JS & TS checks", "Desktop E2E"}
def test_classify_infra_jobs_excluded():
"""Infra jobs (detect, all-checks-pass, comment-live) are never shown."""
jobs = [
_job("detect", "completed", "success"),
_job("Detect affected areas", "completed", "success"),
_job("all-checks-pass", "completed", "success"),
_job("All required checks pass", "completed", "success"),
_job("comment-live", "in_progress", None),
_job("CI review comment (live)", "in_progress", None),
_job("Python tests", "completed", "success"),
]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {"Python tests": "success"}
assert pending == []
def test_classify_sub_workflow_jobs_prefixed():
"""Sub-workflow jobs get 'Workflow / job' display names."""
jobs = [
_job("test", "completed", "success", workflow="Tests"),
_job("check", "in_progress", None, workflow="JS Tests"),
]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert "Tests / test" in completed
assert completed["Tests / test"] == "success"
assert "JS Tests / check" in pending
def test_classify_captures_html_url():
"""The poller captures html_url per job for per-job log links."""
jobs = [
{**_job("Python tests", "completed", "failure"),
"html_url": "https://github.com/repo/actions/runs/1/job/2"},
_job("Python lints", "completed", "success"),
]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert job_urls["Python tests"] == "https://github.com/repo/actions/runs/1/job/2"
# Jobs without html_url are simply absent from the dict
assert "Python lints" not in job_urls
def test_classify_cancelled_treated_as_skipped():
jobs = [_job("Python tests", "completed", "cancelled")]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {"Python tests": "skipped"}
def test_classify_timed_out_treated_as_failure():
jobs = [_job("Python tests", "completed", "timed_out")]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {"Python tests": "failure"}
def test_classify_neutral_treated_as_skipped():
jobs = [_job("Python tests", "completed", "neutral")]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {"Python tests": "skipped"}
def test_classify_action_required_treated_as_skipped():
jobs = [_job("Python tests", "completed", "action_required")]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {"Python tests": "skipped"}
def test_classify_unknown_status_skipped():
"""Unknown status values are silently ignored, not crashed on."""
jobs = [_job("weird-job", "unknown_status", None)]
completed, pending, job_urls = _mod.classify_jobs(jobs)
assert completed == {}
assert pending == []