From 424d74559a8db5b749176ef8fc3067673183123e Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 26 Sep 2026 12:03:45 +0100 Subject: [PATCH 1/2] feat(heart): emit the organ-cockpit state.json feed + transition-only push alert PyAutoBrain#416 PR 2 (Heart side): - dashboard.to_state / --state: contract-v1 cockpit feed projected from the same Board as every other surface; ts normalised to ISO-8601 Z; missing snapshot or verdict yields a valid grey feed, never a default green. - heart/alert.py: compare the previously published state.json with the new one and POST one ntfy message only when the status changed; unknown previous never alerts; never raises, always exits 0. - heart-health.yml: render _site/state.json, validate it with the Brain's board/_state.py, push the transition alert (HEART_NTFY_URL secret). Co-Authored-By: Claude Fable 5.1 --- .github/workflows/heart-health.yml | 33 +++++- heart/alert.py | 144 ++++++++++++++++++++++++++ heart/dashboard.py | 103 ++++++++++++++++++- tests/test_alert.py | 158 +++++++++++++++++++++++++++++ tests/test_dashboard.py | 90 ++++++++++++++++ 5 files changed, 525 insertions(+), 3 deletions(-) create mode 100644 heart/alert.py create mode 100644 tests/test_alert.py diff --git a/.github/workflows/heart-health.yml b/.github/workflows/heart-health.yml index 25aca56c..e1caa109 100644 --- a/.github/workflows/heart-health.yml +++ b/.github/workflows/heart-health.yml @@ -31,8 +31,9 @@ name: Heart Health # # Observer boundary: everything here writes ONLY within PyAutoHeart's own repo # (its gh-pages, its README, its [heart-health] issue), the job step summary, or -# the job workspace. No foreign repo, no build/workflow dispatch, no secret -# beyond the auto-provisioned GITHUB_TOKEN. +# the job workspace. No foreign repo, no build/workflow dispatch. The one +# outbound side effect is the transition-only push alert (below) to the private +# ntfy topic named by the optional HEART_NTFY_URL secret. on: schedule: @@ -170,12 +171,23 @@ jobs: # each already carrying its own /bug prompt — without re-deriving # anything (schema v2; the same JSON the Health Agent consumes). PYTHONPATH="$PWD" python -m heart.dashboard --cloud --json > _site/board.json + # The organ-cockpit feed (PyAutoBrain#416, contract v1): one small + # status document the Brain's cockpit polls. Same snapshot, so it can + # never disagree with the page; no snapshot → a valid grey feed. + PYTHONPATH="$PWD" python -m heart.dashboard --cloud --state > _site/state.json PYTHONPATH="$PWD" python -m heart.dashboard --cloud --md > board.md cp board.md _site/dashboard.md # The README carries only the brief strip; the full board lives on # the Pages page (one-tap 📋 fix prompts) and the step summary. PYTHONPATH="$PWD" python -m heart.dashboard --cloud --md-brief > readme_strip.md + - name: Validate the cockpit feed against the Brain contract + run: | + # The contract is owned by the Brain (board/_state.py + + # board/state_schema.json); the Heart only emits it. A feed the + # cockpit can not read must fail this job loudly rather than publish. + python3 PyAutoBrain/board/_state.py _site/state.json + - name: Write the board to the job step summary run: | { @@ -223,6 +235,23 @@ jobs: echo "README health block and timing record unchanged — nothing to commit." fi + # Transition-only push alert. Compare the feed published by the PREVIOUS + # run (live on Pages until this run deploys) with the one just rendered + # and notify only when the status CHANGED (green→red, red→green, + # stale↔green…): a board that stays red pages once, not daily. An unknown + # previous (first run, fetch failure, grey) never alerts. Never fails the + # job. The [heart-health] issue channel below is unchanged. + # HUMAN STEP: create the repo secret HEART_NTFY_URL pointing at a private + # ntfy topic (e.g. https://ntfy.sh/) and subscribe to + # it on your phone; without it this step reports "skipped". + - name: Push a transition alert + env: + HEART_NTFY_URL: ${{ secrets.HEART_NTFY_URL }} + run: | + curl -fsS https://pyautolabs.github.io/PyAutoHeart/state.json -o prev_state.json \ + || echo '{}' > prev_state.json + PYTHONPATH="$PWD" python -m heart.alert --previous prev_state.json --current _site/state.json + - name: Upload Pages artifact uses: actions/upload-pages-artifact@v3 with: diff --git a/heart/alert.py b/heart/alert.py new file mode 100644 index 00000000..cde877ce --- /dev/null +++ b/heart/alert.py @@ -0,0 +1,144 @@ +"""heart/alert.py — a push notification when the Heart's status CHANGES. + +The daily cloud job already keeps a ``[heart-health]`` issue open while +anything is degraded; that is a record, not a tap on the shoulder. This module +is the tap: it compares the previous published cockpit feed (``state.json`` on +Pages, PyAutoBrain#416) with the one just rendered and, only when the status +moved, POSTs one message to an ntfy topic. + +Transition-only by design: a board that stays red for a week pages once, on +the day it went red, and once more on the day it recovers — never daily. Every +change between two KNOWN statuses counts, including stale↔green: an evidence +gap opening or closing is exactly the kind of drift a human wants to hear +about. An unknown previous (first run, a failed fetch, a grey/unparseable +feed) never alerts, so a Pages outage can not fire a false "→ red". + +Observer boundary: this writes nothing; its one side effect is the POST to the +topic named by ``HEART_NTFY_URL`` (a repo secret — a private topic). Absent +that, it reports "skipped" and exits 0; alerting must never fail the job. + +Usage: + python -m heart.alert --previous prev.json --current _site/state.json [--url URL] +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request +from pathlib import Path +from typing import Any + +KNOWN_STATUSES = ("green", "yellow", "red", "stale") +MAX_ITEMS = 5 + + +def transition(previous_status: str | None, new_status: str) -> str | None: + """``"green→red"`` when a known status changed, else None. + + None/unknown previous → None (first run never alerts); same status → None. + A grey/unknown NEW status is also None: "we can not see" is not news. + """ + if previous_status not in KNOWN_STATUSES or new_status not in KNOWN_STATUSES: + return None + if previous_status == new_status: + return None + return f"{previous_status}→{new_status}" + + +def render_message(kind: str, state: dict[str, Any]) -> tuple[str, str, int, str]: + """(title, body, priority, tags) for a transition ``kind``. + + Priority 5 (urgent) when the Heart went red, 3 (default) otherwise. Tags + are plain words (ntfy turns known ones into icons on the phone itself). + """ + prev, _, new = kind.partition("→") + title = f"Heart: {prev.upper()} → {new.upper()}" + lines = [str(state.get("headline") or "")] + for item in list(state.get("items") or [])[:MAX_ITEMS]: + if not isinstance(item, dict): + continue + line = f"- [{item.get('severity', 'info')}] {item.get('text', '')}" + if item.get("url"): + line += f" {item['url']}" + lines.append(line) + if state.get("pages_url"): + lines.append(str(state["pages_url"])) + priority = 5 if new == "red" else 3 + tags = "heart,red" if new == "red" else f"heart,{new}" + return title, "\n".join(lines), priority, tags + + +def _post(url: str, title: str, body: str, priority: int, tags: str, + timeout: float) -> str | None: + """POST one ntfy message; None on success, else a one-line reason. + + Headers must be latin-1, so the title's arrow is sent as ``->``; the body + is UTF-8 and keeps it. + """ + header_title = title.replace("\u2192", "->").encode("ascii", "replace").decode() + req = urllib.request.Request( + url, data=body.encode("utf-8"), method="POST", + headers={"Title": header_title, "Priority": str(priority), "Tags": tags}, + ) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + code = int(getattr(resp, "status", 200) or 200) + except Exception as e: # noqa: BLE001 — alerting must never break the job + return f"{type(e).__name__}: {e}" + return None if code < 400 else f"HTTP {code}" + + +def notify(url: str, title: str, body: str, priority: int, tags: str, + timeout: float = 10) -> bool: + """POST one ntfy message. True on success; prints a notice and returns + False on any error — never raises.""" + reason = _post(url, title, body, priority, tags, timeout) + if reason: + print(f"notice: ntfy POST failed ({reason})") + return reason is None + + +def _load_status(path: str | None) -> tuple[str | None, dict[str, Any]]: + """(status, document) from a feed file; (None, {}) if unreadable/invalid.""" + if not path: + return None, {} + try: + doc = json.loads(Path(path).read_text()) + except (OSError, ValueError): + return None, {} + if not isinstance(doc, dict): + return None, {} + status = doc.get("status") + return (status if isinstance(status, str) else None), doc + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(prog="python -m heart.alert") + ap.add_argument("--previous", help="the previously published state.json") + ap.add_argument("--current", required=True, help="the state.json just rendered") + ap.add_argument("--url", default=None, + help="ntfy topic URL (default: $HEART_NTFY_URL)") + ns = ap.parse_args(argv) + + prev, _ = _load_status(ns.previous) + new, current = _load_status(ns.current) + kind = transition(prev, new or "") + if kind is None: + print(f"alert: none ({prev or 'unknown'}→{new or 'unknown'})") + return 0 + url = ns.url if ns.url is not None else os.environ.get("HEART_NTFY_URL", "") + if not url: + print(f"alert: {kind} skipped (no HEART_NTFY_URL)") + return 0 + title, body, priority, tags = render_message(kind, current) + reason = _post(url, title, body, priority, tags, timeout=10) + print(f"alert: {kind} sent" if reason is None else f"alert: {kind} failed ({reason})") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/heart/dashboard.py b/heart/dashboard.py index 0892966c..ab8645d3 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -2006,6 +2006,95 @@ def badge_endpoint(board: Board) -> dict[str, Any]: } +# --- the organ-cockpit feed (PyAutoBrain#416) -------------------------------- +# One small, schema-pinned document per organ that the Brain's cockpit polls +# (``state.json`` on Pages). It is a PROJECTION of the same Board every other +# surface renders, so the cockpit can never disagree with the Heart's own page; +# the contract (v1) is owned by the Brain (``board/state_schema.json``) and the +# Heart only ever emits it — it never imports the Brain to do so. +STATE_SCHEMA_VERSION = 1 +STATE_STATUSES = ("green", "yellow", "red", "stale", "grey") +_STATE_TEXT_MAX = 160 + + +def _iso_z(ts: Any) -> str: + """``ts`` as ISO-8601 UTC with a ``Z`` suffix, whole seconds. + + The snapshot stamps ``datetime.now(utc).isoformat()`` (``+00:00`` with + microseconds), and older snapshots may be naive; the contract admits only + the ``Z`` form, so both are normalised here. An unparseable or empty stamp + becomes *now* — the moment this feed was written — rather than a non-Z + string the validator would reject (the status already says grey then). + """ + t = _parse_ts(ts) if ts else None + if t is None: + t = datetime.datetime.now(datetime.timezone.utc) + return t.astimezone(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _clip(text: Any, limit: int = _STATE_TEXT_MAX) -> str: + text = " ".join(str(text).split()) + return text if len(text) <= limit else text[: limit - 1] + "\u2026" + + +def grey_state(headline: str = "no Heart snapshot yet") -> dict[str, Any]: + """A valid feed for when there is nothing to project (no cache yet). + + The cockpit must always get a document it can render; grey means "unknown", + never "fine", so an unobserved Heart can not masquerade as green. + """ + return { + "schema_version": STATE_SCHEMA_VERSION, + "organ": "heart", + "repo": "PyAutoHeart", + "status": "grey", + "headline": _clip(headline), + "updated": _iso_z(None), + "pages_url": PAGES_URL, + "items": [], + } + + +def to_state(board: Board) -> dict[str, Any]: + """The organ-cockpit feed (fmt='state'): contract v1 of PyAutoBrain#416. + + status is the readiness verdict (anything outside the four tiers is grey); + the headline is the worst reason, else a clear line worded like the badge; + items are the structured blockers (each keeping its failing-run link and + its copy-for-Claude prompt) so the cockpit acts on them without + re-deriving anything. + """ + status = board.verdict if board.verdict in STATE_STATUSES[:4] else "grey" + # build_board defaults a MISSING verdict to green; a board with no snapshot + # timestamp observed nothing, so the cockpit is told grey, not green. + if status == "grey" or _parse_ts(board.ts) is None: + return grey_state() + first = next((r for rs in (board.red_reasons, board.yellow_reasons, + board.stale_reasons) for r in rs), None) + if first is not None: + headline = str(first) + else: + headline = f"{_VERDICT_WORD.get(status, 'GREEN')} \u00b7 {board.score} \u2014 all clear" + items: list[dict[str, Any]] = [] + for b in board.blockers: + sev = b.get("severity") + items.append({ + "severity": sev if sev in ("red", "yellow") else "info", + "text": _clip(b.get("text", "")), + "url": b.get("run_url") or b.get("repo_url") or None, + "prompt": b.get("prompt"), + }) + # blockers already carry the stale reasons (severity "stale" → info); fall + # back to the flat list only for a verdict whose blockers were not built. + if not any(b.get("severity") == "stale" for b in board.blockers): + items += [{"severity": "info", "text": _clip(r), "url": None, + "prompt": None} for r in board.stale_reasons] + state = grey_state() + state.update(status=status, headline=_clip(headline), + updated=_iso_z(board.ts), items=items) + return state + + def render( snapshot: dict | None, verdict: dict | None, @@ -2035,6 +2124,11 @@ def render( return _render_html(board) if fmt == "json": return json.dumps(to_dict(board), indent=2, sort_keys=True) + if fmt == "state": + if not verdict: + # No readiness verdict computed yet: unknown, never a default green. + return json.dumps(grey_state("no readiness verdict yet"), indent=2) + return json.dumps(to_state(board), indent=2) raise ValueError(f"unknown dashboard fmt: {fmt!r}") @@ -2060,6 +2154,8 @@ def main(argv: list[str] | None = None) -> int: g.add_argument("--html", action="store_true", help="standalone self-contained HTML page") g.add_argument("--json", action="store_true", help="the machine surface (Health Agent / mobile)") g.add_argument("--badge", action="store_true", help="emit a shields.io endpoint-badge JSON") + g.add_argument("--state", action="store_true", + help="emit the organ-cockpit state.json feed (PyAutoBrain#416 contract v1)") ap.add_argument("--cloud", action="store_true", help="mark local-only checks as 'not observed here' (cloud job vantage)") ap.add_argument("--devbox", metavar="PATH", default=None, @@ -2075,7 +2171,8 @@ def main(argv: list[str] | None = None) -> int: fmt = "term" for name, label in (("oneline", "oneline"), ("md", "md"), - ("md_brief", "md-brief"), ("html", "html"), ("json", "json")): + ("md_brief", "md-brief"), ("html", "html"), ("json", "json"), + ("state", "state")): if getattr(ns, name): fmt = label break @@ -2092,6 +2189,10 @@ def main(argv: list[str] | None = None) -> int: print(json.dumps({"schemaVersion": 1, "label": "health", "message": "unknown", "color": "lightgrey"})) return 0 + if fmt == "state": + # The cockpit must always receive a valid document: grey, not a crash. + print(json.dumps(grey_state(), indent=2)) + return 0 print("no cache yet — run `pyauto-heart tick` first", file=sys.stderr) return 2 diff --git a/tests/test_alert.py b/tests/test_alert.py new file mode 100644 index 00000000..bf95788b --- /dev/null +++ b/tests/test_alert.py @@ -0,0 +1,158 @@ +"""tests/test_alert.py — the transition-only push alert (PyAutoBrain#416). + +Hermetic: urllib.request.urlopen is replaced, so nothing leaves the machine. +The load-bearing properties are that a status CHANGE posts exactly once, a +steady status or an unknown previous posts nothing, and no failure mode — +network, missing secret, garbage previous feed — ever raises or exits non-zero. +""" + +from __future__ import annotations + +import json +import urllib.error + +import pytest + +from heart import alert + +ARROW = "→" + + +def _state(status: str, **kw) -> dict: + doc = { + "schema_version": 1, "organ": "heart", "repo": "PyAutoHeart", + "status": status, "headline": kw.get("headline", f"{status} headline"), + "updated": "2026-09-26T05:31:00Z", + "pages_url": "https://pyautolabs.github.io/PyAutoHeart/", + "items": kw.get("items", []), + } + return doc + + +@pytest.mark.parametrize("prev,new,expected", [ + (None, "red", None), + ("green", "green", None), + ("green", "red", f"green{ARROW}red"), + ("red", "green", f"red{ARROW}green"), + ("stale", "green", f"stale{ARROW}green"), + ("green", "stale", f"green{ARROW}stale"), + ("bogus", "red", None), + ("grey", "red", None), + ("green", "grey", None), +]) +def test_transition_table(prev, new, expected): + assert alert.transition(prev, new) == expected + + +def test_render_message_shape(): + items = [{"severity": "red", "text": f"repo{i}: CI failure", + "url": f"https://github.com/o/r{i}", "prompt": "/bug x"} for i in range(8)] + title, body, priority, tags = alert.render_message( + f"green{ARROW}red", _state("red", headline="PyAutoFit: CI failure", items=items)) + assert title == f"Heart: GREEN {ARROW} RED" + assert body.splitlines()[0] == "PyAutoFit: CI failure" + item_lines = [ln for ln in body.splitlines() if ln.startswith("- ")] + assert len(item_lines) == alert.MAX_ITEMS + assert "https://github.com/o/r0" in item_lines[0] + assert priority == 5 + assert tags.isascii() and "red" in tags.split(",") + _, _, p2, _ = alert.render_message(f"red{ARROW}green", _state("green")) + assert p2 == 3 + + +class _Resp: + status = 200 + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + +@pytest.fixture +def posts(monkeypatch): + calls = [] + + def fake_urlopen(req, timeout=None): + calls.append(req) + return _Resp() + + monkeypatch.setattr(alert.urllib.request, "urlopen", fake_urlopen) + monkeypatch.delenv("HEART_NTFY_URL", raising=False) + return calls + + +def _write(tmp_path, name, doc): + p = tmp_path / name + p.write_text(json.dumps(doc) if not isinstance(doc, str) else doc) + return str(p) + + +def test_cli_green_to_red_posts_once(tmp_path, posts, capsys): + prev = _write(tmp_path, "prev.json", _state("green")) + cur = _write(tmp_path, "cur.json", _state("red", headline="PyAutoFit: CI failure")) + rc = alert.main(["--previous", prev, "--current", cur, "--url", "https://ntfy.example/t"]) + assert rc == 0 + assert len(posts) == 1 + req = posts[0] + assert req.get_method() == "POST" + assert req.full_url == "https://ntfy.example/t" + headers = {k.lower(): v for k, v in req.header_items()} + assert headers["title"] == "Heart: GREEN -> RED" + assert headers["priority"] == "5" + assert "red" in headers["tags"] + assert b"PyAutoFit: CI failure" in req.data + assert f"alert: green{ARROW}red sent" in capsys.readouterr().out + + +def test_cli_url_defaults_to_env(tmp_path, posts, monkeypatch): + monkeypatch.setenv("HEART_NTFY_URL", "https://ntfy.example/env") + prev = _write(tmp_path, "prev.json", _state("red")) + cur = _write(tmp_path, "cur.json", _state("green")) + assert alert.main(["--previous", prev, "--current", cur]) == 0 + assert [r.full_url for r in posts] == ["https://ntfy.example/env"] + + +def test_cli_steady_status_posts_nothing(tmp_path, posts, capsys): + prev = _write(tmp_path, "prev.json", _state("green")) + cur = _write(tmp_path, "cur.json", _state("green")) + assert alert.main(["--previous", prev, "--current", cur, "--url", "https://x/t"]) == 0 + assert posts == [] + assert f"alert: none (green{ARROW}green)" in capsys.readouterr().out + + +@pytest.mark.parametrize("prev_doc", [None, "{}", "not json", "[1, 2]"]) +def test_cli_missing_or_invalid_previous_posts_nothing(tmp_path, posts, capsys, prev_doc): + prev = (str(tmp_path / "absent.json") if prev_doc is None + else _write(tmp_path, "prev.json", prev_doc)) + cur = _write(tmp_path, "cur.json", _state("red")) + assert alert.main(["--previous", prev, "--current", cur, "--url", "https://x/t"]) == 0 + assert posts == [] + assert "alert: none" in capsys.readouterr().out + + +def test_cli_without_url_skips(tmp_path, posts, capsys): + prev = _write(tmp_path, "prev.json", _state("green")) + cur = _write(tmp_path, "cur.json", _state("red")) + assert alert.main(["--previous", prev, "--current", cur]) == 0 + assert posts == [] + assert f"alert: green{ARROW}red skipped (no HEART_NTFY_URL)" in capsys.readouterr().out + + +def test_network_error_never_raises(tmp_path, monkeypatch, capsys): + def boom(req, timeout=None): + raise urllib.error.URLError("no route") + + monkeypatch.setattr(alert.urllib.request, "urlopen", boom) + assert alert.notify("https://x/t", "Heart: A", "b", 3, "heart") is False + prev = _write(tmp_path, "prev.json", _state("green")) + cur = _write(tmp_path, "cur.json", _state("red")) + assert alert.main(["--previous", prev, "--current", cur, "--url", "https://x/t"]) == 0 + out = capsys.readouterr().out + assert f"alert: green{ARROW}red failed (URLError" in out + + +def test_notify_success_returns_true(posts): + assert alert.notify("https://x/t", f"Heart: GREEN {ARROW} RED", "body", 5, "heart,red") + assert len(posts) == 1 diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index a9d0f7be..078825b8 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -1694,3 +1694,93 @@ def test_an_unknown_or_absent_unit_cache_state_leaves_the_line_unchanged(): for cache in (None, {}, {"jax": "unknown", "numba": "unknown"}, {"jax": "warm", "numba": None}, "nonsense"): assert _unit_line(cache) == unchanged + + +# --- the organ-cockpit state.json feed (PyAutoBrain#416, contract v1) -------- +STATE_KEYS = {"schema_version", "organ", "repo", "status", "headline", + "updated", "pages_url", "items"} + + +def _assert_valid_state(doc): + assert set(doc) == STATE_KEYS + assert doc["schema_version"] == 1 + assert doc["organ"] == "heart" and doc["repo"] == "PyAutoHeart" + assert doc["status"] in ("green", "yellow", "red", "stale", "grey") + assert doc["updated"].endswith("Z") + datetime.datetime.strptime(doc["updated"], "%Y-%m-%dT%H:%M:%SZ") + assert doc["pages_url"] == dashboard.PAGES_URL + assert isinstance(doc["headline"], str) and doc["headline"] + for item in doc["items"]: + assert item["severity"] in ("red", "yellow", "info") + assert len(item["text"]) <= 160 + assert "url" in item + + +def test_to_state_green_board(): + board = dashboard.build_board(make_snapshot(), make_verdict(), now=FRESH_NOW) + doc = dashboard.to_state(board) + _assert_valid_state(doc) + assert doc["status"] == "green" + assert doc["updated"] == "2026-06-01T00:00:00Z" + assert "100" in doc["headline"] and doc["items"] == [] + + +def test_to_state_red_items_carry_url_and_prompt(): + snap = make_snapshot() + snap["repos"]["PyAutoFit"]["ci_status"].update( + conclusion="failure", url="https://github.com/PyAutoLabs/PyAutoFit/actions/runs/1") + v = make_verdict("red", 40, red_reasons=["PyAutoFit: CI failure " + "x" * 300], + yellow_reasons=["autolens_workspace: open PR"]) + doc = dashboard.to_state(dashboard.build_board(snap, v, now=FRESH_NOW)) + _assert_valid_state(doc) + assert doc["status"] == "red" + assert doc["headline"].startswith("PyAutoFit: CI failure") + red = [i for i in doc["items"] if i["severity"] == "red"] + assert red and red[0]["url"].endswith("/actions/runs/1") + assert red[0]["prompt"].startswith("/bug") + assert any(i["severity"] == "yellow" for i in doc["items"]) + + +def test_to_state_stale_reasons_become_info_items(): + v = make_verdict("stale", 90) + v["stale_reasons"] = ["release validation: evidence expired"] + doc = dashboard.to_state(dashboard.build_board(make_snapshot(), v, now=FRESH_NOW)) + _assert_valid_state(doc) + assert doc["status"] == "stale" + assert doc["headline"] == "release validation: evidence expired" + assert [i["severity"] for i in doc["items"]] == ["info"] + + +def test_to_state_naive_and_microsecond_ts_normalise_to_z(): + board = dashboard.build_board(make_snapshot(ts="2026-06-01T00:00:00.123456"), + make_verdict(), now=FRESH_NOW) + assert dashboard.to_state(board)["updated"] == "2026-06-01T00:00:00Z" + + +def test_to_state_unknown_verdict_is_grey(): + board = dashboard.build_board({"ts": ""}, {}, now=FRESH_NOW) + doc = dashboard.to_state(board) + _assert_valid_state(doc) + assert doc["status"] == "grey" + + +def test_state_fmt_renders_json(): + doc = json.loads(dashboard.render(make_snapshot(), make_verdict(), fmt="state", + now=FRESH_NOW)) + _assert_valid_state(doc) + + +def test_main_no_cache_state_emits_grey(monkeypatch, tmp_path, capsys): + from heart import state + monkeypatch.setattr(state, "HEART_STATE_FILE", tmp_path / "absent.json") + rc = dashboard.main(["--state"]) + doc = json.loads(capsys.readouterr().out) + assert rc == 0 + _assert_valid_state(doc) + assert doc["status"] == "grey" + + +def test_state_fmt_without_verdict_is_grey(): + doc = json.loads(dashboard.render(make_snapshot(), None, fmt="state", now=FRESH_NOW)) + _assert_valid_state(doc) + assert doc["status"] == "grey" From 0c10d3f4627521f6f683f0d55fcaa43d382be65b Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sat, 26 Sep 2026 12:10:41 +0100 Subject: [PATCH 2/2] test(heart): neutral placeholders in the cockpit-feed tests (tenant firewall) PyAutoBrain#416: replace tenant literals (org, library name, Pages host) in tests/test_alert.py and tests/test_dashboard.py with example.org / SomeLib. Co-Authored-By: Claude Fable 5.1 --- tests/test_alert.py | 10 +++++----- tests/test_dashboard.py | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/test_alert.py b/tests/test_alert.py index bf95788b..07500825 100644 --- a/tests/test_alert.py +++ b/tests/test_alert.py @@ -23,7 +23,7 @@ def _state(status: str, **kw) -> dict: "schema_version": 1, "organ": "heart", "repo": "PyAutoHeart", "status": status, "headline": kw.get("headline", f"{status} headline"), "updated": "2026-09-26T05:31:00Z", - "pages_url": "https://pyautolabs.github.io/PyAutoHeart/", + "pages_url": "https://example.org/heart/", "items": kw.get("items", []), } return doc @@ -48,9 +48,9 @@ def test_render_message_shape(): items = [{"severity": "red", "text": f"repo{i}: CI failure", "url": f"https://github.com/o/r{i}", "prompt": "/bug x"} for i in range(8)] title, body, priority, tags = alert.render_message( - f"green{ARROW}red", _state("red", headline="PyAutoFit: CI failure", items=items)) + f"green{ARROW}red", _state("red", headline="SomeLib: CI failure", items=items)) assert title == f"Heart: GREEN {ARROW} RED" - assert body.splitlines()[0] == "PyAutoFit: CI failure" + assert body.splitlines()[0] == "SomeLib: CI failure" item_lines = [ln for ln in body.splitlines() if ln.startswith("- ")] assert len(item_lines) == alert.MAX_ITEMS assert "https://github.com/o/r0" in item_lines[0] @@ -91,7 +91,7 @@ def _write(tmp_path, name, doc): def test_cli_green_to_red_posts_once(tmp_path, posts, capsys): prev = _write(tmp_path, "prev.json", _state("green")) - cur = _write(tmp_path, "cur.json", _state("red", headline="PyAutoFit: CI failure")) + cur = _write(tmp_path, "cur.json", _state("red", headline="SomeLib: CI failure")) rc = alert.main(["--previous", prev, "--current", cur, "--url", "https://ntfy.example/t"]) assert rc == 0 assert len(posts) == 1 @@ -102,7 +102,7 @@ def test_cli_green_to_red_posts_once(tmp_path, posts, capsys): assert headers["title"] == "Heart: GREEN -> RED" assert headers["priority"] == "5" assert "red" in headers["tags"] - assert b"PyAutoFit: CI failure" in req.data + assert b"SomeLib: CI failure" in req.data assert f"alert: green{ARROW}red sent" in capsys.readouterr().out diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 078825b8..285d5281 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -1728,7 +1728,7 @@ def test_to_state_green_board(): def test_to_state_red_items_carry_url_and_prompt(): snap = make_snapshot() snap["repos"]["PyAutoFit"]["ci_status"].update( - conclusion="failure", url="https://github.com/PyAutoLabs/PyAutoFit/actions/runs/1") + conclusion="failure", url="https://example.org/actions/runs/1") v = make_verdict("red", 40, red_reasons=["PyAutoFit: CI failure " + "x" * 300], yellow_reasons=["autolens_workspace: open PR"]) doc = dashboard.to_state(dashboard.build_board(snap, v, now=FRESH_NOW))