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
9 changes: 7 additions & 2 deletions heart/_common.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
# HEART_HOME — repo root (PyAutoHeart/)
# HEART_STATE_DIR — ~/.pyauto-heart/ (created on first call)
# HEART_PER_REPO_DIR — per-repo JSON caches
# HEART_CLOUD_CI_DIR — agent/MCP-supplied CI run payloads (no-gh sessions)
# HEART_TIMINGS_DIR — rolling script timing baselines
# HEART_LOG_DIR — daemon log files
# HEART_PID_FILE — daemon pidfile
Expand All @@ -32,18 +33,22 @@ export PYAUTO_ROOT

HEART_STATE_DIR="${HEART_STATE_DIR:-$HOME/.pyauto-heart}"
HEART_PER_REPO_DIR="$HEART_STATE_DIR/per-repo"
# Agent/MCP-supplied CI run payloads, one per repo — the mobile/cloud path
# for a session with no `gh`. See heart/checks/ci_status.py.
HEART_CLOUD_CI_DIR="$HEART_STATE_DIR/cloud_ci"
HEART_TIMINGS_DIR="$HEART_STATE_DIR/timings"
HEART_LOG_DIR="$HEART_STATE_DIR/logs"
HEART_PID_FILE="$HEART_STATE_DIR/heart.pid"
HEART_STATE_FILE="$HEART_STATE_DIR/state.json"
HEART_TICK_LOG="$HEART_LOG_DIR/heart.log"
export HEART_STATE_DIR HEART_PER_REPO_DIR HEART_TIMINGS_DIR HEART_LOG_DIR
export HEART_STATE_DIR HEART_PER_REPO_DIR HEART_CLOUD_CI_DIR HEART_TIMINGS_DIR HEART_LOG_DIR
export HEART_PID_FILE HEART_STATE_FILE HEART_TICK_LOG

source "$HEART_HOME/heart/_color.sh"

heart_state_dir() {
mkdir -p "$HEART_STATE_DIR" "$HEART_PER_REPO_DIR" "$HEART_TIMINGS_DIR" "$HEART_LOG_DIR"
mkdir -p "$HEART_STATE_DIR" "$HEART_PER_REPO_DIR" "$HEART_CLOUD_CI_DIR" \
"$HEART_TIMINGS_DIR" "$HEART_LOG_DIR"
}

# Live-mode detection. Live (clear-screen, redraw, countdown) when stdout is a
Expand Down
108 changes: 106 additions & 2 deletions heart/checks/ci_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"conclusion": "failure", # rolled-up over required workflows (back-compat)
"status": "completed", # rolled-up status (back-compat)
"error": "", # non-empty => the runs fetch itself failed
"source": "gh", # "gh" (live fetch) | "cloud" (agent/MCP-supplied)
"sha": "abc1234", # short HEAD sha (back-compat with old sidecar)
"workflow": "Smoke Tests", # the failing/representative workflow, for the summary
"url": "https://github.com/.../actions/runs/123",
Expand All @@ -60,14 +61,23 @@
from __future__ import annotations

import argparse
import datetime
import json
import os
import sys
from pathlib import Path
from typing import Any

HEART_HOME = Path(__file__).resolve().parents[2]
CONFIG_PATH = HEART_HOME / "config" / "repos.yaml"

# How old an agent/MCP-supplied runs payload may be before it stops counting.
# A CI conclusion is a claim about *now*; past this bound the honest answer is
# the same "unavailable" the failed fetch already produced, never a stale green.
# One hour: long enough to span a mobile session's refresh-then-tick, short
# enough that nobody reads yesterday's CI as today's.
CLOUD_RUNS_MAX_AGE_S = int(os.environ.get("HEART_CLOUD_CI_MAX_AGE", "3600"))

# Conclusions that count as a hard failure for gating. Deliberately a denylist
# of genuine failures rather than "anything != success": ``skipped`` /
# ``neutral`` / ``stale`` are non-events (e.g. a path-filtered job) and must not
Expand Down Expand Up @@ -104,6 +114,70 @@ def required_for(group: str, config_path: Path | str = CONFIG_PATH) -> list[str]
return load_required_workflows(config_path).get(group, [])


def cloud_runs(
path: Path | str,
max_age_s: int = CLOUD_RUNS_MAX_AGE_S,
now: datetime.datetime | None = None,
) -> tuple[Any | None, str]:
"""Read an agent/MCP-supplied runs payload, or explain why it was rejected.

The mobile/cloud path. There is no ``gh`` in a Claude web/mobile session, so
the live fetch in ``ci_status.sh`` fails outright; Brain queries the runs via
its MCP GitHub tools and drops the REST response here instead. This is the
same hand-off ``test_run.py`` uses for the workspace-validation verdict — the
MCP ``list_workflow_runs`` response is already the exact
``{"workflow_runs": [...]}`` shape :func:`normalize_runs` expects, so nothing
is reshaped on the way in.

File shape (``ts`` optional; the file's mtime is used when it is absent)::

{"ts": "2026-08-25T12:00:00+00:00", "runs": {"workflow_runs": [...]}}

Returns ``(runs, "")`` when usable, else ``(None, reason)``. Fails closed at
every step: unreadable, malformed, undated *and* un-stat-able, or simply too
old all return ``None`` with the reason, so the caller reports "we could not
ask" rather than dressing up stale evidence as current.
"""
p = Path(path)
try:
data = json.loads(p.read_text())
except FileNotFoundError:
return None, "no cloud runs payload"
except (OSError, json.JSONDecodeError, ValueError):
return None, "cloud runs payload unreadable"

if not isinstance(data, dict):
return None, "cloud runs payload malformed"

runs = data.get("runs", data)
if not isinstance(runs, (dict, list)) or not runs:
return None, "cloud runs payload empty"

stamped = data.get("ts")
ts: datetime.datetime | None = None
if stamped:
try:
ts = datetime.datetime.fromisoformat(str(stamped).replace("Z", "+00:00"))
except ValueError:
ts = None
if ts is None:
try:
ts = datetime.datetime.fromtimestamp(
p.stat().st_mtime, datetime.timezone.utc
)
except OSError:
return None, "cloud runs payload undated"
if ts.tzinfo is None:
ts = ts.replace(tzinfo=datetime.timezone.utc)

now = now or datetime.datetime.now(datetime.timezone.utc)
age = (now - ts).total_seconds()
if age > max_age_s:
return None, f"cloud runs payload stale ({int(age)}s > {max_age_s}s)"

return runs, ""


def normalize_runs(payload: Any, branch: str = "main") -> list[dict[str, Any]]:
"""Coerce a runs payload into the internal run shape, filtered to ``branch``.

Expand Down Expand Up @@ -246,13 +320,19 @@ def build_sidecar(
ts: str,
config_path: Path | str = CONFIG_PATH,
error: str = "",
source: str = "gh",
) -> dict[str, Any]:
"""Construct the full ci_status sidecar dict for one repo.

``error`` is the reason the runs fetch failed. When set, the sidecar
reports ``status="unavailable"`` rather than the ``in_progress`` that an
empty run list would otherwise roll up to, so "we could not ask" is
readable as itself instead of impersonating "CI is still running".

``source`` records where the runs came from — ``"gh"`` for the live fetch,
``"cloud"`` for an agent/MCP-supplied payload. Provenance is part of the
evidence, not decoration: a reader must be able to tell a conclusion Heart
fetched itself from one an agent handed it.
"""
required = required_for(group, config_path)
latest = latest_per_workflow(normalize_runs(runs))
Expand All @@ -278,6 +358,7 @@ def build_sidecar(
"status": roll["status"],
"workflow": roll["workflow"],
"error": error,
"source": source,
"url": (rep or {}).get("url", ""),
"workflows": workflows,
"ts": ts,
Expand Down Expand Up @@ -321,8 +402,9 @@ def write_and_summarise(
out_path: Path,
config_path: Path | str = CONFIG_PATH,
error: str = "",
source: str = "gh",
) -> dict[str, Any]:
sidecar = build_sidecar(name, group, runs, head_sha, ts, config_path, error)
sidecar = build_sidecar(name, group, runs, head_sha, ts, config_path, error, source)
sys.path.insert(0, str(HEART_HOME))
from heart import state

Expand All @@ -342,6 +424,11 @@ def main(argv: list[str] | None = None) -> int:
default="",
help="reason the runs fetch failed; recorded instead of a bogus pending state",
)
ap.add_argument(
"--cloud-runs",
default="",
help="agent/MCP-supplied runs payload, consulted only when the live fetch failed",
)
ns = ap.parse_args(argv)

error = ns.fetch_error
Expand All @@ -353,8 +440,25 @@ def main(argv: list[str] | None = None) -> int:
runs = []
error = error or "runs payload was not valid JSON"

# The live fetch is authoritative and is never second-guessed: the drop
# point is consulted only once `gh` has already failed (or is absent, which
# is the same thing from here). That ordering is what keeps the dev box's
# behaviour byte-for-byte unchanged — there, `error` is empty and this never
# runs — while giving the no-gh session real evidence instead of a blank.
source = "gh"
if error and ns.cloud_runs:
supplied, reason = cloud_runs(ns.cloud_runs)
if supplied is not None:
runs, error, source = supplied, "", "cloud"
else:
# Keep the original fetch failure as the headline and append why the
# fallback did not save it, so "no gh AND the payload was stale" is
# one readable string rather than a silently unchanged error.
error = f"{error} ({reason})"

sidecar = write_and_summarise(
ns.name, ns.group, runs, ns.head_sha, ns.ts, Path(ns.out), error=error
ns.name, ns.group, runs, ns.head_sha, ns.ts, Path(ns.out),
error=error, source=source,
)
print(summary_line(sidecar))
return 0
Expand Down
61 changes: 58 additions & 3 deletions heart/checks/ci_status.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
# heart/checks/ci_status.sh — per-required-workflow CI conclusions on main HEAD.
#
# For each polled repo this fetches, via `gh api` (cheap metadata reads only):
# 1. the `main` HEAD commit sha (`gh api .../commits/main`)
# 1. the `main` HEAD commit sha (`gh api .../commits/main`, falling back to
# an anonymous `git ls-remote` — see `ci_head_sha` below)
# 2. the recent workflow runs on `main` (`gh api .../actions/runs?branch=main`)
# and pipes the runs JSON to `heart.checks.ci_status`, which picks the latest
# run of each workflow, rolls the *required* workflows for the repo's group
Expand Down Expand Up @@ -35,6 +36,59 @@ source "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../_common.sh"
# Recent runs on main, newest first. `per_page=30` mirrors the old --limit 30.
_CI_RUNS_PATH="actions/runs?branch=main&per_page=30&exclude_pull_requests=true"

# Seconds any single `git ls-remote` HEAD-sha fallback may take. The repos are
# scanned in parallel, so the worst case this adds to a tick is one timeout, not
# one per repo — but it is capped anyway so a stalled network can never eat the
# <30s budget.
_CI_LS_REMOTE_TIMEOUT="${HEART_LS_REMOTE_TIMEOUT:-10}"

# Which binary bounds that fallback. `timeout` is coreutils: Linux has it, and
# macOS has it only as `gtimeout`, and only when coreutils is installed. When
# neither exists the fallback is skipped entirely rather than run unbounded — a
# stalled `ls-remote` inside the tick is a worse failure than the empty sha that
# is already today's answer. Overridable for tests (set to "" to force the
# no-timeout path), same idiom as HEART_VALIDATION_FILE.
if [[ -n "${HEART_TIMEOUT_BIN+set}" ]]; then
_CI_TIMEOUT_BIN="$HEART_TIMEOUT_BIN"
elif command -v timeout >/dev/null 2>&1; then
_CI_TIMEOUT_BIN="timeout"
elif command -v gtimeout >/dev/null 2>&1; then
_CI_TIMEOUT_BIN="gtimeout"
else
_CI_TIMEOUT_BIN=""
fi

# Resolve <owner/name>'s `main` HEAD sha, preferring `gh` and falling back to an
# anonymous `git ls-remote`.
#
# `gh` stays first: it is what the dev box uses, and it is the only one of the
# two that can read a private repo. The fallback exists for the mobile/cloud
# session, where `gh` is not installed at all — there the sha came back empty and
# readiness could not confirm an ingested release-validation report against the
# live HEADs, reporting "release validation source unconfirmed (current HEADs
# unknown)" even with every other gap cleared.
#
# `ls-remote` needs no authentication and no session repo attachment, so it works
# exactly where `gh` cannot. It is bounded because this runs inside the <30s
# tick: GIT_TERMINAL_PROMPT=0 stops a private repo blocking on a credential
# prompt, and `timeout` caps a stalled connection. Prints the empty string on
# failure — the same honest answer as before, never a fabricated sha.
ci_head_sha() {
local owner_name="$1" sha=""

if command -v gh >/dev/null 2>&1; then
sha="$(gh api "repos/$owner_name/commits/main" --jq '.sha' 2>/dev/null || echo '')"
fi

if [[ -z "$sha" && -n "$_CI_TIMEOUT_BIN" ]]; then
sha="$(GIT_TERMINAL_PROMPT=0 "$_CI_TIMEOUT_BIN" "$_CI_LS_REMOTE_TIMEOUT" \
git ls-remote "https://github.com/$owner_name" refs/heads/main \
2>/dev/null | awk 'NR==1 {print $1}')"
fi

printf '%s' "$sha"
}

check_one_repo_ci() {
local owner_name="$1"
local group="$2"
Expand All @@ -44,7 +98,7 @@ check_one_repo_ci() {
err="$(mktemp)"
runs="$(gh api "repos/$owner_name/$_CI_RUNS_PATH" 2>"$err")"
rc=$?
head_sha="$(gh api "repos/$owner_name/commits/main" --jq '.sha' 2>/dev/null || echo '')"
head_sha="$(ci_head_sha "$owner_name")"
ts="$(date -Iseconds)"

local fetch_error=""
Expand All @@ -59,12 +113,13 @@ check_one_repo_ci() {
printf '%s' "$runs" | PYTHONPATH="$HEART_HOME" python3 -m heart.checks.ci_status \
--name "$name" --group "$group" --head-sha "$head_sha" --ts "$ts" \
--fetch-error "$fetch_error" \
--cloud-runs "$HEART_CLOUD_CI_DIR/$name.json" \
--out "$HEART_PER_REPO_DIR/$name.ci_status.json"
}

check_ci_status_all() {
heart_state_dir
heart_log INFO "$(c_info "ci_status: scanning $(load_repos_yaml | wc -l) repos via gh (per-required-workflow on main HEAD)")"
heart_log INFO "$(c_info "ci_status: scanning $(load_repos_yaml | wc -l) repos via gh (HEAD sha falls back to ls-remote; per-required-workflow on main HEAD)")"
while read -r line; do
[[ -z "$line" ]] && continue
local owner_name group
Expand Down
Loading
Loading