Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions .github/workflows/heart-health.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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: |
{
Expand Down Expand Up @@ -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/<unguessable-topic>) 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:
Expand Down
144 changes: 144 additions & 0 deletions heart/alert.py
Original file line number Diff line number Diff line change
@@ -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())
103 changes: 102 additions & 1 deletion heart/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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}")


Expand All @@ -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,
Expand All @@ -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
Expand All @@ -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

Expand Down
Loading
Loading