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
4 changes: 4 additions & 0 deletions health_agent/capabilities.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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)"
Expand Down
165 changes: 165 additions & 0 deletions heart/checks/release_run.py
Original file line number Diff line number Diff line change
@@ -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))
6 changes: 6 additions & 0 deletions heart/tick.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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')"

Expand Down
68 changes: 68 additions & 0 deletions tests/test_release_run.py
Original file line number Diff line number Diff line change
@@ -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"
Loading