diff --git a/.github/workflows/heart-health.yml b/.github/workflows/heart-health.yml index 874534d6..53d922ed 100644 --- a/.github/workflows/heart-health.yml +++ b/.github/workflows/heart-health.yml @@ -39,8 +39,28 @@ on: schedule: # Daily 05:00 UTC — one hour ahead of PyAutoMind's morning_health message # (06:00 UTC), which reads this run's verdict (moved from 06:00 for that). + # Since PyAutoHeart#340 this is the BACKSTOP; the events below refresh the + # feed when its evidence actually moves. - cron: "0 5 * * *" workflow_dispatch: + # EVENT TRIGGERS (PyAutoHeart#340, human ruling 2026-11-12: "event triggers + # refresh the feed"). A development ship treats evidence older than 6 h as + # STALE (heart/readiness.py `dev_ship`), so the feed must move when its + # evidence moves, not once a day: + # * repository_dispatch `heart-refresh` — sent by the reusable library + # gate (lib-tests.yml, job `heart-refresh`) when a library's CI finishes + # on `main`, i.e. after every library merge. Any other sender (the + # release workflow) uses the same event type. + # * workflow_run on Release Integrate — the release-validation rehearsal + # lands new release evidence in this repo. + # Bursts coalesce: the concurrency group below keeps one run in flight and + # at most one queued, so ten merges in a minute cost two runs, not ten. + # Both events run on the default branch, so they publish like the cron. + repository_dispatch: + types: [heart-refresh] + workflow_run: + workflows: ["Release Integrate"] + types: [completed] # contents: write → commit the README badge/block into Heart's OWN README # issues: write → the [heart-health] tracking issue @@ -139,6 +159,9 @@ jobs: # Read validation artifacts before readiness; never dispatch a run. PYTHONPATH="$PWD" python -m heart.checks.test_run PYTHONPATH="$PWD" python -m heart.checks.cloud_validation + # Rehearsed SHA still on main? (M2.4) — after the validation + # report is in, before readiness reads it. + PYTHONPATH="$PWD" python -m heart.checks.rehearsal_ancestry exit 0 - name: Append today's observations to the timing record diff --git a/.github/workflows/lib-tests.yml b/.github/workflows/lib-tests.yml index ec89e3a7..722a689f 100644 --- a/.github/workflows/lib-tests.yml +++ b/.github/workflows/lib-tests.yml @@ -610,3 +610,47 @@ jobs: { "text": "${{ github.repository }}/${{ github.ref_name }} (no-jax leg) build result: ${{ job.status }}\n${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" } + + # EVENT TRIGGER for the Heart feed (PyAutoHeart#340). When a library's CI + # finishes on `main` — after a merge — ask PyAutoHeart's heart-health.yml for + # a fresh board, so a development ship never reads a day-old verdict about + # the library that just moved. The ship gate treats a feed older than 6 h as + # STALE (heart/readiness.py `dev_ship`); this is the trigger that keeps the + # feed young. + # + # Harmless by construction: + # * runs only on a push to `main`, never on a PR or a branch; + # * `always()` — a red run moves the feed as much as a green one; + # * `continue-on-error` — a failed mint or dispatch never reds the + # library's required check (the caller's run conclusion is untouched); + # * it dispatches one `heart-refresh` event and nothing else: Heart's own + # concurrency group coalesces bursts. + # The App token is the org App the Heart already uses (heart-health.yml), + # scoped to the one Heart repo; the caller passes it with `secrets: inherit`. + heart-refresh: + name: Refresh the Heart feed + needs: [unittest, unittest-nojax] + if: ${{ always() && github.event_name == 'push' && github.ref == 'refs/heads/main' }} + runs-on: ubuntu-latest + continue-on-error: true + steps: + - name: Mint App token (the Heart repo, contents write for dispatch) + id: app_token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ vars.APP_CLIENT_ID }} + private-key: ${{ secrets.APP_PRIVATE_KEY }} + owner: ${{ github.repository_owner }} + repositories: PyAutoHeart + permission-contents: write + + - name: Dispatch heart-refresh to heart-health.yml + env: + GH_TOKEN: ${{ steps.app_token.outputs.token }} + run: | + gh api "repos/${{ github.repository_owner }}/PyAutoHeart/dispatches" \ + -f event_type=heart-refresh \ + -f "client_payload[source]=${{ github.repository }}" \ + -f "client_payload[sha]=${{ github.sha }}" \ + -f "client_payload[reason]=library CI finished on main" + echo "heart-refresh dispatched for ${{ github.repository }}@${{ github.sha }}" diff --git a/AGENTS.md b/AGENTS.md index 7df78106..5e04c663 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,9 +16,12 @@ triggers Build. **STALE** is the freshness tier: nothing known-bad, but some evidence is missing or expired — the remedy is re-running a check, never fixing code, and evidence whose last known result was adverse stays yellow/red (`heart/readiness.py` docstring is the canonical definition). -Releases still require GREEN; the dev-ship gate (PyAutoBrain `AUTONOMY.md` -leg 4) treats STALE as passing because an evidence gap is organism-scope, -not branch-scope. +Releases still require GREEN. A development ship asks the scoped gate, +`pyauto-heart readiness --dev --repos A,B --json`: only CI on `main` of the +touched repos and their dependants blocks, every other reason is shown, a +feed older than 6 h is STALE, and STALE never passes (PyAutoHeart#340). It +judges the dev box's local `~/.pyauto-heart/state.json`; the event triggers +refresh the published cloud feed, not that file. For the release-**validation** rehearsal specifically (build-and-exercise the exact source about to ship, before promoting to PyPI — see diff --git a/REFERENCE.md b/REFERENCE.md index ee466d96..1f0891c5 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -113,13 +113,35 @@ back to grey after 48 h (`DEVBOX_FRESH_SECONDS`). script-timing regressions, stale open PRs / parked scripts, skew BEHIND. - **STALE** — evidence missing or expired with nothing known-bad; the remedy is re-running a check, never fixing code. Evidence whose last known result was - adverse stays yellow/red. Releases require GREEN; the dev-ship gate treats - STALE as passing (an evidence gap is organism-scope, not branch-scope). + adverse stays yellow/red. Releases require GREEN. - **GREEN** — none of the above. `red > yellow > stale > green`. The `score` (0–100) is advisory/sortable only — the colour is the gate. Persisted to `~/.pyauto-heart/release_ready.json`. +### The development-ship gate (`readiness --dev --repos A,B`) + +`dev_ship(snapshot, repos)` answers "may this branch ship?" (PyAutoHeart#340, +human ruling 2026-11-12). It computes the release verdict above and partitions +it: only CI on `main` of the touched repos and of their dependants (the +`dependencies:` graph in `config/repos.yaml`) blocks; every other reason is +carried in `shown_reasons`. In-scope `main` CI is read for a repo of any +group (organs and developer workspaces included); a run with no conclusion +yet is STALE. A touched repo Heart does not poll is STALE ("not polled by +Heart"); a name `config/repos.yaml` never mentions is a usage error. Evidence +older than 6 h (`--max-feed-age-hours`, positive, at most 6), of unknown age, +or dated more than 5 min ahead, is STALE; each CI sidecar is aged by its own +`ts`, the snapshot by its aggregation `ts`. Only GREEN passes +(`"pass": true`); STALE means re-check, or park. The plain `readiness` call — +the release gate — is unchanged. Never persisted. + +**What it reads.** The dev box's local `$HEART_STATE_DIR/state.json` (default +`~/.pyauto-heart/state.json`, written by `tick` / `watch`); the verdict's +`source` and `feed_age_hours` say so. The event triggers in `heart-health.yml` +(`repository_dispatch: heart-refresh` from library CI on `main`, Release +Integrate completing) refresh the **published cloud feed** on Pages, which the +Brain's door reads — not this local snapshot. Refresh it locally with `tick`. + ## The release freeze window (`freeze`) A release validation is a window in which the library `main` branches must not diff --git a/bin/pyauto-heart b/bin/pyauto-heart index 08ac0fec..61b3c69e 100755 --- a/bin/pyauto-heart +++ b/bin/pyauto-heart @@ -190,7 +190,8 @@ cmd_status() { } help_readiness() { cat < -> the libraries it imports directly. +# Read strictly by heart/readiness.py's development-ship scope (`readiness +# --dev --repos A,B`, PyAutoHeart#340): a branch is blocked by red CI on `main` +# of the repos it touches AND of their dependants — the libraries downstream of +# them in this graph, transitively — and by nothing else. Mirrors the deps map +# in .github/workflows/lib-tests.yml (the install chain each library's own CI +# uses). A library with no entry imports no other library. Release gating does +# not read this block. +dependencies: + PyAutoFit: [PyAutoNerves] + PyAutoArray: [PyAutoNerves] + PyAutoGalaxy: [PyAutoNerves, PyAutoFit, PyAutoArray] + PyAutoLens: [PyAutoNerves, PyAutoFit, PyAutoArray, PyAutoGalaxy] + PyAutoCTI: [PyAutoNerves, PyAutoFit, PyAutoArray] + # Smoke-suite table: the workspaces the local smoke runner (heart/smoke.py) # can prepare and run — each key names its workspace checkout directory and the # library install chain — plus the repo -> import-package map the preflight @@ -198,6 +254,22 @@ smoke: excluded: - autolens_assistant # public-facing template - autolens_profiling # profiling project + - PyAutoReduce # standalone library (own lib-tests.yml caller); not polled — a dev ship touching it reads STALE + # Body-map repos (PyAutoMind/repos.yaml) Heart does not poll. Named so a + # development ship touching one reads STALE ("not polled by Heart") rather + # than failing as an unknown name; poll one to give its branches a verdict. + - PyAutoBroca + - PyAutoCortex + - PyAutoDNA + - PyAutoGut + - PyAutoScientist + - ECLIPSE_lens_catalogue + - autocti_assistant + - autofit_assistant + - autogalaxy_assistant + - euclid_assistant + - autoreduce_workspace + - pyautolabs.github.io - autolens_inference # inference benchmark project (search/inference runs; results tracked) - autolens_visualization # lens figure gallery project (PNGs + manifest tracked; re-rendered on release) - autogalaxy_visualization # galaxy figure gallery project (PNGs + manifest tracked; re-rendered on release) diff --git a/health_agent/capabilities.yaml b/health_agent/capabilities.yaml index 362685ac..b91db8d0 100644 --- a/health_agent/capabilities.yaml +++ b/health_agent/capabilities.yaml @@ -45,6 +45,19 @@ gate: HEADs and whose profile == release. Absent/stale/SHA-mismatch/wrong-profile → YELLOW; a failed validation stage → RED. This is the M2 hard gate: no release rehearsal for the current source can no longer be GREEN. + dev_ship_gate: + command: "pyauto-heart readiness --dev --repos A,B --json" + returns: "{ gate: dev-ship, verdict: green|stale|red, pass, scope{touched,dependants,enforced,not_polled}, red_reasons[], stale_reasons[], shown_reasons[], organism_verdict, feed_age_hours, max_feed_age_hours, remedy }" + rule: >- + PyAutoHeart#340 (human ruling 2026-11-12). A development ship blocks only + on CI on `main` of the repos the branch touches and of their dependants + (config/repos.yaml dependencies:); every other reason is shown in + shown_reasons, not blocking. Evidence older than 6 h, or of unknown age, + is STALE; only GREEN passes; STALE means re-check, or park. Release + gating is unchanged. It judges the dev box's LOCAL + ~/.pyauto-heart/state.json (named in `source`, aged in + feed_age_hours); the heart-health.yml event triggers refresh the + published cloud feed instead. # Continuous checks — cheap, run every <30s tick (heart/tick.sh). continuous_checks: diff --git a/heart/checks/ci_status.py b/heart/checks/ci_status.py index 216a9794..593020be 100644 --- a/heart/checks/ci_status.py +++ b/heart/checks/ci_status.py @@ -64,9 +64,10 @@ import datetime import json import os +import subprocess import sys from pathlib import Path -from typing import Any +from typing import Any, Callable HEART_HOME = Path(__file__).resolve().parents[2] CONFIG_PATH = HEART_HOME / "config" / "repos.yaml" @@ -365,6 +366,101 @@ def build_sidecar( } +# --- declared-CI backfill (PyAutoHeart#340) --------------------------------- +# +# The runs page above is the newest 30 runs on main. A repo whose OWN CI is +# declared in config/repos.yaml `dev_ship.ci_workflows` (an organ, say) can +# have a declared workflow fall off that page behind busy ops workflows; the +# development-ship gate would then have no run to judge. For each declared +# workflow absent from the page we fetch its latest main run directly — +# `actions/workflows//runs?branch=main&per_page=1` — resolving the id from +# the name via `actions/workflows` once and caching it. Bounded: one extra call +# per missing declared workflow per tick (plus the listing, only on a cache +# miss), each under BACKFILL_TIMEOUT_S. A failed fetch leaves the workflow +# absent, which readiness reads as STALE. The rolled-up conclusion is computed +# BEFORE the backfill, so the release-facing rollup is unchanged. + +#: Per-call bound for the backfill's gh calls (the tick's ls-remote bound). +BACKFILL_TIMEOUT_S = int(os.environ.get("HEART_LS_REMOTE_TIMEOUT", "10")) + + +def gh_api(path: str) -> Any: + """The gh seam: parsed ``gh api `` output, or None on any failure.""" + try: + result = subprocess.run(["gh", "api", path], capture_output=True, text=True, + timeout=BACKFILL_TIMEOUT_S) + return json.loads(result.stdout) if result.returncode == 0 else None + except (OSError, ValueError, subprocess.TimeoutExpired): + return None + + +def load_declared_ci(name: str, config_path: Path | str = CONFIG_PATH) -> list[str]: + """``dev_ship.ci_workflows[name]`` — the repo's declared own CI ([] if none).""" + try: + import yaml + + cfg = yaml.safe_load(Path(config_path).read_text()) or {} + return [str(w) for w in ((cfg.get("dev_ship") or {}).get("ci_workflows") or {}) + .get(name) or []] + except Exception: + return [] + + +def _read_cache(path: Path | None) -> dict[str, Any]: + try: + data = json.loads(path.read_text()) if path and path.is_file() else {} + return data if isinstance(data, dict) else {} + except (OSError, ValueError): + return {} + + +def backfill_declared( + sidecar: dict[str, Any], + owner: str, + declared: list[str], + api: Callable[[str], Any], + cache_path: Path | None = None, +) -> list[str]: + """Add the latest main run of each declared workflow missing from + ``sidecar["workflows"]`` (entries flagged ``backfilled``). Returns the + declared workflows still missing (fetch failed). Mutates ``sidecar``.""" + name = sidecar.get("name") or "" + workflows = sidecar.setdefault("workflows", {}) + missing = [wf for wf in declared if wf not in workflows] + if not missing or not owner or not name: + return missing + ids = _read_cache(cache_path) + if any(wf not in ids for wf in missing): + listing = api(f"repos/{owner}/{name}/actions/workflows?per_page=100") + for w in (listing or {}).get("workflows") or [] if isinstance(listing, dict) else []: + if isinstance(w, dict) and w.get("name") and w.get("id"): + ids[str(w["name"])] = w["id"] + if cache_path is not None and ids: + try: + cache_path.parent.mkdir(parents=True, exist_ok=True) + tmp = cache_path.with_suffix(".tmp") + tmp.write_text(json.dumps(ids, sort_keys=True)) + tmp.replace(cache_path) + except OSError: + pass + still: list[str] = [] + head_sha = sidecar.get("head_sha") or "" + for wf in missing: + wid = ids.get(wf) + payload = api(f"repos/{owner}/{name}/actions/workflows/{wid}/runs" + "?branch=main&per_page=1&exclude_pull_requests=true") if wid else None + runs = normalize_runs(payload) if isinstance(payload, dict) else [] + if not runs: + still.append(wf) + continue + entry = _wf_entry(runs[0], head_sha) + entry["backfilled"] = True + workflows[wf] = entry + if still: + sidecar["backfill_missing"] = still + return still + + def summary_line(sidecar: dict[str, Any]) -> str: """Coloured one-line summary for the daemon log.""" from heart.heart_color import ( @@ -424,6 +520,8 @@ 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("--owner", default="", + help="GitHub owner, for the declared-CI backfill (#340)") ap.add_argument( "--cloud-runs", default="", @@ -456,10 +554,16 @@ def main(argv: list[str] | None = None) -> int: # 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, source=source, - ) + sidecar = build_sidecar(ns.name, ns.group, runs, ns.head_sha, ns.ts, + error=error, source=source) + sys.path.insert(0, str(HEART_HOME)) + from heart import state + + declared = load_declared_ci(ns.name) + if declared and not error and source == "gh": + backfill_declared(sidecar, ns.owner, declared, gh_api, + state.HEART_STATE_DIR / "ci_workflow_ids" / f"{ns.name}.json") + state.atomic_write_json(Path(ns.out), sidecar) print(summary_line(sidecar)) return 0 diff --git a/heart/checks/ci_status.sh b/heart/checks/ci_status.sh index 66e2d0d8..083f6530 100755 --- a/heart/checks/ci_status.sh +++ b/heart/checks/ci_status.sh @@ -111,7 +111,7 @@ check_one_repo_ci() { rm -f "$err" printf '%s' "$runs" | PYTHONPATH="$HEART_HOME" python3 -m heart.checks.ci_status \ - --name "$name" --group "$group" --head-sha "$head_sha" --ts "$ts" \ + --name "$name" --owner "${owner_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/heart/checks/rehearsal_ancestry.py b/heart/checks/rehearsal_ancestry.py new file mode 100644 index 00000000..8d5a0741 --- /dev/null +++ b/heart/checks/rehearsal_ancestry.py @@ -0,0 +1,161 @@ +"""heart/checks/rehearsal_ancestry.py — is each rehearsed SHA still on ``main``? + +M2.4 (PyAutoHands#337, human ruling 2026-11-12): a release publishes EXACTLY +the commits the rehearsal built, even when ``main`` has moved on since. So a +release-validation report whose ``commit_shas`` differ from the current ``main`` +HEADs is not stale merely because ``main`` moved: it is still evidence for what +will ship, provided each rehearsed commit is an ANCESTOR of its repo's ``main`` +(main moved forward). It is stale when a rehearsed commit is not on ``main`` +(main rewritten, or an off-main commit was rehearsed), or when that cannot be +established. + +This check records the fact; ``heart/readiness.py`` reads it (``compute`` stays +a pure function of the snapshot). For each release-gate library whose rehearsed +SHA differs from the ``main`` HEAD that ``ci_status`` recorded, it asks GitHub's +compare API (``gh api repos///compare/...``): +``status`` ``ahead`` or ``identical`` means the rehearsed commit is an ancestor +of HEAD, and ``ahead_by`` is how many commits ``main`` is ahead. Anything else +(``behind``, ``diverged``, an error) is recorded as not proven. + +Writes ``$HEART_STATE_DIR/rehearsal_ancestry.json``; ``state.aggregate`` folds +it into the snapshot as ``rehearsal_ancestry``. ``collect`` is pure apart from +the injected ``api`` callable (the gh seam), so tests stay offline. +""" + +from __future__ import annotations + +import datetime +import json +import subprocess +import sys +import time +from concurrent.futures import ThreadPoolExecutor, wait +from pathlib import Path +from typing import Any, Callable + +import yaml + +from heart import state + +CONFIG_PATH = Path(__file__).resolve().parents[2] / "config" / "repos.yaml" +SIDECAR = "rehearsal_ancestry.json" +#: Compare statuses under which the base (rehearsed) commit is an ancestor of head. +ANCESTOR_STATUSES = frozenset({"ahead", "identical"}) +#: Per-call gh timeout, and the total wall-clock budget for all compare calls +#: (they run in parallel). A call still out at the budget is recorded as +#: unknown — readiness reads that as unproven, i.e. STALE, never as fresh. +CALL_TIMEOUT_S = 15 +TOTAL_BUDGET_S = 20.0 + + +def gh_api(path: str) -> dict: + """The gh seam: ``gh api `` as a dict, ``{}`` on any failure.""" + try: + result = subprocess.run(["gh", "api", path], capture_output=True, text=True, + timeout=CALL_TIMEOUT_S) + data = json.loads(result.stdout) if result.returncode == 0 else {} + return data if isinstance(data, dict) else {} + except (OSError, ValueError, subprocess.TimeoutExpired): + return {} + + +def library_owners(config_path: Path | str = CONFIG_PATH) -> dict[str, str]: + """Release-gate library -> GitHub owner, from the policy file.""" + cfg = yaml.safe_load(Path(config_path).read_text()) or {} + return { + r["name"]: r["owner"] + for r in (cfg.get("repos") or {}).get("libraries") or [] + if isinstance(r, dict) and r.get("name") and r.get("owner") + and r.get("release_gate", True) + } + + +def ancestry(owner: str, repo: str, rehearsed: str, head: str, + api: Callable[[str], dict]) -> dict[str, Any]: + """One repo's answer: is ``rehearsed`` an ancestor of ``head``?""" + data = api(f"repos/{owner}/{repo}/compare/{rehearsed}...{head}") + status = str(data.get("status") or "") + row: dict[str, Any] = {"rehearsed": rehearsed, "head": head, + "status": status or "unknown", + "ancestor": status in ANCESTOR_STATUSES} + if status in ANCESTOR_STATUSES: + try: + row["ahead_by"] = int(data.get("ahead_by", 0)) + except (TypeError, ValueError): + row["ahead_by"] = None + if not status: + row["error"] = "compare unavailable" + return row + + +def collect(snapshot: dict, owners: dict[str, str], api: Callable[[str], dict], + now: datetime.datetime | None = None, + budget_s: float = TOTAL_BUDGET_S) -> dict[str, Any]: + """The sidecar for ``snapshot``: one row per library whose rehearsed SHA + differs from its recorded ``main`` HEAD. Libraries that match need no row. + The compare calls run in parallel under one total ``budget_s``; a call not + back in time is a row with status ``unknown`` (error ``timeout``).""" + now = now or datetime.datetime.now(datetime.timezone.utc) + report = snapshot.get("validation_report") or {} + shas = report.get("commit_shas") if isinstance(report, dict) else None + repos = snapshot.get("repos") or {} + todo: dict[str, tuple[str, str, str]] = {} + for lib, owner in owners.items(): + want = str((shas or {}).get(lib) or "") + head = str((((repos.get(lib) or {}).get("ci_status")) or {}).get("head_sha") or "") + if not want or not head: + continue + n = min(len(want), len(head)) + if n >= 7 and want[:n].lower() == head[:n].lower(): + continue # rehearsed == HEAD: nothing to prove + todo[lib] = (owner, want, head) + rows: dict[str, Any] = {} + if todo: + pool = ThreadPoolExecutor(max_workers=len(todo)) + futures = {lib: pool.submit(ancestry, o, lib, w, h, api) + for lib, (o, w, h) in todo.items()} + wait(futures.values(), timeout=budget_s) + for lib, fut in futures.items(): + owner, want, head = todo[lib] + if fut.done() and fut.exception() is None: + rows[lib] = fut.result() + else: + rows[lib] = {"rehearsed": want, "head": head, "status": "unknown", + "ancestor": False, + "error": "timeout" if not fut.done() else "compare failed"} + pool.shutdown(wait=False, cancel_futures=True) + return {"checked_at": now.isoformat(), "report_ts": (report or {}).get("ts"), + "repos": rows} + + +def read_inputs(state_dir: Path | None = None) -> dict[str, Any]: + """The two inputs, read straight from this tick's sidecars — the + validation report and each library's ci_status — WITHOUT aggregating + (the tick's own aggregate, at its end, folds this check's sidecar in).""" + base = state_dir or state.HEART_STATE_DIR + per_repo = base / "per-repo" + + def read(path: Path) -> dict: + try: + data = json.loads(path.read_text()) + return data if isinstance(data, dict) else {} + except (OSError, ValueError): + return {} + + repos = {} + for f in sorted(per_repo.glob("*.ci_status.json")) if per_repo.is_dir() else (): + repos[f.name.split(".")[0]] = {"ci_status": read(f)} + return {"validation_report": read(base / "validation_report.json"), "repos": repos} + + +def main(argv: list[str] | None = None) -> int: + started = time.monotonic() + sidecar = collect(read_inputs(), library_owners(), gh_api) + state.atomic_write_json(state.HEART_STATE_DIR / SIDECAR, sidecar) + print(f"rehearsal_ancestry: {len(sidecar['repos'])} moved repo(s) checked " + f"in {time.monotonic() - started:.1f}s") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/heart/readiness.py b/heart/readiness.py index 10671761..dad5bd2d 100644 --- a/heart/readiness.py +++ b/heart/readiness.py @@ -28,14 +28,16 @@ hard block), script-timing regressions, stale open PRs, stale parked scripts, a stale or never-run install verification, **no fresh release-validation report for the current source** (absent, stale by age, or - whose ``commit_shas`` no longer match the current ``main`` HEADs, or which ran - under a profile other than ``release``), and — crucially — any *unknown* + whose ``commit_shas`` are no longer ancestors of the current ``main`` HEADs — + main moving FORWARD from the rehearsed commits keeps it fresh, since a + release publishes exactly those commits (M2.4, ``validation_ahead``) — or + which ran under a profile other than ``release``), and — crucially — any *unknown* (missing test-run report, a library absent from the snapshot). An unknown is never silently treated as green and never escalated to red. - **STALE** (an evidence gap, the freshness tier) when nothing is known-bad but some evidence is *missing or expired*: a check that was never run, a - passing-but-aged report, a rehearsal whose ``commit_shas`` no longer match - ``main``, a validation report whose ``validation_outcome`` is ``incomplete`` + passing-but-aged report, a rehearsal whose ``commit_shas`` are not (or not + provably) ancestors of ``main``, a validation report whose ``validation_outcome`` is ``incomplete`` (nothing failed; the rehearsal evidence is absent), an unknown repo/version status. The remedy for a stale reason is to **re-run the check**, never to fix code — which is exactly what separates it @@ -64,11 +66,37 @@ exactly as they always did. The workspace script surface is not weakened by scoping out the local ``test_run`` cache: the release-validation report *is* that surface at release fidelity, and required-workflow conclusions gate the -workspaces' ``main``. The **dev-ship gate** (PyAutoBrain ``AUTONOMY.md`` leg 4) -treats STALE as passing: an evidence gap is organism-scope, not branch-scope, -and the other three legs gate the branch itself. This is what makes GREEN -reachable in steady state and keeps YELLOW meaning "something is actually -wrong" instead of training ack-fatigue. +workspaces' ``main``. Keeping evidence gaps in their own tier is what makes +GREEN reachable in steady state and keeps YELLOW meaning "something is +actually wrong" instead of training ack-fatigue. + +**The development-ship gate** (``--dev --repos A,B``; ``dev_ship``; human +ruling 2026-11-12, PyAutoHeart#340) answers a different question from the +release gate — "may this branch ship?", not "may ``main`` be published?": + +- *Scope.* A development ship is blocked only by CI on ``main`` of the repos + the branch touches and of their dependants (the libraries downstream of + them in ``config/repos.yaml``'s ``dependencies`` graph). Every other reason + — release validation, install verification, version floors, organ + workflows, the dev box's checkout state — is still shown, in + ``shown_reasons``, but does not block. In-scope ``main`` CI is read for a + repo of ANY group (an organ, a developer workspace), not only the + release-gated ones; a run with no conclusion yet is STALE. A touched repo + Heart does not poll is STALE ("not polled by Heart"); a name the policy file + never mentions is a usage error. +- *Feed age.* Evidence older than ``DEV_MAX_FEED_AGE_HOURS`` (6 h, also the + ceiling a caller may set), of unknown age, or dated more than 5 min in the + future, is STALE: re-check, or park. Each in-scope CI sidecar is aged by its + own collection ``ts``, and the snapshot by its aggregation ``ts``. **STALE + never passes** this gate; only GREEN does (``pass``). This replaces the + earlier rule under which the dev-ship gate treated an organism-wide STALE as + a pass. +- *Source.* From the CLI it judges the dev box's local + ``$HEART_STATE_DIR/state.json`` (the tick's snapshot), and says so with that + snapshot's age. The event triggers in ``heart-health.yml`` refresh the + published cloud feed, which this command does not read. +- *Release gating is unchanged:* ``compute`` and the plain ``readiness`` call + read exactly as before. Red dominates yellow, which dominates stale, structurally: reasons are collected into separate lists and @@ -86,6 +114,7 @@ import argparse import datetime import json +import math import os import sys from pathlib import Path @@ -272,6 +301,10 @@ def compute( na: list[str] = [] counts: dict[str, int] = {} repository_reasons: list[dict[str, str]] = [] + # Repos whose main moved FORWARD from the rehearsed commit -> commits ahead + # (None when GitHub did not say). Informational: the rehearsal still covers + # exactly what a release would publish (M2.4). + validation_ahead: dict[str, Any] = {} def hit(key: str, n: int = 1) -> None: counts[key] = counts.get(key, 0) + n @@ -302,6 +335,8 @@ def scope_local(msg: str, key: str) -> None: body = repos.get(lib) if not isinstance(body, dict) or not body: add_stale(f"{lib}: status unknown", "lib_unknown") + repository_reasons.append({"repo": lib, "key": "lib_unknown", + "text": stale[-1], "severity": "stale"}) continue ci = body.get("ci_status", {}) or {} conclusion = ci.get("conclusion") @@ -611,16 +646,43 @@ def scope_local(msg: str, key: str) -> None: else: mismatched.append(lib) vr_profile = str(vr.get("profile") or "").strip().lower() + # M2.4 (PyAutoHands#337): a release publishes EXACTLY the rehearsed + # commits, so main moving FORWARD from them does not stale the + # rehearsal. A moved repo stays fresh when the rehearsed SHA is + # proven an ancestor of the current HEAD (rehearsal_ancestry + # sidecar, both SHAs matching); it is stale when proven NOT an + # ancestor (main rewritten / off-main commit) or when unproven. + anc_rows = (snapshot.get("rehearsal_ancestry") or {}).get("repos") or {} + not_ancestor: list[str] = [] + unproven: list[str] = [] + for lib in mismatched: + row = anc_rows.get(lib) if isinstance(anc_rows, dict) else None + cur = ((repos.get(lib) or {}).get("ci_status") or {}).get("head_sha") + if not (isinstance(row, dict) + and _sha_eq(row.get("rehearsed"), commit_shas.get(lib)) + and _sha_eq(row.get("head"), cur) + and row.get("status") not in (None, "", "unknown")): + unproven.append(lib) + elif row.get("ancestor") is True: + validation_ahead[lib] = row.get("ahead_by") + else: + not_ancestor.append(lib) if not commit_shas: add_stale("release validation source unconfirmed (no commit_shas)", "validation_unknown") - elif mismatched: + elif not_ancestor: + add_stale( + "release validation stale: rehearsed commit not an ancestor of main (" + + ", ".join(not_ancestor) + ")", + "validation_stale_sha", + ) + elif unproven: add_stale( "release validation stale: source moved since rehearsal (" - + ", ".join(mismatched) + ")", + + ", ".join(unproven) + "; ancestry unproven)", "validation_stale_sha", ) - elif confirmed == 0: + elif confirmed == 0 and not validation_ahead: add_stale("release validation source unconfirmed (current HEADs unknown)", "validation_unknown") elif unconfirmed: @@ -768,6 +830,13 @@ def scope_local(msg: str, key: str) -> None: # flat lists above are the contract every existing consumer reads. "stale_details": [{"text": t, "key": k} for t, k in zip(stale, stale_keys)], "na_reasons": na, + "validation_ahead": validation_ahead, + "validation_note": ( + "release validation covers the rehearsed commits; main is ahead by " + + ", ".join(f"{lib} {n if n is not None else '?'}" + for lib, n in validation_ahead.items()) + + " commit(s) — a release publishes the rehearsed SHAs (M2.4)" + ) if validation_ahead else "", "ts": snapshot.get("ts") or datetime.datetime.now(datetime.timezone.utc).isoformat(), } @@ -789,6 +858,420 @@ def load_verdict() -> dict[str, Any]: return compute(state.load() or {}) +# --- the development-ship gate (PyAutoHeart#340) ---------------------------- +# +# See the module docstring, "The development-ship gate". The release verdict +# above is computed in full and then *partitioned*: the reasons this gate +# enforces block, every other reason is carried in ``shown_reasons``. On top of +# that partition, every in-scope repo's ``main`` CI is read straight from the +# snapshot, whatever its group — an organ or a developer workspace is gated by +# nothing in ``compute``, but red CI on it is still the branch's business. +# +# WHAT IT READS. The snapshot passed in. From the CLI that is the dev box's +# local ``$HEART_STATE_DIR/state.json`` (default ``~/.pyauto-heart/``), written +# by ``pyauto-heart tick`` / the watch daemon — NOT the published cloud feed. +# The event triggers (heart-health.yml: ``repository_dispatch: heart-refresh`` +# from library CI on main, Release Integrate completing) refresh the PUBLISHED +# cloud feed (Pages ``state.json`` / ``board.json``), which the Brain's door +# (``bin/heart_feed.py``) reads; they do not touch a dev box's local state. +# The verdict names its ``source`` and that source's age, so a reader always +# knows which of the two it is looking at. + +#: Evidence older than this many hours is STALE at a development ship. Also the +#: largest maximum a caller may ask for (the ruling's ceiling); smaller is allowed. +DEV_MAX_FEED_AGE_HOURS = 6.0 + +#: A snapshot dated this far in the future is clock skew; beyond it the age is +#: unknown (STALE), never "fresh". +DEV_CLOCK_SKEW_HOURS = 5.0 / 60.0 + +#: The reason keys of ``compute`` a development ship enforces, all of them CI on +#: ``main`` of one named repo (``repository_reasons[].key``). +DEV_ENFORCED_KEYS = frozenset({"lib_ci", "ws_ci", "lib_ci_unavailable", "lib_unknown"}) + + +def load_dependencies(config_path: Path | str = CONFIG_PATH) -> dict[str, list[str]]: + """``dependencies:`` from the policy file — library -> libraries it imports. + + Strict: the dev-ship scope is built from it, and a silently missing graph + would shrink every scope to the touched repos alone (dependants unblocked), + so an absent or malformed block fails loudly.""" + cfg = yaml.safe_load(Path(config_path).read_text()) or {} + deps = cfg.get("dependencies") + if not isinstance(deps, dict) or not deps: + raise ValueError(f"no dependencies graph in {config_path}") + out: dict[str, list[str]] = {} + for lib, ups in deps.items(): + if not isinstance(ups, list): + raise ValueError(f"dependencies.{lib} must be a list in {config_path}") + out[str(lib)] = [str(u) for u in ups] + return out + + +def load_repo_groups(config_path: Path | str = CONFIG_PATH) -> dict[str, str]: + """Every polled repo -> its group (``repos.[].name``).""" + cfg = yaml.safe_load(Path(config_path).read_text()) or {} + return { + r["name"]: group + for group, entries in (cfg.get("repos") or {}).items() + for r in entries or [] + if isinstance(r, dict) and r.get("name") + } + + +def load_known_repo_names(config_path: Path | str = CONFIG_PATH) -> list[str]: + """Every repo the policy file names anywhere — polled groups, ``excluded``, + ``version_skew``, the smoke table, the dependency graph. A dev-ship + ``--repos`` entry outside this set is a usage error (a typo), never a + silent pass.""" + cfg = yaml.safe_load(Path(config_path).read_text()) or {} + names = set(load_repo_groups(config_path)) + names |= {str(x) for x in cfg.get("excluded") or [] if isinstance(x, str)} + names |= {str(k) for k in (cfg.get("version_skew") or {})} + smoke = cfg.get("smoke") or {} + names |= {str(k) for k in (smoke.get("import_names") or {})} + names |= {str(w.get("directory")) for w in (smoke.get("workspaces") or {}).values() + if isinstance(w, dict) and w.get("directory")} + for lib, ups in (cfg.get("dependencies") or {}).items(): + names.add(str(lib)) + names |= {str(u) for u in ups or []} + return sorted(names) + + +def load_release_scope_workflows(config_path: Path | str = CONFIG_PATH) -> frozenset[str]: + """``dev_ship.release_scope_workflows`` — workflow names that never count + as a repo's own ``main`` CI at a development ship. Absent ⇒ none (every + run counts: the fail-closed direction).""" + cfg = yaml.safe_load(Path(config_path).read_text()) or {} + wfs = (cfg.get("dev_ship") or {}).get("release_scope_workflows") or [] + return frozenset(str(w) for w in wfs) + + +def load_ci_workflows(config_path: Path | str = CONFIG_PATH) -> dict[str, list[str]]: + """``dev_ship.ci_workflows`` — repo -> the workflows that are its own CI + (advisory groups only; libraries and gated workspaces use + ``required_workflows``). Absent repo ⇒ no declaration (STALE at a ship).""" + cfg = yaml.safe_load(Path(config_path).read_text()) or {} + raw = (cfg.get("dev_ship") or {}).get("ci_workflows") or {} + return {str(k): [str(w) for w in (v or [])] for k, v in raw.items()} + + +def dependants_of(repos: Sequence[str], dependencies: dict[str, list[str]]) -> set[str]: + """Everything downstream of ``repos`` in the graph, transitively (the + repos themselves excluded unless they sit downstream of one another).""" + down: dict[str, set[str]] = {} + for lib, ups in dependencies.items(): + for up in ups: + down.setdefault(up, set()).add(lib) + seen: set[str] = set() + frontier = list(repos) + while frontier: + for d in down.get(frontier.pop(), ()): + if d not in seen: + seen.add(d) + frontier.append(d) + return seen + + +def dev_scope( + repos: Sequence[str], + dependencies: dict[str, list[str]], + known: Sequence[str] = (), + universe: Sequence[str] | None = None, +) -> dict[str, list[str]]: + """The repos a development ship answers for. + + ``repos`` is what the caller states the branch touches (comma-separated + entries are split). Names match the policy's spelling case-insensitively + and are reported in it. ``known`` is the polled set; a touched repo outside + it is listed under ``not_polled`` — Heart holds no evidence about it, so + ``dev_ship`` reads it STALE, never green. With ``universe`` (every name the + policy file mentions), a name outside it raises ``ValueError``: a typo is a + usage error, not a repo.""" + pool = (*(universe or ()), *known, *dependencies, + *(u for ups in dependencies.values() for u in ups)) + canon = {n.lower(): n for n in pool} + touched: list[str] = [] + for raw in repos: + for part in str(raw).split(","): + name = part.strip() + if name: + name = canon.get(name.lower(), name) + if name not in touched: + touched.append(name) + if universe is not None: + unknown = [t for t in touched if t.lower() not in {n.lower() for n in pool}] + if unknown: + raise ValueError("not a repo named in config/repos.yaml: " + ", ".join(unknown)) + dependants = sorted(dependants_of(touched, dependencies) - set(touched)) + known_l = {n.lower() for n in known} + return { + "touched": touched, + "dependants": dependants, + "enforced": [*touched, *dependants], + "not_polled": [t for t in touched if known and t.lower() not in known_l], + } + + +def split_dev_reasons( + verdict: dict[str, Any], enforced: Sequence[str] +) -> tuple[list[str], list[str], list[dict[str, str]]]: + """Partition a release verdict for a development ship. + + Returns ``(blocking_red, blocking_stale, shown)``: the enforced reasons + (``DEV_ENFORCED_KEYS`` on an in-scope repo) by tier, and every other reason + of the verdict as ``{"severity", "text"}`` — shown, never dropped.""" + scope = {str(r).lower() for r in enforced} + blocking = [ + r for r in verdict.get("repository_reasons") or [] + if isinstance(r, dict) and r.get("key") in DEV_ENFORCED_KEYS + and str(r.get("repo", "")).lower() in scope + ] + red = [str(r.get("text")) for r in blocking if r.get("severity") == "red"] + stale = [str(r.get("text")) for r in blocking if r.get("severity") == "stale"] + taken = set(red) | set(stale) + shown = [ + {"severity": sev, "text": str(t)} + for sev, key in (("red", "red_reasons"), ("yellow", "yellow_reasons"), + ("stale", "stale_reasons")) + for t in verdict.get(key) or [] + if str(t) not in taken + ] + return red, stale, shown + + +def feed_age_hours(ts: Any, now: datetime.datetime) -> float | None: + """Hours since ``ts``. None — unknown, so STALE — when it is absent, + unparseable, or further in the future than ``DEV_CLOCK_SKEW_HOURS``; a + future stamp within the skew reads as 0.""" + t = _parse_ts(ts) + if t is None: + return None + age = (now - t).total_seconds() / 3600.0 + if age < -DEV_CLOCK_SKEW_HOURS: + return None + return max(0.0, age) + + +def check_max_age_hours(value: Any) -> float: + """A caller's maximum feed age: finite, positive, at most the ruling's 6 h.""" + try: + v = float(value) + except (TypeError, ValueError): + raise ValueError(f"max feed age {value!r} is not a number") from None + if not math.isfinite(v) or v <= 0: + raise ValueError(f"max feed age must be finite and positive, got {value!r}") + if v > DEV_MAX_FEED_AGE_HOURS: + raise ValueError(f"max feed age {v:g} h exceeds the {DEV_MAX_FEED_AGE_HOURS:g} h ceiling") + return v + + +def _no_conclusion(c: Any) -> bool: + return c in (None, "") + + +def _in_scope_ci( + snapshot: dict, enforced: Sequence[str], groups: dict[str, str], + gate_libs: set[str], req_wf: dict[str, list[str]], + now: datetime.datetime, max_age_hours: float, + release_scope: frozenset[str] = frozenset(), + ci_workflows: dict[str, list[str]] | None = None, +) -> tuple[list[str], list[str], list[dict[str, str]]]: + """``main`` CI of every in-scope repo, read from the snapshot: (red, stale). + + Release-gate libraries and gated workspaces already carry their red / error + / absent reasons from ``compute``; this adds what the release gate passes + over — no conclusion yet, aged evidence — and gives every other group + (organs, build workflow, developer workspaces) the same treatment in full. + For an advisory group only the repo's declared CI workflows + (``ci_workflows``) count, each judged on its latest run: any failing → + red; any unfinished, or with no recorded run, → stale. Every + other workflow (ops: boards, sweeps, schedules; never a ``release_scope`` + one) failing on HEAD is returned in ``shown``, never blocking. An advisory + repo with no declaration is STALE. Returns ``(red, stale, shown)``.""" + repos = snapshot.get("repos") or {} + ci_workflows = ci_workflows or {} + red: list[str] = [] + stale: list[str] = [] + shown: list[dict[str, str]] = [] + for name in enforced: + group = groups.get(name) + if group is None: + continue # not polled: reported by the caller + body = repos.get(name) + ci = body.get("ci_status") if isinstance(body, dict) else None + ci = ci if isinstance(ci, dict) and ci else None + if group == "libraries" and name in gate_libs: + if ci and not ci.get("error") and _no_conclusion(ci.get("conclusion")): + stale.append(f"{name}: CI on main has no conclusion yet " + f"({ci.get('status') or 'status unknown'})") + elif ci is None: + stale.append(f"{name}: CI status on main not observed") + elif ci.get("error"): + stale.append(f"{name}: CI status unavailable ({ci['error']})") + elif group in GATED_WORKSPACE_GROUPS and req_wf.get(group): + wfs = ci.get("workflows") + if isinstance(wfs, dict): + for wf in req_wf[group]: + if _no_conclusion((wfs.get(wf) or {}).get("conclusion")): + stale.append(f"{name}: {wf} on main has no conclusion yet") + elif _no_conclusion(ci.get("conclusion")): + stale.append(f"{name}: CI on main has no conclusion yet") + elif name not in ci_workflows: + stale.append(f"{name}: no CI workflows declared (config/repos.yaml " + "dev_ship.ci_workflows) — its main CI cannot be judged") + else: + declared = set(ci_workflows[name]) + raw = ci.get("workflows") + every = {wf: e for wf, e in (raw.items() if isinstance(raw, dict) else ()) + if isinstance(e, dict)} + for wf, e in sorted(every.items()): + if (wf not in declared and wf not in release_scope and e.get("on_head") + and e.get("conclusion") in FAILURE_CONCLUSIONS): + shown.append({"severity": "red", + "text": f"{name}: {wf} {e.get('conclusion')} on main " + "(ops workflow — not CI, not blocking)"}) + # The LATEST run of EACH declared workflow is judged (ci_status + # keeps one entry per workflow — its newest run on main): any red + # blocks, any missing or unfinished one is STALE. One workflow's + # newer green never hides another's red. + failing: list[str] = [] + for wf in sorted(declared): + e = every.get(wf) + if e is None: + stale.append(f"{name}: {wf} has no recorded run on main " + "(not in the CI status page) — cannot be judged") + elif e.get("conclusion") in FAILURE_CONCLUSIONS: + failing.append(f"{wf} {e.get('conclusion')}") + elif e.get("conclusion") != "success": + stale.append(f"{name}: {wf} on main has no conclusion yet") + if failing: + red.append(f"{name}: {', '.join(failing)} on main") + # The evidence's own collection time, where the sidecar carries one; + # the snapshot's aggregation ts is judged separately by the caller. + if ci and ci.get("ts"): + age = feed_age_hours(ci.get("ts"), now) + if age is None: + stale.append(f"{name}: CI evidence age unknown (ts {ci.get('ts')})") + elif age > max_age_hours: + stale.append(f"{name}: CI evidence {age:.1f} h old, over the " + f"{max_age_hours:g} h maximum — re-check, or park") + return red, stale, shown + + +def dev_ship( + snapshot: dict | None, + repos: Sequence[str], + *, + now: datetime.datetime | None = None, + max_age_hours: float = DEV_MAX_FEED_AGE_HOURS, + libraries: Sequence[str] | None = None, + required_workflows: dict[str, list[str]] | None = None, + dependencies: dict[str, list[str]] | None = None, + groups: dict[str, str] | None = None, + universe: Sequence[str] | None = None, + release_scope: Sequence[str] | None = None, + ci_workflows: dict[str, list[str]] | None = None, + source: str | None = None, +) -> dict[str, Any]: + """The development-ship verdict for a branch touching ``repos``. + + Pure apart from the policy-file reads its defaults make. GREEN is the only + pass; RED is red CI on ``main`` in scope; STALE is in-scope CI evidence + missing, unfinished or aged, a touched repo Heart does not poll, or a + snapshot older than ``max_age_hours`` (or of unknown age) — re-check, or + park. An in-scope RED outranks staleness: the last known result was + adverse, exactly as the release tiers treat it. Raises ``ValueError`` for + a name the policy file never mentions or an invalid maximum age.""" + snapshot = snapshot or {} + now = now or datetime.datetime.now(datetime.timezone.utc) + max_age_hours = check_max_age_hours(max_age_hours) + libs = list(libraries) if libraries is not None else load_release_gate_names() + req_wf = required_workflows if required_workflows is not None else load_required_workflows() + full = compute(snapshot, libraries=libs, required_workflows=req_wf) + deps = dependencies if dependencies is not None else load_dependencies() + groups_given = groups + groups = groups if groups is not None else load_repo_groups() + if universe is None and groups_given is None: + universe = load_known_repo_names() # live policy: a typo is a usage error + scope = dev_scope(repos, deps, known=list(groups), universe=universe) + red, stale, shown = split_dev_reasons(full, scope["enforced"]) + + if not scope["touched"]: + stale.append("no touched repos stated — the dev-ship scope is unknown") + for name in scope["not_polled"]: + stale.append(f"not polled by Heart: {name}") + + rs = (frozenset(release_scope) if release_scope is not None + else load_release_scope_workflows() if groups_given is None else frozenset()) + ciw = (ci_workflows if ci_workflows is not None + else load_ci_workflows() if groups_given is None else {}) + ci_red, ci_stale, ci_shown = _in_scope_ci(snapshot, scope["enforced"], groups, set(libs), + req_wf, now, max_age_hours, rs, ciw) + red += ci_red + stale += ci_stale + shown += ci_shown + + age = feed_age_hours(snapshot.get("ts"), now) + if age is None: + stale.append("Heart snapshot age unknown (no ts, or dated in the future) " + "— re-check, or park") + elif age > max_age_hours: + stale.append(f"Heart snapshot {age:.1f} h old, over the {max_age_hours:g} h " + "maximum — re-check, or park") + + verdict = "red" if red else ("stale" if stale else "green") + return { + "gate": "dev-ship", + "verdict": verdict, + "pass": verdict == "green", + "remedy": {"red": "fix the failing in-scope CI on main, or park", + "stale": "re-check (refresh the evidence, then ask again), or park", + "green": ""}[verdict], + "scope": scope, + "red_reasons": red, + "yellow_reasons": [], + "stale_reasons": stale, + "reasons": red + stale, + "shown_reasons": shown, + "organism_verdict": full["verdict"], + "source": source or "snapshot passed in", + "feed_ts": snapshot.get("ts"), + "feed_age_hours": None if age is None else round(age, 2), + "max_feed_age_hours": max_age_hours, + "ts": now.isoformat(), + } + + +def render_dev(verdict: dict[str, Any]) -> list[str]: + """The human reading of a ``dev_ship`` verdict.""" + v = str(verdict.get("verdict", "?")) + colour = {"green": c_ok, "red": c_fail}.get(v, c_warn) + glyph = {"green": glyph_ok, "red": glyph_fail}.get(v, glyph_warn) + scope = verdict.get("scope") or {} + head = ", ".join(scope.get("touched") or []) or "?" + if scope.get("dependants"): + head += f" (+ dependants {', '.join(scope['dependants'])})" + age = verdict.get("feed_age_hours") + lines = [c_bold(f"DEV SHIP {head}"), + f" {glyph()} {colour(v.upper())} " + + ("passes" if verdict.get("pass") else f"blocks — {verdict.get('remedy')}"), + c_meta(f" judged: {verdict.get('source')}, " + f"age {'unknown' if age is None else f'{age:.1f} h'} " + f"(max {verdict.get('max_feed_age_hours'):g} h)")] + for t in verdict.get("red_reasons") or []: + lines.append(f" {c_fail('red ')} {t}") + for t in verdict.get("stale_reasons") or []: + lines.append(f" {c_warn('stale')} {t}") + shown = verdict.get("shown_reasons") or [] + if shown: + lines.append(c_info(f" shown, not blocking (organism verdict " + f"{str(verdict.get('organism_verdict', '?')).upper()}):")) + for r in shown: + lines.append(f" {r['severity']:<6} {r['text']}") + return lines + + def render_block(verdict: dict[str, Any], quiet: bool = False) -> list[str]: """The coloured RELEASE READINESS header block. @@ -813,10 +1296,61 @@ def main(argv: list[str] | None = None) -> int: "na_reasons for the scheduled-nightly gate (design §5); default " "is unchanged dev-box behaviour", ) + ap.add_argument( + "--dev", + action="store_true", + help="the development-ship gate: block only on CI on main of --repos " + "and their dependants; every other reason is shown, not " + "blocking; STALE never passes (implied by --repos)", + ) + ap.add_argument( + "--repos", + action="append", + default=[], + metavar="REPO[,REPO...]", + help="the repos the branch touches (repeatable or comma-separated)", + ) + def _max_age(raw: str) -> float: + try: + return check_max_age_hours(raw) + except ValueError as exc: + raise argparse.ArgumentTypeError(str(exc)) from None + + ap.add_argument( + "--max-feed-age-hours", + type=_max_age, + default=DEV_MAX_FEED_AGE_HOURS, + help=f"dev gate: evidence older than this is STALE (default and ceiling " + f"{DEV_MAX_FEED_AGE_HOURS:g}; a smaller positive value is allowed)", + ) ns = ap.parse_args(argv) if ns.no_color: os.environ["NO_COLOR"] = "1" + if ns.dev or ns.repos: + repos = [p.strip() for r in ns.repos for p in r.split(",") if p.strip()] + if not repos: + ap.error("--dev needs --repos: the repos this branch touches") + if ns.profile != "default": + ap.error("--dev reads the dev-box snapshot; it takes no --profile") + # Always a live compute over the dev box's LOCAL snapshot (the tick's + # state.json — not the published cloud feed), never persisted: + # release_ready.json stays the release verdict its consumers expect. + source = f"local snapshot {state.HEART_STATE_FILE}" + try: + dev = dev_ship(state.load() or {}, repos, max_age_hours=ns.max_feed_age_hours, + source=source) + except ValueError as exc: + ap.error(str(exc)) + if ns.json: + json.dump(dev, sys.stdout, indent=2, sort_keys=True) + sys.stdout.write("\n") + return 0 + lines = render_dev(dev) + for line in lines[:2] if ns.quiet else lines: + print(line) + return 0 + if ns.profile != "default": # Profile verdicts are always a live compute and are never persisted: # release_ready.json stays the default-profile artifact its existing diff --git a/heart/state.py b/heart/state.py index ebcff050..491f288d 100644 --- a/heart/state.py +++ b/heart/state.py @@ -133,6 +133,10 @@ def aggregate() -> dict[str, Any]: "verify_install": _read_json_or_default(HEART_STATE_DIR / "verify_install.json", {}), "url_check": _read_json_or_default(HEART_STATE_DIR / "url_check.json", {}), "validation_report": _read_json_or_default(HEART_STATE_DIR / "validation_report.json", {}), + # Whether each rehearsed SHA is still an ancestor of its repo's main + # (heart/checks/rehearsal_ancestry.py, M2.4): readiness keeps a + # rehearsal fresh when main only moved FORWARD from what was built. + "rehearsal_ancestry": _read_json_or_default(HEART_STATE_DIR / "rehearsal_ancestry.json", {}), # The release push-credential proof is COMMITTED (state/token_push.json, # written by token_push_check.yml), not a local cache: every checkout — # dev box, the cloud board, the nightly driver — reads the same file. diff --git a/heart/tick.sh b/heart/tick.sh index 7e4844d4..591b1498 100755 --- a/heart/tick.sh +++ b/heart/tick.sh @@ -52,6 +52,12 @@ PYTHONPATH="$HEART_HOME" python3 -m heart.checks.test_run || heart_log WARN "$(c # local ingest. PYTHONPATH="$HEART_HOME" python3 -m heart.checks.release_run || heart_log WARN "$(c_warn 'release_run failed')" +# Python: is each rehearsed SHA still an ancestor of its main? (M2.4 — a +# release publishes exactly the rehearsed commits, so main moving FORWARD does +# not stale the rehearsal.) One `gh api .../compare` per library whose main +# moved since the rehearsal; none when nothing moved. +PYTHONPATH="$HEART_HOME" python3 -m heart.checks.rehearsal_ancestry || heart_log WARN "$(c_warn 'rehearsal_ancestry 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_ci_backfill.py b/tests/test_ci_backfill.py new file mode 100644 index 00000000..33e8f050 --- /dev/null +++ b/tests/test_ci_backfill.py @@ -0,0 +1,111 @@ +"""tests/test_ci_backfill.py — declared CI absent from the 30-run page is +fetched directly (PyAutoHeart#340), with a fake gh (no network). +""" + +from __future__ import annotations + +import io +import json + +from heart.checks import ci_status + +HEAD = "f" * 40 + + +def run(name, conclusion, sha=HEAD, created="2026-11-12T10:00:00Z"): + return {"name": name, "conclusion": conclusion, "status": "completed", + "head_sha": sha, "created_at": created, "html_url": f"u/{name}", + "head_branch": "main", "event": "push"} + + +def sidecar(*runs): + return ci_status.build_sidecar("OrganRepo", "organism", + {"workflow_runs": list(runs)}, HEAD, "2026-11-12T12:00:00+00:00") + + +class FakeGh: + def __init__(self, ids=None, latest=None, fail=()): + self.ids = ids or {} + self.latest = latest or {} + self.fail = set(fail) + self.calls = [] + + def __call__(self, path): + self.calls.append(path) + if path.endswith("/actions/workflows?per_page=100"): + return None if "list" in self.fail else { + "workflows": [{"name": n, "id": i} for n, i in self.ids.items()]} + wid = int(path.split("/actions/workflows/")[1].split("/")[0]) + name = next(n for n, i in self.ids.items() if i == wid) + if name in self.fail: + return None + return {"workflow_runs": [self.latest[name]]} + + +def test_a_declared_workflow_off_the_page_is_fetched_by_id_and_cached(tmp_path): + sc = sidecar(run("Organ Board", "success")) # the declared gate is not on the page + gh = FakeGh(ids={"Organ Gate": 7, "Organ Board": 8}, + latest={"Organ Gate": run("Organ Gate", "failure", created="2026-11-01T00:00:00Z")}) + cache = tmp_path / "ids" / "OrganRepo.json" + assert ci_status.backfill_declared(sc, "org", ["Organ Gate"], gh, cache) == [] + entry = sc["workflows"]["Organ Gate"] + assert entry["conclusion"] == "failure" and entry["backfilled"] is True + assert entry["on_head"] is True + assert gh.calls == ["repos/org/OrganRepo/actions/workflows?per_page=100", + "repos/org/OrganRepo/actions/workflows/7/runs" + "?branch=main&per_page=1&exclude_pull_requests=true"] + assert json.loads(cache.read_text())["Organ Gate"] == 7 + # Next tick: the id comes from the cache — exactly one call per missing workflow. + gh2 = FakeGh(ids={"Organ Gate": 7}, latest=gh.latest) + sc2 = sidecar(run("Organ Board", "success")) + ci_status.backfill_declared(sc2, "org", ["Organ Gate"], gh2, cache) + assert len(gh2.calls) == 1 and "/workflows/7/runs" in gh2.calls[0] + + +def test_declared_workflows_on_the_page_cost_no_call(tmp_path): + sc = sidecar(run("Organ Gate", "success")) + gh = FakeGh() + assert ci_status.backfill_declared(sc, "org", ["Organ Gate"], gh, tmp_path / "c.json") == [] + assert gh.calls == [] + assert "backfilled" not in sc["workflows"]["Organ Gate"] + + +def test_a_failed_fetch_leaves_it_missing_for_readiness_to_read_stale(tmp_path): + sc = sidecar(run("Organ Board", "success")) + gh = FakeGh(ids={"Organ Gate": 7}, fail={"Organ Gate"}) + assert ci_status.backfill_declared(sc, "org", ["Organ Gate"], gh, tmp_path / "c.json") == ["Organ Gate"] + assert "Organ Gate" not in sc["workflows"] + assert sc["backfill_missing"] == ["Organ Gate"] + gh = FakeGh(fail={"list"}) + assert ci_status.backfill_declared(sc, "org", ["Organ Gate"], gh, tmp_path / "d.json") == ["Organ Gate"] + + +def test_backfill_never_moves_the_release_rollup(tmp_path): + sc = sidecar(run("Organ Board", "success")) + before = (sc["conclusion"], sc["status"], sc["workflow"]) + gh = FakeGh(ids={"Organ Gate": 7}, latest={"Organ Gate": run("Organ Gate", "failure")}) + ci_status.backfill_declared(sc, "org", ["Organ Gate"], gh, tmp_path / "c.json") + assert (sc["conclusion"], sc["status"], sc["workflow"]) == before + + +def test_main_backfills_declared_ci_and_the_dev_gate_sees_it(tmp_path, monkeypatch): + from heart import readiness, state + monkeypatch.setattr(state, "HEART_STATE_DIR", tmp_path) + monkeypatch.setattr(ci_status, "load_declared_ci", lambda name, *a: ["Organ Gate"]) + gh = FakeGh(ids={"Organ Gate": 7}, latest={"Organ Gate": run("Organ Gate", "success")}) + monkeypatch.setattr(ci_status, "gh_api", gh) + monkeypatch.setattr(ci_status, "required_for", lambda group, *a: []) + monkeypatch.setattr("sys.stdin", io.StringIO(json.dumps( + {"workflow_runs": [run("Organ Board", "success")]}))) + out = tmp_path / "OrganRepo.ci_status.json" + ci_status.main(["--name", "OrganRepo", "--owner", "org", "--group", "organism", + "--head-sha", HEAD, "--ts", "2026-11-12T12:00:00+00:00", "--out", str(out)]) + body = json.loads(out.read_text()) + assert body["workflows"]["Organ Gate"]["backfilled"] is True + import datetime + v = readiness.dev_ship( + {"ts": "2026-11-12T12:00:00+00:00", "repos": {"OrganRepo": {"ci_status": body}}}, + ["OrganRepo"], now=datetime.datetime(2026, 11, 12, 13, tzinfo=datetime.timezone.utc), + libraries=[], required_workflows={}, dependencies={"X": []}, + groups={"OrganRepo": "organism"}, ci_workflows={"OrganRepo": ["Organ Gate"]}) + assert v["verdict"] == "green" diff --git a/tests/test_dev_ship.py b/tests/test_dev_ship.py new file mode 100644 index 00000000..2b059d9c --- /dev/null +++ b/tests/test_dev_ship.py @@ -0,0 +1,516 @@ +"""tests/test_dev_ship.py — the development-ship gate (PyAutoHeart#340). + +Human ruling, 2026-11-12: a development ship is blocked only by CI on `main` +of the repos the branch touches and of their dependants; every other reason is +shown, not blocking; evidence older than 6 h is STALE and STALE never passes; +release gating is unchanged. + +The repo names here are synthetic on purpose (a three-library chain, a side +library and two workspaces), so the scoping rules are tested independently of +the live policy file; `test_readiness.py` pins the live graph. +""" + +from __future__ import annotations + +import datetime +import json + +import pytest + +from heart import readiness + +CORE, MID, TOP, SIDE = "CoreLib", "MidLib", "TopLib", "SideLib" +WS, OTHER_WS = "demo_workspace", "other_workspace" +LIBS = [CORE, MID, TOP, SIDE] +# CORE <- MID <- TOP ; SIDE stands alone. +DEPS = {MID: [CORE], TOP: [CORE, MID]} +ORGAN, BUILD, DEV_WS = "ToolRepo", "BuildRepo", "dev_workspace" +GROUPS = {**{lib: "libraries" for lib in LIBS}, WS: "workspaces", OTHER_WS: "workspaces", + ORGAN: "organism", BUILD: "build_workflow", DEV_WS: "workspaces_developer"} +# Named in the policy file but not polled (an `excluded:` entry, say). +UNIVERSE = [*GROUPS, "UnpolledLib"] +REQ_WF = {"workspaces": ["Smoke Tests"]} + +TS = "2026-11-12T12:00:00+00:00" +NOW = datetime.datetime(2026, 11, 12, 13, 0, tzinfo=datetime.timezone.utc) # 1 h later + + +def _lib(conclusion="success", **repo_state): + rs = {"branch": "main", "dirty_real": 0, "behind": 0} + rs.update(repo_state) + return {"ci_status": {"conclusion": conclusion, "head_sha": ""}, "repo_state": rs} + + +def _ws(conclusion="success"): + return {"ci_status": {"group": "workspaces", "conclusion": conclusion, + "workflows": {"Smoke Tests": {"conclusion": conclusion}}}} + + +def snapshot(**repos): + body = {lib: _lib() for lib in LIBS} + body[WS] = _ws() + body[OTHER_WS] = _ws() + body.update(repos) + return {"ts": TS, "repos": body} + + +# Each advisory repo's own CI (config/repos.yaml dev_ship.ci_workflows). +CIW = {ORGAN: ["Organ Tests"], BUILD: ["Organ Tests"], DEV_WS: ["Organ Tests"]} + + +def dev(snap, repos, **kw): + kw.setdefault("now", NOW) + kw.setdefault("ci_workflows", CIW) + return readiness.dev_ship(snap, repos, libraries=LIBS, required_workflows=REQ_WF, + dependencies=DEPS, groups=GROUPS, **kw) + + +# --- scope ----------------------------------------------------------------- + +def test_scope_is_touched_plus_transitive_dependants(): + s = readiness.dev_scope([CORE], DEPS, known=list(GROUPS)) + assert s["touched"] == [CORE] + assert s["dependants"] == [MID, TOP] + assert s["enforced"] == [CORE, MID, TOP] + # Upstream is not a dependant. + assert readiness.dev_scope([TOP], DEPS, known=list(GROUPS))["dependants"] == [] + + +def test_scope_names_match_case_insensitively_and_unknown_names_are_listed(): + s = readiness.dev_scope(["corelib, Demo_Workspace", "NotARepo"], DEPS, known=list(GROUPS)) + assert s["touched"] == [CORE, WS, "NotARepo"] + assert s["not_polled"] == ["NotARepo"] + + +def test_an_in_repo_red_ci_blocks(): + v = dev(snapshot(**{MID: _lib("failure")}), [MID]) + assert v["verdict"] == "red" and v["pass"] is False + assert v["red_reasons"] == [f"{MID}: CI failure"] + + +def test_an_out_of_repo_red_ci_does_not_block_but_is_shown(): + v = dev(snapshot(**{SIDE: _lib("failure")}), [MID]) + assert v["verdict"] == "green" and v["pass"] is True + assert {"severity": "red", "text": f"{SIDE}: CI failure"} in v["shown_reasons"] + assert v["organism_verdict"] == "red" + + +def test_a_dependants_red_ci_blocks(): + """Touching CORE: TOP is a (transitive) dependant, so its red CI blocks.""" + v = dev(snapshot(**{TOP: _lib("failure")}), [CORE]) + assert v["verdict"] == "red" + assert v["red_reasons"] == [f"{TOP}: CI failure"] + assert v["scope"]["dependants"] == [MID, TOP] + + +def test_an_upstream_libraries_red_ci_does_not_block(): + v = dev(snapshot(**{CORE: _lib("failure")}), [TOP]) + assert v["verdict"] == "green" + + +def test_a_touched_workspaces_red_smoke_blocks_and_another_workspaces_does_not(): + snap = snapshot(**{WS: _ws("failure"), OTHER_WS: _ws("failure")}) + v = dev(snap, [WS]) + assert v["verdict"] == "red" + assert v["red_reasons"] == [f"{WS}: Smoke Tests failure on main"] + assert {"severity": "red", "text": f"{OTHER_WS}: Smoke Tests failure on main"} \ + in v["shown_reasons"] + + +def test_release_scope_and_checkout_reasons_never_block_a_dev_ship(): + snap = snapshot(**{MID: _lib(branch="feature/x", dirty_real=3, behind=4)}) + snap["verify_install"] = {"ready": False, "index": "testpypi", + "checks": [{"check": "F", "status": "FAIL"}]} + snap["validation_report"] = {"validation_outcome": "fail", + "stages": {"integrate": {"status": "fail"}}} + v = dev(snap, [MID]) + assert v["verdict"] == "green" and v["pass"] is True + shown = {r["text"] for r in v["shown_reasons"]} + assert f"{MID}: on branch feature/x (not main)" in shown + assert f"{MID}: 4 commit(s) behind origin" in shown + assert any(t.startswith("release validation FAILED") for t in shown) + assert any(t.startswith("install verification FAILED") for t in shown) + # Nothing is dropped: every release reason is shown or blocking. + full = readiness.compute(snap, libraries=LIBS, required_workflows=REQ_WF) + assert len(v["shown_reasons"]) + len(v["reasons"]) == len(full["reasons"]) + + +def test_a_touched_repo_heart_does_not_poll_is_stale_never_green(): + v = dev(snapshot(), ["UnpolledLib", MID], universe=UNIVERSE) + assert v["verdict"] == "stale" and v["pass"] is False + assert v["scope"]["not_polled"] == ["UnpolledLib"] + assert "not polled by Heart: UnpolledLib" in v["stale_reasons"] + + +def test_a_name_the_policy_never_mentions_is_a_usage_error(): + with pytest.raises(ValueError, match="CoreLibb"): + dev(snapshot(), ["CoreLibb"], universe=UNIVERSE) + + +def test_no_touched_repos_is_stale_never_green(): + v = dev(snapshot(), [" , "]) + assert v["verdict"] == "stale" and v["pass"] is False + + +# --- STALE never passes ------------------------------------------------------ + +def test_in_scope_ci_unreadable_is_stale_and_does_not_pass(): + lib = _lib() + lib["ci_status"] = {"error": "gh api 502"} + v = dev(snapshot(**{MID: lib}), [MID]) + assert v["verdict"] == "stale" and v["pass"] is False + assert v["stale_reasons"] == [f"{MID}: CI status unavailable (gh api 502)"] + + +def test_in_scope_library_missing_from_the_snapshot_is_stale(): + snap = snapshot() + del snap["repos"][TOP] + v = dev(snap, [CORE]) # TOP is a dependant of CORE + assert v["verdict"] == "stale" and v["pass"] is False + assert v["stale_reasons"] == [f"{TOP}: status unknown"] + + +def test_in_scope_workspace_not_observed_is_stale(): + snap = snapshot() + del snap["repos"][WS] + v = dev(snap, [WS]) + assert v["verdict"] == "stale" and v["pass"] is False + assert v["stale_reasons"] == [f"{WS}: CI status on main not observed"] + + +def test_an_organism_wide_stale_verdict_is_shown_and_an_aged_one_never_passes(): + """The old dev gate passed an organism-wide STALE. Out-of-scope gaps are + now shown; but the feed itself going stale (age) blocks.""" + snap = snapshot() # no validation report / install run → organism STALE gaps + fresh = dev(snap, [MID]) + assert fresh["verdict"] == "green" + assert any(r["severity"] == "stale" for r in fresh["shown_reasons"]) + aged = dev(snap, [MID], now=NOW + datetime.timedelta(hours=7)) + assert aged["verdict"] == "stale" and aged["pass"] is False + + +def test_pass_is_only_ever_green(): + """No reason the gate enforces is yellow, and a stale verdict never passes.""" + snap = snapshot() + snap["script_timing"] = {"red_count": 2} # a release YELLOW: shown only + v = dev(snap, [MID], now=NOW + datetime.timedelta(hours=10)) + assert v["verdict"] == "stale" and v["pass"] is False + assert v["yellow_reasons"] == [] + assert {"severity": "yellow", "text": "2 script timing regression(s)"} in v["shown_reasons"] + + +# --- the 6 h feed-age rule ---------------------------------------------------- + +def test_default_maximum_feed_age_is_six_hours(): + assert readiness.DEV_MAX_FEED_AGE_HOURS == 6.0 + + +@pytest.mark.parametrize("hours, verdict", [(0.0, "green"), (5.9, "green"), + (6.0, "green"), (6.1, "stale"), (30, "stale")]) +def test_feed_older_than_six_hours_is_stale(hours, verdict): + now = datetime.datetime.fromisoformat(TS) + datetime.timedelta(hours=hours) + v = dev(snapshot(), [MID], now=now) + assert v["verdict"] == verdict + assert v["feed_age_hours"] == pytest.approx(hours, abs=0.01) + assert v["max_feed_age_hours"] == 6.0 + if verdict == "stale": + assert "over the 6 h maximum" in v["stale_reasons"][-1] + assert v["remedy"].startswith("re-check") + + +def test_feed_without_a_timestamp_is_stale(): + snap = snapshot() + del snap["ts"] + v = dev(snap, [MID]) + assert v["verdict"] == "stale" + assert v["feed_age_hours"] is None + + +def test_the_maximum_age_is_configurable(): + later = NOW + datetime.timedelta(hours=2) # feed is 3 h old + assert dev(snapshot(), [MID], now=later, max_age_hours=2)["verdict"] == "stale" + assert dev(snapshot(), [MID], now=later, max_age_hours=4)["verdict"] == "green" + + +def test_an_in_scope_red_outranks_an_aged_feed(): + v = dev(snapshot(**{MID: _lib("failure")}), [MID], + now=NOW + datetime.timedelta(hours=12)) + assert v["verdict"] == "red" + assert v["stale_reasons"] # the age is still said + + +# --- release gating is unchanged --------------------------------------------- + +def test_the_release_verdict_is_untouched_by_the_dev_gate(): + snap = snapshot(**{SIDE: _lib("failure")}) + before = json.dumps(snap, sort_keys=True) + release = readiness.compute(snap, libraries=LIBS, required_workflows=REQ_WF) + v = dev(snap, [MID]) + assert json.dumps(snap, sort_keys=True) == before # no mutation + assert release["verdict"] == "red" + assert v["organism_verdict"] == release["verdict"] + assert readiness.compute(snap, libraries=LIBS, required_workflows=REQ_WF) == release + + +# --- CLI --------------------------------------------------------------------- + +def _cli(monkeypatch, snap): + monkeypatch.setattr(readiness.state, "load", lambda: snap) + monkeypatch.setattr(readiness, "load_dependencies", lambda *a, **k: DEPS) + monkeypatch.setattr(readiness, "load_repo_groups", lambda *a, **k: GROUPS) + monkeypatch.setattr(readiness, "load_known_repo_names", lambda *a, **k: UNIVERSE) + monkeypatch.setattr(readiness, "load_release_gate_names", lambda *a, **k: LIBS) + monkeypatch.setattr(readiness, "load_required_workflows", lambda *a, **k: REQ_WF) + + +def test_cli_dev_json_reports_the_scoped_verdict(monkeypatch, capsys): + snap = snapshot(**{SIDE: _lib("failure")}) + snap["ts"] = datetime.datetime.now(datetime.timezone.utc).isoformat() + _cli(monkeypatch, snap) + assert readiness.main(["--dev", "--repos", f"{MID},{WS}", "--json"]) == 0 + out = json.loads(capsys.readouterr().out) + assert out["gate"] == "dev-ship" + assert out["verdict"] == "green" and out["pass"] is True + assert out["scope"]["touched"] == [MID, WS] + assert out["organism_verdict"] == "red" + + +def test_cli_repos_implies_dev_and_text_render_names_the_scope(monkeypatch, capsys): + snap = snapshot(**{TOP: _lib("failure")}) + snap["ts"] = datetime.datetime.now(datetime.timezone.utc).isoformat() + _cli(monkeypatch, snap) + assert readiness.main(["--repos", CORE, "--no-color"]) == 0 + out = capsys.readouterr().out + assert out.startswith(f"DEV SHIP {CORE} (+ dependants {MID}, {TOP})") + assert "RED" in out and f"{TOP}: CI failure" in out + + +def test_cli_dev_without_repos_is_a_usage_error(monkeypatch): + _cli(monkeypatch, snapshot()) + with pytest.raises(SystemExit) as exc: + readiness.main(["--dev", "--json"]) + assert exc.value.code == 2 + + +def test_cli_dev_refuses_a_release_profile(monkeypatch): + _cli(monkeypatch, snapshot()) + with pytest.raises(SystemExit): + readiness.main(["--repos", MID, "--profile", "release-ci"]) + + +def test_cli_unscoped_call_still_prints_the_release_verdict(monkeypatch, capsys): + release = {"verdict": "red", "red_reasons": ["x"], "reasons": ["x"]} + monkeypatch.setattr(readiness, "load_verdict", lambda: release) + assert readiness.main(["--json"]) == 0 + assert json.loads(capsys.readouterr().out) == release + + +# --- review findings (PyAutoHeart#340 review, 2026-11-12) -------------------- + +def _organ(conclusion="success", status="completed", on_head=True, rolled=None, ts=None): + ci = {"group": "organism", "conclusion": rolled if rolled is not None else conclusion, + "workflows": {"Organ Tests": {"conclusion": conclusion, "status": status, + "on_head": on_head}}} + if ts: + ci["ts"] = ts + return {"ci_status": ci} + + +@pytest.mark.parametrize("repo", [ORGAN, BUILD, DEV_WS]) +def test_red_main_ci_on_a_touched_repo_of_any_group_blocks(repo): + """Finding 1: compute never gates organ / build-workflow / developer- + workspace CI, but red CI on main of a touched one is the branch's.""" + v = dev(snapshot(**{repo: _organ("failure")}), [repo]) + assert v["verdict"] == "red" and v["pass"] is False + assert v["red_reasons"] == [f"{repo}: Organ Tests failure on main"] + + +def test_an_untouched_organs_red_ci_does_not_block(): + v = dev(snapshot(**{ORGAN: _organ("failure")}), [MID]) + assert v["verdict"] == "green" + + +def _drift(lifecycle, spawn): + """Two declared CI workflows, neither on the HEAD; spawn's run is newer.""" + return {"ci_status": {"group": "organism", "conclusion": spawn, "workflows": { + "Lifecycle Drift": {"conclusion": lifecycle, "status": "completed", + "on_head": False, "created_at": "2026-11-12T10:00:00Z"}, + "Spawn Drift": {"conclusion": spawn, "status": "completed", + "on_head": False, "created_at": "2026-11-12T11:00:00Z"}}}} + + +DRIFT_CIW = {ORGAN: ["Lifecycle Drift", "Spawn Drift"]} + + +def test_each_declared_workflows_latest_run_is_judged_a_newer_green_never_hides_a_red(): + """Must-fix: a red Lifecycle Drift at 10:00 hidden by a green Spawn Drift + at 11:00 used to read GREEN.""" + v = dev(snapshot(**{ORGAN: _drift("failure", "success")}), [ORGAN], ci_workflows=DRIFT_CIW) + assert v["verdict"] == "red" + assert v["red_reasons"] == [f"{ORGAN}: Lifecycle Drift failure on main"] + ok = dev(snapshot(**{ORGAN: _drift("success", "success")}), [ORGAN], ci_workflows=DRIFT_CIW) + assert ok["verdict"] == "green" + pending = dev(snapshot(**{ORGAN: _drift("", "success")}), [ORGAN], ci_workflows=DRIFT_CIW) + assert pending["verdict"] == "stale" + assert pending["stale_reasons"] == [f"{ORGAN}: Lifecycle Drift on main has no conclusion yet"] + + +def test_a_declared_workflow_missing_from_the_ci_status_page_is_stale_not_skipped(): + """Must-fix: e.g. a gate that has not run within the 30-run page.""" + ciw = {ORGAN: ["Lifecycle Drift", "Spawn Drift", "Tenant Firewall Gate"]} + v = dev(snapshot(**{ORGAN: _drift("success", "success")}), [ORGAN], ci_workflows=ciw) + assert v["verdict"] == "stale" and v["pass"] is False + assert v["stale_reasons"] == [f"{ORGAN}: Tenant Firewall Gate has no recorded run on " + "main (not in the CI status page) — cannot be judged"] + # A red elsewhere still outranks the gap. + v = dev(snapshot(**{ORGAN: _drift("success", "failure")}), [ORGAN], ci_workflows=ciw) + assert v["verdict"] == "red" + + +def test_an_ops_workflow_never_blocks_but_is_shown(): + """Review finding: a scheduled board/sweep failing must not block a ship.""" + def organ(on_head): + return {"ci_status": {"group": "organism", "conclusion": "failure", "workflows": { + "Organ Tests": {"conclusion": "success", "status": "completed", + "on_head": on_head, "created_at": "2026-11-12T08:00:00Z"}, + "Organ Board": {"conclusion": "failure", "status": "completed", + "on_head": on_head, "created_at": "2026-11-12T11:00:00Z"}}}} + on = dev(snapshot(**{ORGAN: organ(True)}), [ORGAN]) + assert on["verdict"] == "green" + assert {"severity": "red", "text": f"{ORGAN}: Organ Board failure on main " + "(ops workflow — not CI, not blocking)"} in on["shown_reasons"] + # Nothing on HEAD: the newest CI run decides, not the newer ops run. + assert dev(snapshot(**{ORGAN: organ(False)}), [ORGAN])["verdict"] == "green" + + +def test_an_advisory_repo_without_declared_ci_is_stale_and_empty_means_no_ci(): + snap = snapshot(**{ORGAN: _organ("success")}) + v = dev(snap, [ORGAN], ci_workflows={}) + assert v["verdict"] == "stale" + assert v["stale_reasons"][0].startswith(f"{ORGAN}: no CI workflows declared") + assert dev(snap, [ORGAN], ci_workflows={ORGAN: []})["verdict"] == "green" + + +def test_declared_ci_with_no_recorded_run_is_stale(): + snap = snapshot(**{ORGAN: _organ("success")}) + v = dev(snap, [ORGAN], ci_workflows={ORGAN: ["Other Tests"]}) + assert v["verdict"] == "stale" + assert v["stale_reasons"][0].startswith(f"{ORGAN}: Other Tests has no recorded run on main") + + +def test_an_organ_with_ci_unfinished_or_unobserved_is_stale(): + v = dev(snapshot(**{ORGAN: _organ("", status="in_progress")}), [ORGAN]) + assert v["verdict"] == "stale" + assert v["stale_reasons"] == [f"{ORGAN}: Organ Tests on main has no conclusion yet"] + v = dev(snapshot(), [ORGAN]) # polled, but absent from the snapshot + assert v["verdict"] == "stale" + assert v["stale_reasons"] == [f"{ORGAN}: CI status on main not observed"] + + +def test_a_future_snapshot_beyond_clock_skew_is_stale_not_fresh(): + """Finding 3: a negative age used to clamp to 0 and read as fresh.""" + now = datetime.datetime.fromisoformat(TS) + assert readiness.feed_age_hours(TS, now - datetime.timedelta(minutes=4)) == 0.0 + assert readiness.feed_age_hours(TS, now - datetime.timedelta(minutes=6)) is None + assert dev(snapshot(), [MID], now=now - datetime.timedelta(minutes=4))["verdict"] == "green" + v = dev(snapshot(), [MID], now=now - datetime.timedelta(hours=1)) + assert v["verdict"] == "stale" and v["feed_age_hours"] is None + + +@pytest.mark.parametrize("bad", [float("nan"), float("inf"), -1, 0, 6.5, "x"]) +def test_max_feed_age_must_be_finite_positive_and_at_most_six(bad): + """Finding 4.""" + with pytest.raises(ValueError): + readiness.check_max_age_hours(bad) + with pytest.raises(ValueError): + dev(snapshot(), [MID], max_age_hours=bad) + + +def test_max_feed_age_accepts_up_to_the_ceiling(): + assert readiness.check_max_age_hours("6") == 6.0 + assert readiness.check_max_age_hours(0.5) == 0.5 + + +@pytest.mark.parametrize("bad", ["nan", "inf", "-2", "0", "12"]) +def test_cli_rejects_a_bad_max_feed_age(monkeypatch, bad): + _cli(monkeypatch, snapshot()) + with pytest.raises(SystemExit) as exc: + readiness.main(["--repos", MID, "--max-feed-age-hours", bad]) + assert exc.value.code == 2 + + +def test_cli_unknown_repo_name_is_a_usage_error(monkeypatch): + _cli(monkeypatch, snapshot()) + with pytest.raises(SystemExit) as exc: + readiness.main(["--repos", "MidLibb", "--json"]) + assert exc.value.code == 2 + + +def test_in_scope_library_with_no_conclusion_is_stale(): + """Finding 5: a library mid-run (conclusion empty) used to read GREEN.""" + lib = _lib("") + lib["ci_status"]["status"] = "in_progress" + v = dev(snapshot(**{MID: lib}), [MID]) + assert v["verdict"] == "stale" and v["pass"] is False + assert v["stale_reasons"] == [f"{MID}: CI on main has no conclusion yet (in_progress)"] + + +def test_in_scope_workspace_required_workflow_with_no_conclusion_is_stale(): + ws = _ws() + ws["ci_status"]["workflows"]["Smoke Tests"]["conclusion"] = None + v = dev(snapshot(**{WS: ws}), [WS]) + assert v["verdict"] == "stale" + assert v["stale_reasons"] == [f"{WS}: Smoke Tests on main has no conclusion yet"] + + +def test_in_scope_evidence_is_aged_by_its_own_collection_time(): + """Finding 5: a fresh aggregation over an old sidecar is not fresh evidence.""" + old = (NOW - datetime.timedelta(hours=8)).isoformat() + lib = _lib() + lib["ci_status"]["ts"] = old + v = dev(snapshot(**{MID: lib}), [MID]) # snapshot itself is 1 h old + assert v["verdict"] == "stale" + assert v["stale_reasons"][0].startswith(f"{MID}: CI evidence 8.0 h old") + lib["ci_status"]["ts"] = (NOW - datetime.timedelta(hours=2)).isoformat() + assert dev(snapshot(**{MID: lib}), [MID])["verdict"] == "green" + # Out-of-scope aged evidence does not block. + side = _lib() + side["ci_status"]["ts"] = old + assert dev(snapshot(**{SIDE: side}), [MID])["verdict"] == "green" + + +def test_the_cli_names_the_local_snapshot_it_judged_and_its_age(monkeypatch, capsys): + """Finding 6: the reader must know it is the dev box's local state.json, + not the published cloud feed the event triggers refresh.""" + snap = snapshot() + snap["ts"] = datetime.datetime.now(datetime.timezone.utc).isoformat() + _cli(monkeypatch, snap) + readiness.main(["--repos", MID, "--no-color"]) + out = capsys.readouterr().out + assert f"judged: local snapshot {readiness.state.HEART_STATE_FILE}, age 0.0 h" in out + readiness.main(["--repos", MID, "--json"]) + j = json.loads(capsys.readouterr().out) + assert j["source"] == f"local snapshot {readiness.state.HEART_STATE_FILE}" + assert j["feed_age_hours"] == pytest.approx(0.0, abs=0.01) + + +def test_release_scope_workflows_in_an_organ_never_count_as_its_own_ci(): + """Release Integrate failing on an organ's main HEAD is the release + question (shown in the release verdict), not the organ's own CI.""" + ci = {"group": "organism", "conclusion": "failure", "workflows": { + "Release Integrate": {"conclusion": "failure", "status": "completed", "on_head": True, + "created_at": "2026-11-12T11:00:00Z"}, + "Organ Tests": {"conclusion": "success", "status": "completed", "on_head": True, + "created_at": "2026-11-12T10:00:00Z"}}} + snap = snapshot(**{ORGAN: {"ci_status": ci}}) + assert dev(snap, [ORGAN], release_scope=["Release Integrate"])["verdict"] == "green" + # Even if someone declared it as CI, release scope is still the ruling's + # "shown, not enforced" — but declaration is explicit, so it would count. + assert dev(snap, [ORGAN], release_scope=[], + ci_workflows={ORGAN: ["Organ Tests", "Release Integrate"]})["verdict"] == "red" + v = dev(snap, [ORGAN], release_scope=["Release Integrate"]) + assert not any("Release Integrate" in r["text"] for r in v["shown_reasons"]) + # With nothing on HEAD, the newest non-release run decides, not the rollup. + for e in ci["workflows"].values(): + e["on_head"] = False + assert dev(snap, [ORGAN], release_scope=["Release Integrate"])["verdict"] == "green" diff --git a/tests/test_heart_health_wiring.py b/tests/test_heart_health_wiring.py index 7194b882..e65d112f 100644 --- a/tests/test_heart_health_wiring.py +++ b/tests/test_heart_health_wiring.py @@ -153,3 +153,52 @@ def test_cloud_reads_validation_before_aggregation(): assert 'python -m heart.checks.test_run' in body assert 'python -m heart.checks.cloud_validation' in body assert _step_index(job, 'Run cloud-safe checks') < _step_index(job, 'Aggregate snapshot') + + +# --- event triggers refresh the feed (PyAutoHeart#340) ---------------------- + +def _triggers(name): + # PyYAML parses the bare `on:` key as boolean True. + return yaml.safe_load((WORKFLOWS / name).read_text())[True] + + +def test_the_daily_cron_stays_as_the_backstop(): + on = _triggers("heart-health.yml") + assert on["schedule"] == [{"cron": "0 5 * * *"}] + assert "workflow_dispatch" in on + + +def test_a_heart_refresh_dispatch_and_a_release_rehearsal_refresh_the_feed(): + on = _triggers("heart-health.yml") + assert on["repository_dispatch"] == {"types": ["heart-refresh"]} + assert on["workflow_run"]["workflows"] == ["Release Integrate"] + assert on["workflow_run"]["types"] == ["completed"] + # The watched workflow exists under that exact display name. + names = {yaml.safe_load(p.read_text()).get("name") for p in WORKFLOWS.glob("*.yml")} + assert "Release Integrate" in names + + +def test_bursts_of_events_coalesce_rather_than_cancel_a_publish(): + data, _ = _job() + assert data["concurrency"]["cancel-in-progress"] is False + + +def test_library_ci_on_main_sends_the_heart_refresh_event(): + """The sender lives in the reusable library gate every library calls, so a + library merge refreshes the feed with no edit in the library repos.""" + jobs = yaml.safe_load((WORKFLOWS / "lib-tests.yml").read_text())["jobs"] + job = jobs["heart-refresh"] + assert set(job["needs"]) == {"unittest", "unittest-nojax"} + cond = job["if"] + assert "always()" in cond + assert "github.event_name == 'push'" in cond + assert "github.ref == 'refs/heads/main'" in cond + # Never reds the library's required check. + assert job["continue-on-error"] is True + mint = next(s for s in job["steps"] if s.get("id") == "app_token") + assert mint["with"]["permission-contents"] == "write" + send = job["steps"][-1]["run"] + assert "/PyAutoHeart/dispatches" in send + assert "event_type=heart-refresh" in send + # The event type sent is the one heart-health.yml listens for. + assert "heart-refresh" in _triggers("heart-health.yml")["repository_dispatch"]["types"] diff --git a/tests/test_readiness.py b/tests/test_readiness.py index a1cadb6c..60ab7af0 100644 --- a/tests/test_readiness.py +++ b/tests/test_readiness.py @@ -1254,3 +1254,76 @@ def test_token_push_refusal_dominates_staleness(): v = compute(make_snapshot(token_push=tp)) assert v["verdict"] == "red" assert not any("push credential check stale" in r for r in v["stale_reasons"]) + + +# --- the development-ship scope reads the live dependency graph (#340) ------- + +def test_live_dependency_graph_gives_each_library_its_downstream_dependants(): + deps = readiness.load_dependencies() + assert readiness.dependants_of(["PyAutoNerves"], deps) == set(LIBS) - {"PyAutoNerves"} + assert readiness.dependants_of(["PyAutoFit"], deps) == {"PyAutoGalaxy", "PyAutoLens", "PyAutoCTI"} + assert readiness.dependants_of(["PyAutoArray"], deps) == {"PyAutoGalaxy", "PyAutoLens", "PyAutoCTI"} + assert readiness.dependants_of(["PyAutoGalaxy"], deps) == {"PyAutoLens"} + assert readiness.dependants_of(["PyAutoLens"], deps) == set() + assert readiness.dependants_of(["PyAutoCTI"], deps) == set() + + +def test_live_dependency_graph_names_only_polled_libraries(): + deps = readiness.load_dependencies() + libs = set(readiness.load_library_names()) + assert set(deps) <= libs + assert {u for ups in deps.values() for u in ups} <= libs + + +def test_live_dev_ship_for_a_library_branch_blocks_on_a_dependants_ci_only(): + snap = make_snapshot() + snap["repos"]["PyAutoGalaxy"]["ci_status"]["conclusion"] = "failure" + snap["repos"]["PyAutoLens"]["repo_state"]["behind"] = 3 # checkout state: shown + now = readiness._parse_ts(snap["ts"]) + fit = readiness.dev_ship(snap, ["PyAutoFit"], now=now, libraries=LIBS) + assert fit["verdict"] == "red" + assert fit["red_reasons"] == ["PyAutoGalaxy: CI failure"] + lens = readiness.dev_ship(snap, ["PyAutoLens"], now=now, libraries=LIBS) + assert lens["verdict"] == "green" + assert {"severity": "red", "text": "PyAutoLens: 3 commit(s) behind origin"} in lens["shown_reasons"] + + +def test_missing_dependency_graph_fails_loudly(tmp_path): + cfg = tmp_path / "repos.yaml" + cfg.write_text("repos: {}\n") + with pytest.raises(ValueError): + readiness.load_dependencies(cfg) + + +def test_live_excluded_repos_are_known_but_read_not_polled(): + import yaml + excluded = yaml.safe_load(readiness.CONFIG_PATH.read_text())["excluded"] + groups = readiness.load_repo_groups() + known = set(readiness.load_known_repo_names()) + assert set(excluded) <= known + s = readiness.dev_scope(excluded[:2], readiness.load_dependencies(), + known=list(groups), universe=sorted(known)) + assert s["not_polled"] == excluded[:2] + + +def test_live_typo_in_a_repo_name_is_a_usage_error(): + with pytest.raises(ValueError, match="PyAutoFitt"): + readiness.dev_ship(make_snapshot(), ["PyAutoFitt"]) + + +def test_live_release_scope_workflows_cover_the_release_gate_workflows(): + rs = readiness.load_release_scope_workflows() + assert {"Release Integrate", "Workspace Smoke", "Python Version Matrix", + "Nightly Release"} <= rs + + +def test_live_every_polled_advisory_repo_declares_its_ci_workflows(): + """An undeclared advisory repo reads STALE at every ship; keep the + declaration complete for the polled set, and naming only polled repos.""" + groups = readiness.load_repo_groups() + ciw = readiness.load_ci_workflows() + gated = {"libraries"} | set(readiness.GATED_WORKSPACE_GROUPS) + advisory = {n for n, g in groups.items() if g not in gated} + assert advisory == set(ciw) + rs = readiness.load_release_scope_workflows() + assert not any(set(w) & rs for w in ciw.values()) diff --git a/tests/test_rehearsal_ancestry.py b/tests/test_rehearsal_ancestry.py new file mode 100644 index 00000000..37be6594 --- /dev/null +++ b/tests/test_rehearsal_ancestry.py @@ -0,0 +1,182 @@ +"""tests/test_rehearsal_ancestry.py — M2.4: a rehearsal stays fresh while main +only moves FORWARD from the rehearsed commits (PyAutoHands#337 partner). + +Offline: the GitHub compare API is the injected ``api`` seam. Repo names are +synthetic; readiness is driven with an explicit library list. +""" + +from __future__ import annotations + +import datetime + +import pytest + +from heart import readiness +from heart.checks import rehearsal_ancestry as ra + +LIBS = ["LibOne", "LibTwo"] +OWNERS = {lib: "some-org" for lib in LIBS} +REHEARSED = {"LibOne": "a" * 40, "LibTwo": "b" * 40} +TS = "2026-11-12T00:00:00+00:00" + + +@pytest.fixture(autouse=True) +def _synthetic_gate(monkeypatch): + # The SHA leg walks the module-level release-gate tuple; point it at the + # synthetic libraries so the test stays free of live repo names. + monkeypatch.setattr(readiness, "_GATE_SHA_LIBS", tuple(LIBS)) + + +def snapshot(heads=None, ancestry=None): + heads = heads or dict(REHEARSED) + snap = { + "ts": TS, + "repos": {lib: {"ci_status": {"conclusion": "success", "head_sha": heads[lib]}, + "repo_state": {"branch": "main", "dirty_real": 0, "behind": 0}} + for lib in LIBS}, + "test_run": {"ready": True, "passed": 1, "failed": 0, "ts": TS}, + "script_timing": {}, "version_skew": {"workspaces": []}, + "verify_install": {"ready": True, "ts": TS, "index": "pypi", "checks": []}, + "validation_report": {"validation_outcome": "pass", "release_ready": True, + "profile": "release", "commit_shas": dict(REHEARSED), + "stages": {}, "ts": TS}, + "token_push": {"checked_at": TS, "identity": "bot", + "repos": {lib: {"push": True} for lib in LIBS}}, + } + if ancestry is not None: + snap["rehearsal_ancestry"] = ancestry + return snap + + +def fake_api(statuses): + """compare API stub: repo -> (status, ahead_by).""" + calls = [] + + def api(path): + calls.append(path) + repo = path.split("/")[2] + status, ahead = statuses[repo] + return {"status": status, "ahead_by": ahead} + api.calls = calls + return api + + +def compute(snap): + return readiness.compute(snap, libraries=LIBS, required_workflows={}) + + +def test_unmoved_main_needs_no_compare_and_is_green(): + api = fake_api({}) + side = ra.collect(snapshot(), OWNERS, api) + assert side["repos"] == {} and api.calls == [] + assert compute(snapshot(ancestry=side))["verdict"] == "green" + + +def test_rehearsed_sha_an_ancestor_of_main_stays_fresh_and_says_how_far_ahead(): + heads = {"LibOne": "c" * 40, "LibTwo": REHEARSED["LibTwo"]} + api = fake_api({"LibOne": ("ahead", 3)}) + side = ra.collect(snapshot(heads), OWNERS, api) + assert api.calls == [f"repos/some-org/LibOne/compare/{'a' * 40}...{'c' * 40}"] + assert side["repos"]["LibOne"]["ancestor"] is True + v = compute(snapshot(heads, side)) + assert v["verdict"] == "green" + assert not any("release validation" in r for r in v["reasons"]) + assert v["validation_ahead"] == {"LibOne": 3} + assert "main is ahead by LibOne 3 commit(s)" in v["validation_note"] + + +def test_rehearsed_sha_not_an_ancestor_is_stale(): + heads = {"LibOne": "c" * 40, "LibTwo": "d" * 40} + side = ra.collect(snapshot(heads), OWNERS, + fake_api({"LibOne": ("ahead", 2), "LibTwo": ("diverged", 0)})) + assert side["repos"]["LibTwo"]["ancestor"] is False + v = compute(snapshot(heads, side)) + assert v["verdict"] == "stale" + assert any("not an ancestor of main (LibTwo)" in r for r in v["stale_reasons"]) + assert v["stale_details"][0]["key"] == "validation_stale_sha" + + +def test_missing_ancestry_record_is_stale(): + heads = {"LibOne": "c" * 40, "LibTwo": REHEARSED["LibTwo"]} + v = compute(snapshot(heads)) # no rehearsal_ancestry sidecar at all + assert v["verdict"] == "stale" + assert any("source moved since rehearsal (LibOne; ancestry unproven)" in r + for r in v["stale_reasons"]) + assert v["validation_ahead"] == {} + + +def test_a_record_for_a_different_head_or_a_failed_compare_is_not_proof(): + heads = {"LibOne": "c" * 40, "LibTwo": REHEARSED["LibTwo"]} + side = ra.collect(snapshot(heads), OWNERS, fake_api({"LibOne": ("ahead", 1)})) + moved_again = {"LibOne": "e" * 40, "LibTwo": REHEARSED["LibTwo"]} + assert compute(snapshot(moved_again, side))["verdict"] == "stale" + failed = ra.collect(snapshot(heads), OWNERS, lambda path: {}) + assert failed["repos"]["LibOne"]["error"] == "compare unavailable" + assert compute(snapshot(heads, failed))["verdict"] == "stale" + + +def test_main_behind_the_rehearsed_commit_is_not_an_ancestor(): + heads = {"LibOne": "c" * 40, "LibTwo": REHEARSED["LibTwo"]} + side = ra.collect(snapshot(heads), OWNERS, fake_api({"LibOne": ("behind", 0)})) + assert compute(snapshot(heads, side))["verdict"] == "stale" + + +def test_sidecar_is_folded_into_the_snapshot(): + src = (readiness.HEART_HOME / "heart" / "state.py").read_text() + assert '"rehearsal_ancestry": _read_json_or_default(' in src + + +def test_check_is_wired_into_the_tick_and_the_cloud_job(): + home = readiness.HEART_HOME + assert "heart.checks.rehearsal_ancestry" in (home / "heart" / "tick.sh").read_text() + assert "heart.checks.rehearsal_ancestry" in ( + home / ".github" / "workflows" / "heart-health.yml").read_text() + + +def test_live_owner_map_is_the_release_gate_libraries(): + assert set(ra.library_owners()) == set(readiness.load_release_gate_names()) + + +def test_sidecar_carries_its_collection_time(): + now = datetime.datetime(2026, 11, 12, tzinfo=datetime.timezone.utc) + assert ra.collect(snapshot(), OWNERS, fake_api({}), now=now)["checked_at"] == now.isoformat() + + +def test_compare_calls_run_under_one_total_budget_and_timeouts_are_stale(): + """Review finding: bound total gh time; a call not back in time is unknown.""" + import threading + import time + release = threading.Event() + + def slow_api(path): + release.wait(5) + return {"status": "ahead", "ahead_by": 1} + + heads = {"LibOne": "c" * 40, "LibTwo": "d" * 40} + t0 = time.monotonic() + side = ra.collect(snapshot(heads), OWNERS, slow_api, budget_s=0.2) + elapsed = time.monotonic() - t0 + release.set() + assert elapsed < 2 # both calls shared one 0.2 s budget, in parallel + assert {r["error"] for r in side["repos"].values()} == {"timeout"} + assert compute(snapshot(heads, side))["verdict"] == "stale" + + +def test_main_writes_only_its_own_sidecar_and_never_aggregates(tmp_path, monkeypatch): + import json + import heart.state as state_mod + (tmp_path / "per-repo").mkdir() + (tmp_path / "per-repo" / "LibOne.ci_status.json").write_text( + json.dumps({"head_sha": "c" * 40})) + (tmp_path / "validation_report.json").write_text( + json.dumps({"commit_shas": {"LibOne": "a" * 40}})) + monkeypatch.setattr(state_mod, "HEART_STATE_DIR", tmp_path) + monkeypatch.setattr(state_mod, "aggregate", + lambda: (_ for _ in ()).throw(AssertionError("aggregated"))) + monkeypatch.setattr(ra, "library_owners", lambda *a, **k: {"LibOne": "some-org"}) + monkeypatch.setattr(ra, "gh_api", lambda path: {"status": "ahead", "ahead_by": 4}) + assert ra.main([]) == 0 + assert sorted(p.name for p in tmp_path.iterdir()) == [ + "per-repo", "rehearsal_ancestry.json", "validation_report.json"] + side = json.loads((tmp_path / "rehearsal_ancestry.json").read_text()) + assert side["repos"]["LibOne"]["ahead_by"] == 4