From 3f57cfdcac344f34bc95eb5a6f318260c3b47c1a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 25 Aug 2026 12:39:15 +0000 Subject: [PATCH 1/3] feat(ci_status): resolve main HEAD sha without gh, via ls-remote MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a mobile/cloud session `gh` is not installed, so the `gh api .../commits/main` call returned an empty sha. Readiness could then not confirm an ingested release-validation report against the live HEADs and reported "release validation source unconfirmed (current HEADs unknown)" even with every other evidence gap cleared. Extract the lookup into `ci_head_sha`, which keeps `gh` first — unchanged dev-box behaviour, and the only source that can read a private repo — and falls back to an anonymous `git ls-remote`, which needs neither authentication nor a session repo attachment. The fallback is bounded because it runs inside the <30s tick: GIT_TERMINAL_PROMPT=0 stops a private repo blocking on a credential prompt, and `timeout` caps a stalled connection. `timeout` is coreutils, so it is resolved to `timeout`/`gtimeout` once at source time; where neither exists (stock macOS) the fallback is skipped rather than run unbounded, since a stalled ls-remote is worse than the empty sha that is already today's answer. Failure still yields an empty sha, never a fabricated one. This works standalone because build_sidecar writes `head_sha` unconditionally (ci_status.py:274), independent of the runs fetch error: the CI row keeps reading "unavailable" until the conclusions half lands, but the release gate can already confirm commit_shas. Verified in a gh-less container: all 25 repos scanned in 3.3s, the five release-gate libraries resolve their real shas, and readiness no longer emits the source-unconfirmed reason. Closes #178 Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01SeYsHrJsuH6wXjCCypKPzp --- heart/checks/ci_status.sh | 60 +++++++++++++- tests/test_ci_status_script.py | 144 +++++++++++++++++++++++++++++++++ 2 files changed, 201 insertions(+), 3 deletions(-) create mode 100644 tests/test_ci_status_script.py diff --git a/heart/checks/ci_status.sh b/heart/checks/ci_status.sh index a945cbfa..28de56d8 100755 --- a/heart/checks/ci_status.sh +++ b/heart/checks/ci_status.sh @@ -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 @@ -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 '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" @@ -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="" @@ -64,7 +118,7 @@ check_one_repo_ci() { 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 diff --git a/tests/test_ci_status_script.py b/tests/test_ci_status_script.py new file mode 100644 index 00000000..e0a749d9 --- /dev/null +++ b/tests/test_ci_status_script.py @@ -0,0 +1,144 @@ +"""tests/test_ci_status_script.py — the shell leg's HEAD-sha resolution. + +`ci_head_sha` is the one piece of `ci_status.sh` with a real branch in it: it +prefers `gh` and falls back to an anonymous `git ls-remote` so a mobile/cloud +session with no `gh` still records a sha. Exercised the same way +`test_verify_install_script.py` drives its helpers — source the file, call the +one function, and put stub executables first on `PATH` so nothing here touches +the network or a real `gh`. +""" + +import subprocess +import textwrap +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +SCRIPT = ROOT / "heart" / "checks" / "ci_status.sh" + +GH_SHA = "1111111111111111111111111111111111111111" +LS_REMOTE_SHA = "2222222222222222222222222222222222222222" + + +def write_stub(bin_dir: Path, name: str, body: str) -> None: + """Drop an executable stub named `name` into `bin_dir`.""" + path = bin_dir / name + path.write_text("#!/usr/bin/env bash\n" + textwrap.dedent(body)) + path.chmod(0o755) + + +def call_ci_head_sha(bin_dir: Path, repo: str = "PyAutoLabs/PyAutoFit", env=None): + """Source ci_status.sh in a shell whose PATH starts with the stubs.""" + environ = { + # A PATH holding only the stub dir plus the system dirs the script's own + # `source` line needs. `gh` is absent unless a stub provides it, which is + # exactly the mobile-session condition under test. + "PATH": f"{bin_dir}:/usr/bin:/bin", + "HOME": str(bin_dir), + **(env or {}), + } + return subprocess.run( + [ + "bash", + "-c", + 'source "$1" >/dev/null 2>&1; ci_head_sha "$2"', + "ci_head_sha", + str(SCRIPT), + repo, + ], + capture_output=True, + text=True, + env=environ, + ) + + +@pytest.fixture +def bin_dir(tmp_path): + d = tmp_path / "bin" + d.mkdir() + return d + + +def test_prefers_gh_when_available(bin_dir): + """With `gh` working, its sha wins and the fallback never runs.""" + write_stub(bin_dir, "gh", f'echo "{GH_SHA}"\n') + # A `git` that would fail the assertion if it were ever consulted. + write_stub(bin_dir, "git", f'echo "{LS_REMOTE_SHA}\trefs/heads/main"\n') + + result = call_ci_head_sha(bin_dir) + + assert result.stdout == GH_SHA + + +def test_falls_back_to_ls_remote_when_gh_absent(bin_dir): + """The mobile case: no `gh` on PATH at all, so ls-remote supplies the sha.""" + write_stub(bin_dir, "git", f'echo "{LS_REMOTE_SHA}\trefs/heads/main"\n') + + result = call_ci_head_sha(bin_dir) + + assert result.stdout == LS_REMOTE_SHA + + +def test_falls_back_when_gh_present_but_fails(bin_dir): + """`gh` installed but unauthenticated/erroring is still a fallback case.""" + write_stub(bin_dir, "gh", 'echo "gh: not authenticated" >&2\nexit 1\n') + write_stub(bin_dir, "git", f'echo "{LS_REMOTE_SHA}\trefs/heads/main"\n') + + result = call_ci_head_sha(bin_dir) + + assert result.stdout == LS_REMOTE_SHA + + +def test_empty_when_both_sources_fail(bin_dir): + """Never fabricate a sha — an empty string is the honest answer.""" + write_stub(bin_dir, "gh", "exit 1\n") + write_stub(bin_dir, "git", "exit 128\n") + + result = call_ci_head_sha(bin_dir) + + assert result.stdout == "" + + +def test_empty_when_ls_remote_prints_nothing(bin_dir): + """A zero-exit ls-remote with no matching ref must not yield a blank sha.""" + write_stub(bin_dir, "git", "exit 0\n") + + result = call_ci_head_sha(bin_dir) + + assert result.stdout == "" + + +def test_stalled_ls_remote_is_bounded(bin_dir): + """A hung fallback is capped by `timeout`, so it cannot eat the tick budget.""" + write_stub(bin_dir, "git", "sleep 30\n") + + result = call_ci_head_sha(bin_dir, env={"HEART_LS_REMOTE_TIMEOUT": "1"}) + + assert result.stdout == "" + + +def test_fallback_skipped_when_no_timeout_binary(bin_dir): + """No `timeout`/`gtimeout` (stock macOS): skip rather than run unbounded. + + A stalled ls-remote inside the <30s tick is a worse failure than the empty + sha that is already today's answer, so the fallback is not attempted at all. + """ + write_stub(bin_dir, "git", f'echo "{LS_REMOTE_SHA}\trefs/heads/main"\n') + + result = call_ci_head_sha(bin_dir, env={"HEART_TIMEOUT_BIN": ""}) + + assert result.stdout == "" + + +def test_takes_first_line_only(bin_dir): + """ls-remote can print more than one ref; only the first field of the first.""" + write_stub( + bin_dir, + "git", + f'printf "{LS_REMOTE_SHA}\\trefs/heads/main\\n3333333333333333333333333333333333333333\\trefs/heads/mainline\\n"\n', + ) + + result = call_ci_head_sha(bin_dir) + + assert result.stdout == LS_REMOTE_SHA From d29fe7dbe328409e102841c1ece50f0f650ac2b6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 25 Aug 2026 12:43:47 +0000 Subject: [PATCH 2/3] feat(ci_status): feed run conclusions from an MCP drop point MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second half of the no-gh mobile path (#178 covered the HEAD sha). Without `gh` the runs fetch fails outright, so every polled repo recorded status="unavailable" and CI was unknown per-library. `gh` is only transport here: ci_status.py already parses a REST-shaped {"workflow_runs": [...]} payload, and MCP's list_workflow_runs returns exactly that shape, snake_case keys included — so nothing is reshaped on the way in. Mirrors test_run.py's proven cloud_validation.json hand-off rather than inventing a second idiom. - HEART_CLOUD_CI_DIR ($HEART_STATE_DIR/cloud_ci/.json) holding {ts, runs}; ts optional, file mtime used when absent. - ci_status.cloud_runs() reads and age-bounds it, returning (runs, "") or (None, reason), failing closed on every malformed/undated/stale path. - main gains --cloud-runs, consulted ONLY when the live fetch already failed, so the dev box is byte-for-byte unchanged. A rejected payload appends its reason to the original error rather than vanishing. - New `source` sidecar field ("gh" | "cloud"). Provenance is evidence: a reader must be able to tell a conclusion Heart fetched from one an agent handed it. The tick does no network work for this — it only reads the drop point, as it already reads cloud_validation.json. Population is a separate one-shot leg, which is what keeps the <30s budget intact. Verified in a gh-less container against a drop point built from a real MCP list_workflow_runs response: consumed with source="cloud" and the error cleared. The rollup still declined to report success, because PyAutoFit's main advanced between the fetch and the tick and the existing on_head guard marked the runs off-HEAD — the guard working as intended, and why the age bound alone is not sufficient: a payload can be fresh by clock and stale by commit. Closes #179 Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01SeYsHrJsuH6wXjCCypKPzp --- heart/_common.sh | 9 ++- heart/checks/ci_status.py | 108 ++++++++++++++++++++++++- heart/checks/ci_status.sh | 1 + tests/test_ci_status.py | 163 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 277 insertions(+), 4 deletions(-) diff --git a/heart/_common.sh b/heart/_common.sh index 7da66169..fdfd8844 100644 --- a/heart/_common.sh +++ b/heart/_common.sh @@ -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 @@ -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 diff --git a/heart/checks/ci_status.py b/heart/checks/ci_status.py index 8c5e9637..216a9794 100644 --- a/heart/checks/ci_status.py +++ b/heart/checks/ci_status.py @@ -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", @@ -60,7 +61,9 @@ from __future__ import annotations import argparse +import datetime import json +import os import sys from pathlib import Path from typing import Any @@ -68,6 +71,13 @@ 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 @@ -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``. @@ -246,6 +320,7 @@ 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. @@ -253,6 +328,11 @@ def build_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)) @@ -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, @@ -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 @@ -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 @@ -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 diff --git a/heart/checks/ci_status.sh b/heart/checks/ci_status.sh index 28de56d8..66e2d0d8 100755 --- a/heart/checks/ci_status.sh +++ b/heart/checks/ci_status.sh @@ -113,6 +113,7 @@ 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" } diff --git a/tests/test_ci_status.py b/tests/test_ci_status.py index 602ee8a0..54dbf753 100644 --- a/tests/test_ci_status.py +++ b/tests/test_ci_status.py @@ -2,6 +2,8 @@ from __future__ import annotations +import datetime +import io import json from heart.checks import ci_status as ci @@ -10,6 +12,10 @@ OLD = "b" * 40 +def _now_iso(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() + + def _run(workflow, conclusion, status="completed", sha=HEAD, created="2026-06-29T00:00:00Z", event="push", url="u"): return { @@ -316,3 +322,160 @@ def test_main_reads_real_rest_payload(tmp_path, monkeypatch, capsys): assert side["conclusion"] == "failure" assert side["workflow"] == "Smoke Tests" assert "FAILURE" in capsys.readouterr().out + + +class TestCloudRuns: + """The mobile/cloud drop point: agent/MCP-supplied runs when `gh` cannot run. + + Freshness is the whole point of this leg. A CI conclusion is a claim about + *now*, so every rejection path below must degrade to "we could not ask" + rather than let an aged payload read as a current verdict. + """ + + PAYLOAD = {"workflow_runs": [{"name": "Tests", "head_branch": "main"}]} + + def write(self, tmp_path, data, name="PyAutoFit.json"): + p = tmp_path / name + p.write_text(json.dumps(data)) + return p + + def test_reads_a_fresh_payload(self, tmp_path): + p = self.write(tmp_path, {"ts": _now_iso(), "runs": self.PAYLOAD}) + + runs, reason = ci.cloud_runs(p) + + assert runs == self.PAYLOAD + assert reason == "" + + def test_accepts_a_bare_rest_payload(self, tmp_path): + """No wrapper: the MCP response dropped in as-is, dated by file mtime.""" + p = self.write(tmp_path, self.PAYLOAD) + + runs, reason = ci.cloud_runs(p) + + assert runs == self.PAYLOAD + assert reason == "" + + def test_rejects_a_stale_payload(self, tmp_path): + old = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(hours=5) + p = self.write(tmp_path, {"ts": old.isoformat(), "runs": self.PAYLOAD}) + + runs, reason = ci.cloud_runs(p, max_age_s=3600) + + assert runs is None + assert "stale" in reason + + def test_missing_file_is_not_an_error(self, tmp_path): + runs, reason = ci.cloud_runs(tmp_path / "absent.json") + + assert runs is None + assert reason == "no cloud runs payload" + + def test_unreadable_payload_fails_closed(self, tmp_path): + p = tmp_path / "bad.json" + p.write_text("{not json") + + runs, reason = ci.cloud_runs(p) + + assert runs is None + assert "unreadable" in reason + + def test_empty_payload_fails_closed(self, tmp_path): + p = self.write(tmp_path, {"ts": _now_iso(), "runs": {}}) + + runs, reason = ci.cloud_runs(p) + + assert runs is None + assert "empty" in reason + + def test_unparseable_ts_falls_back_to_mtime(self, tmp_path): + """A malformed stamp must not be trusted, but mtime still dates it.""" + p = self.write(tmp_path, {"ts": "not-a-date", "runs": self.PAYLOAD}) + + runs, reason = ci.cloud_runs(p) + + assert runs == self.PAYLOAD + assert reason == "" + + def test_naive_ts_is_treated_as_utc(self, tmp_path): + naive = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None) + p = self.write(tmp_path, {"ts": naive.isoformat(), "runs": self.PAYLOAD}) + + runs, reason = ci.cloud_runs(p) + + assert runs == self.PAYLOAD + assert reason == "" + + +class TestMainCloudFallback: + """`main`'s ordering: the live fetch wins; the drop point is the fallback.""" + + PAYLOAD = {"workflow_runs": [ + {"name": "Tests", "head_branch": "main", "status": "completed", + "conclusion": "success", "head_sha": "a" * 40, "created_at": "2026-08-25T00:00:00Z"}, + ]} + + def run_main(self, tmp_path, stdin, fetch_error, cloud=None, monkeypatch=None): + out = tmp_path / "out.json" + argv = ["--name", "PyAutoFit", "--group", "libraries", + "--head-sha", "a" * 40, "--ts", _now_iso(), "--out", str(out), + "--fetch-error", fetch_error] + if cloud is not None: + drop = tmp_path / "cloud.json" + drop.write_text(json.dumps({"ts": _now_iso(), "runs": cloud})) + argv += ["--cloud-runs", str(drop)] + monkeypatch.setattr("sys.stdin", io.StringIO(json.dumps(stdin))) + ci.main(argv) + return json.loads(out.read_text()) + + def test_live_fetch_is_never_second_guessed(self, tmp_path, monkeypatch): + """A successful gh fetch must ignore the drop point entirely.""" + live = {"workflow_runs": [ + {"name": "Tests", "head_branch": "main", "status": "completed", + "conclusion": "failure", "head_sha": "a" * 40, + "created_at": "2026-08-25T00:00:00Z"}, + ]} + + sidecar = self.run_main( + tmp_path, live, "", cloud=self.PAYLOAD, monkeypatch=monkeypatch + ) + + assert sidecar["source"] == "gh" + assert sidecar["conclusion"] == "failure" + + def test_failed_fetch_uses_the_drop_point(self, tmp_path, monkeypatch): + sidecar = self.run_main( + tmp_path, {}, "gh: command not found", + cloud=self.PAYLOAD, monkeypatch=monkeypatch, + ) + + assert sidecar["source"] == "cloud" + assert sidecar["error"] == "" + assert sidecar["conclusion"] == "success" + + def test_failed_fetch_without_a_drop_point_is_unchanged(self, tmp_path, monkeypatch): + sidecar = self.run_main( + tmp_path, {}, "gh: command not found", monkeypatch=monkeypatch + ) + + assert sidecar["source"] == "gh" + assert sidecar["status"] == "unavailable" + + def test_stale_drop_point_keeps_the_original_error(self, tmp_path, monkeypatch): + """Both failures are readable: no gh, AND the fallback did not save it.""" + out = tmp_path / "out.json" + drop = tmp_path / "cloud.json" + old = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=2) + drop.write_text(json.dumps({"ts": old.isoformat(), "runs": self.PAYLOAD})) + monkeypatch.setattr("sys.stdin", io.StringIO("{}")) + + ci.main([ + "--name", "PyAutoFit", "--group", "libraries", "--head-sha", "a" * 40, + "--ts", _now_iso(), "--out", str(out), + "--fetch-error", "gh: command not found", "--cloud-runs", str(drop), + ]) + sidecar = json.loads(out.read_text()) + + assert sidecar["status"] == "unavailable" + assert "gh: command not found" in sidecar["error"] + assert "stale" in sidecar["error"] From 9c20153ee246f29d65f5a9c2d4d9d9ae34ece602 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 25 Aug 2026 12:49:16 +0000 Subject: [PATCH 3/3] fix(tests): keep instance facts out of the new ci_status shell test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tenant-firewall check (PyAutoMind repos_sync.py) failed both legs: an unlisted organ file may carry NO instance fact, and the new test defaulted its repo argument to a real owner/name. Genericised rather than allowlisted. The allowlist's own comment says never to grow it casually — each entry is a file an adopting fork must rewrite — and this test earns no entry: `gh` and `git` are both stubbed, so the repo string is never resolved and a real one bought nothing. The suite itself was green on both legs (635 passed); only this check failed. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01SeYsHrJsuH6wXjCCypKPzp --- tests/test_ci_status_script.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_ci_status_script.py b/tests/test_ci_status_script.py index e0a749d9..a761f164 100644 --- a/tests/test_ci_status_script.py +++ b/tests/test_ci_status_script.py @@ -28,7 +28,10 @@ def write_stub(bin_dir: Path, name: str, body: str) -> None: path.chmod(0o755) -def call_ci_head_sha(bin_dir: Path, repo: str = "PyAutoLabs/PyAutoFit", env=None): +# The repo name is deliberately generic: `gh` and `git` are both stubbed here, +# so it is never resolved. A real owner/name would be an instance fact in organ +# code — see the tenant firewall in PyAutoMind's repos_sync.py. +def call_ci_head_sha(bin_dir: Path, repo: str = "ExampleOrg/ExampleRepo", env=None): """Source ci_status.sh in a shell whose PATH starts with the stubs.""" environ = { # A PATH holding only the stub dir plus the system dirs the script's own