From e76a3fcbb51ec9bea216bd3d77d2a3e094e5d9f1 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 30 Jul 2026 15:35:47 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20release-channel=20freshness=20=E2=80=94?= =?UTF-8?q?=20validation=5Freport=20self-refreshes=20from=20release-integr?= =?UTF-8?q?ate=20runs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit validation_report.json only refreshed on a manual local ingest (the nightly's own ingest is ephemeral CI state), so 'release validation stale: source moved since rehearsal' was chronic between releases (PyAutoHeart#128). heart/checks/release_run.py mirrors test_run.py's cached-artifact pattern: the tick reads the latest release-integrate.yml run, downloads its release-stage-report once per run id, and — when the completed cloud run is newer than the ingested report — refreshes validation_report through the existing heart.validate.run() ingest path (stage reports embed their own commit_shas/testpypi_version). A fresher local ingest is never regressed; an already-ingested run id never re-downloads; a FAILED rehearsal ingests too (release_ready=false is evidence: readiness shows 'release validation FAILED (stage integrate)' instead of week-old STALE, self-clearing on the next green night). decide() is pure/no-network; gh callables live only in the tick/CLI entrypoint. Wired into tick.sh beside test_run. Live proof: the real failed rehearsal artifact (run 30516167217) downloads + ingests to release_ready=false and readiness computes exactly 'release validation FAILED (stage integrate)' in a sandbox state dir; the live tick on the new channel honestly reports no-runs until tonight's nightly. Suite: 337 passed (9 new). Co-Authored-By: Claude Fable 5 --- health_agent/capabilities.yaml | 4 + heart/checks/release_run.py | 165 +++++++++++++++++++++++++++++++++ heart/tick.sh | 6 ++ tests/test_release_run.py | 68 ++++++++++++++ 4 files changed, 243 insertions(+) create mode 100644 heart/checks/release_run.py create mode 100644 tests/test_release_run.py diff --git a/health_agent/capabilities.yaml b/health_agent/capabilities.yaml index 257b1fd2..a9a72d60 100644 --- a/health_agent/capabilities.yaml +++ b/health_agent/capabilities.yaml @@ -60,6 +60,10 @@ continuous_checks: impl: heart/checks/open_prs.sh measures: "open PR count + max age per repo" gate_role: "YELLOW if an open PR is >= 7 days old" + - id: release_run + impl: heart/checks/release_run.py + measures: "latest release-integrate.yml run vs the ingested validation_report (per-run-id cached artifact refresh)" + gate_role: "keeps the release-validation leg fresh; verdict impact flows through validation_report" - id: worktree_drift impl: heart/checks/worktree_drift.py measures: "worktree dirs (wt root + claimed paths) vs PyAutoMind active.md/parked.md (orphan/parked/missing/dirty/canonical-dirty)" diff --git a/heart/checks/release_run.py b/heart/checks/release_run.py new file mode 100644 index 00000000..0f62ae5f --- /dev/null +++ b/heart/checks/release_run.py @@ -0,0 +1,165 @@ +"""heart/checks/release_run.py — dev-box freshness for the release channel. + +``validation_report.json`` historically refreshed only on a manual local +``pyauto-heart validate --ingest``: the nightly driver ingests into an +ephemeral CI state dir, so after every library merge the dev box reported +``release validation stale: source moved since rehearsal`` until someone +manually ingested — even though a fresh rehearsal ran (or failed, with +evidence) last night on the ``release-integrate.yml`` channel. + +This check mirrors ``test_run.py``'s cached-artifact pattern: the tick reads +the channel's latest run (conclusion + id via ``gh run list``), downloads its +``release-stage-report`` artifact once per run id, and — when the cloud run is +COMPLETED and NEWER than the ingested report — refreshes ``validation_report`` +through the existing ``heart.validate.run()`` ingest path (stage reports embed +their own ``commit_shas`` / ``testpypi_version``). Rules: + +- a fresher local ingest is never regressed (report ts vs run creation time); +- a run already ingested (sidecar-cached id) is never re-downloaded; +- a FAILED rehearsal ingests too: ``release_ready: false`` is evidence, not an + evidence gap — readiness then shows the accurate ``release validation + FAILED (stage integrate)`` instead of week-old STALE, and it self-clears on + the next green night. + +``decide()`` is pure and no-network: the gh-backed callables are injected only +by the ``main()`` tick/CLI entrypoint (the #83/#120 discipline). +""" + +from __future__ import annotations + +import datetime +import json +import os +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Any, Callable + +HEART_HOME = Path(__file__).resolve().parents[2] +HEART_STATE_DIR = Path(os.environ.get("HEART_STATE_DIR") or Path.home() / ".pyauto-heart") + +RELEASE_REPO = os.environ.get("GITHUB_REPOSITORY", "PyAutoLabs/PyAutoHeart") +RELEASE_WORKFLOW = "release-integrate.yml" +STAGE_ARTIFACT = "release-stage-report" +SIDECAR = HEART_STATE_DIR / "release_run.json" + + +def _read_json(path: Path) -> Any: + try: + return json.loads(path.read_text()) + except (OSError, json.JSONDecodeError): + return None + + +def _parse_ts(ts: Any) -> datetime.datetime | None: + try: + t = datetime.datetime.fromisoformat(str(ts).replace("Z", "+00:00")) + except (TypeError, ValueError): + return None + return t.replace(tzinfo=datetime.timezone.utc) if t.tzinfo is None else t + + +def latest_run() -> dict[str, Any] | None: + """Latest release-integrate run via ``gh``; None if unavailable/no runs.""" + try: + out = subprocess.run( + ["gh", "run", "list", "--repo", RELEASE_REPO, + "--workflow", RELEASE_WORKFLOW, "--limit", "1", + "--json", "conclusion,status,createdAt,databaseId,url"], + capture_output=True, text=True, timeout=30, + ) + runs = json.loads(out.stdout or "[]") + except Exception: + return None + return runs[0] if runs else None + + +def download_stage_report(run_id: Any, dest: Path) -> Path | None: + """Fetch the run's stage-report artifact into ``dest``; None on any failure.""" + try: + res = subprocess.run( + ["gh", "run", "download", str(run_id), "--repo", RELEASE_REPO, + "-n", STAGE_ARTIFACT, "-D", str(dest)], + capture_output=True, text=True, timeout=60, + ) + except Exception: + return None + report = dest / "stage_report.json" + return report if res.returncode == 0 and report.is_file() else None + + +def decide( + current_report: dict[str, Any] | None, + sidecar: dict[str, Any] | None, + run_record: dict[str, Any] | None, +) -> dict[str, Any]: + """Pure refresh decision: {action, run_id?, created?, url?}. + + Actions: no-runs · in-progress · cached (already ingested) · + local-fresher (never regress a newer local ingest) · ingest. + """ + if not run_record: + return {"action": "no-runs"} + run_id = run_record.get("databaseId") or run_record.get("id") + out = { + "run_id": run_id, + "conclusion": run_record.get("conclusion"), + "created": run_record.get("createdAt") or run_record.get("created_at"), + "url": run_record.get("url") or run_record.get("html_url"), + } + if run_record.get("status") != "completed": + return {**out, "action": "in-progress"} + if isinstance(sidecar, dict) and sidecar.get("last_ingested_run_id") == run_id: + return {**out, "action": "cached"} + report_ts = _parse_ts((current_report or {}).get("ts")) + created = _parse_ts(out["created"]) + if report_ts is not None and created is not None and report_ts >= created: + return {**out, "action": "local-fresher"} + return {**out, "action": "ingest"} + + +def main(argv: list[str] | None = None) -> int: + sys.path.insert(0, str(HEART_HOME)) + from heart import state, validate + + decision = decide(validate.load(), _read_json(SIDECAR), latest_run()) + action = decision.get("action") + ingested: dict[str, Any] | None = None + + if action == "ingest": + with tempfile.TemporaryDirectory() as td: + report_path = download_stage_report(decision.get("run_id"), Path(td)) + if report_path is None: + action = decision["action"] = "artifact-unavailable" + else: + ingested = validate.run([td]) + # Record the ingest so the tick never re-downloads this run. + state.atomic_write_json(SIDECAR, { + "last_ingested_run_id": decision.get("run_id"), + "ingested_ts": ingested.get("ts"), + "release_ready": ingested.get("release_ready"), + "run_url": decision.get("url"), + }) + + from heart.heart_color import c_fail, c_info, c_meta, c_ok, c_warn, glyph_fail, glyph_ok, glyph_warn + + label_id = decision.get("run_id", "?") + if action == "ingest": + ready = (ingested or {}).get("release_ready") + if ready is True: + glyph, label = glyph_ok(), c_ok(f"rehearsal ingested (run {label_id}: pass)") + else: + glyph, label = glyph_fail(), c_fail(f"rehearsal ingested (run {label_id}: FAILED)") + elif action in ("cached", "local-fresher"): + glyph, label = glyph_ok(), c_ok(f"validation report current ({action})") + elif action == "in-progress": + glyph, label = glyph_warn(), c_warn(f"rehearsal run {label_id} in progress") + else: # no-runs / artifact-unavailable + glyph, label = glyph_warn(), c_warn(action or "unknown") + print(f"{glyph} {c_info('release_run')} {label} {c_meta(str(decision.get('url') or ''))}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/heart/tick.sh b/heart/tick.sh index d995e2d7..5ff2a03c 100755 --- a/heart/tick.sh +++ b/heart/tick.sh @@ -39,6 +39,12 @@ fi # when there is no local report.json (the mobile case the old guard broke). PYTHONPATH="$HEART_HOME" python3 -m heart.checks.test_run || heart_log WARN "$(c_warn 'test_run failed')" +# Python: release-channel freshness — refreshes validation_report from the +# latest release-integrate.yml run's stage report (cached per run id), so the +# rehearsal verdict self-heals nightly instead of going stale until a manual +# local ingest. +PYTHONPATH="$HEART_HOME" python3 -m heart.checks.release_run || heart_log WARN "$(c_warn 'release_run failed')" + # Python: workspace-vs-library version skew (cheap file reads; no heavy imports). PYTHONPATH="$HEART_HOME" python3 -m heart.checks.version_skew || heart_log WARN "$(c_warn 'version_skew failed')" diff --git a/tests/test_release_run.py b/tests/test_release_run.py new file mode 100644 index 00000000..9a09faa4 --- /dev/null +++ b/tests/test_release_run.py @@ -0,0 +1,68 @@ +"""tests/test_release_run.py — the release-channel freshness decision. + +`decide()` is the pure core (PyAutoHeart#128): given the persisted +validation_report, the per-run-id sidecar cache, and the latest cloud run +record, it must refresh exactly when the completed cloud run is newer than the +ingested evidence — never regressing a fresher local ingest, never +re-downloading an already-ingested run, and treating a failed rehearsal as +evidence to ingest, not a gap to skip. +""" + +from __future__ import annotations + +from heart.checks import release_run as rr + + +def _run(run_id=7, status="completed", conclusion="success", + created="2026-07-30T05:16:28Z"): + return {"databaseId": run_id, "status": status, "conclusion": conclusion, + "createdAt": created, "url": f"https://example/runs/{run_id}"} + + +def test_no_runs(): + assert rr.decide(None, None, None)["action"] == "no-runs" + + +def test_in_progress_never_ingests(): + d = rr.decide(None, None, _run(status="in_progress", conclusion=None)) + assert d["action"] == "in-progress" + + +def test_fresh_completed_run_with_no_local_report_ingests(): + d = rr.decide(None, None, _run()) + assert d["action"] == "ingest" and d["run_id"] == 7 + + +def test_failed_rehearsal_still_ingests(): + # release_ready=false is evidence, not an evidence gap. + d = rr.decide(None, None, _run(conclusion="failure")) + assert d["action"] == "ingest" + + +def test_already_ingested_run_is_cached(): + d = rr.decide(None, {"last_ingested_run_id": 7}, _run()) + assert d["action"] == "cached" + + +def test_fresher_local_ingest_is_never_regressed(): + current = {"ts": "2026-07-30T17:53:15+00:00"} # local ingest AFTER the run + d = rr.decide(current, None, _run(created="2026-07-30T05:16:28Z")) + assert d["action"] == "local-fresher" + + +def test_newer_cloud_run_beats_older_local_report(): + current = {"ts": "2026-07-29T17:53:15+00:00"} + d = rr.decide(current, None, _run(created="2026-07-30T05:16:28Z")) + assert d["action"] == "ingest" + + +def test_unparseable_timestamps_fail_toward_ingest(): + # Freshness unknown → refresh (ingest is idempotent; staleness is the harm). + d = rr.decide({"ts": "not-a-time"}, None, _run()) + assert d["action"] == "ingest" + + +def test_new_run_id_supersedes_old_cache(): + d = rr.decide({"ts": "2026-07-29T00:00:00+00:00"}, + {"last_ingested_run_id": 6}, _run(run_id=7)) + assert d["action"] == "ingest"