diff --git a/.github/workflows/heart-health.yml b/.github/workflows/heart-health.yml index c1405a3d..77ea25d4 100644 --- a/.github/workflows/heart-health.yml +++ b/.github/workflows/heart-health.yml @@ -4,8 +4,9 @@ name: Heart Health # the ONE unified health dashboard (heart/dashboard.py) alongside the existing # alerting. # -# It runs the two checks that need only the GitHub API (no local working tree) — -# CI status and open PRs — across every polled repo, then: +# It runs the four checks that need only the GitHub API (no local working tree) — +# CI status, open PRs, CI wall-clock timing and the NO_RUN census — across every +# polled repo, then: # 1. renders the unified board (one renderer, many formats) and publishes it # three ways, all from the SAME snapshot so they cannot disagree: # * GitHub Pages — self-contained fmt="html" + a shields badge.json @@ -72,13 +73,21 @@ jobs: - name: Install PyYAML run: pip install --quiet pyyaml - - name: Run cloud-safe checks (ci_status, open_prs) + - name: Run cloud-safe checks (ci_status, open_prs, ci_timing, no_run_census) env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | + # Four API-only checks: CI conclusions and open PRs (health), then CI + # wall-clock and the NO_RUN census (the ⏱ performance surface). + # ci_timing's aggregate step re-reads the board.json published by the + # previous run to carry its own per-gate history forward; a fetch + # failure there costs a sparkline, never the render. `set +e` keeps a + # single broken check from aborting the board. set +e bash heart/checks/ci_status.sh bash heart/checks/open_prs.sh + bash heart/checks/ci_timing.sh + bash heart/checks/no_run_census.sh exit 0 - name: Aggregate snapshot + compute readiness verdict diff --git a/config/repos.yaml b/config/repos.yaml index f0322a82..7914017b 100644 --- a/config/repos.yaml +++ b/config/repos.yaml @@ -100,6 +100,22 @@ required_workflows: workspaces_test: ["Smoke Tests"] # smoke_tests.yml howto: ["Smoke Tests", "Navigator Check"] # smoke_tests.yml + navigator_check.yml +# Performance policy: the extra workflows `ci_timing` times BEYOND each group's +# `required_workflows` above. Those required gates are timed automatically (the +# speed row and the health row must be about the same workflows); this block is +# for the scheduled, full-surface drivers that gate nothing per-PR but whose +# wall-clock is exactly what a slow-down would show up in first — the weekly +# full workspace smoke sweep and the nightly release driver. +# +# Keyed by workflow *display name* (the `name:` field), same convention as +# `required_workflows`, matched against the run's `name` in the Actions API. +performance: + extra_workflows: + - repo: PyAutoHeart + workflow: "Workspace Smoke" + - repo: PyAutoBrain + workflow: "Nightly Release" + # Version-skew policy: workspace pin vs installed library. Iterated directly # by heart/checks/version_skew.py — independent of polling (includes unpolled # repos like the assistant). An adopter replaces this with their own map. @@ -205,6 +221,17 @@ thresholds: ci_status: failure_red: true # any latest=failure → red in_progress_yellow: true + # CI wall-clock drift (heart/checks/ci_timing.py). A gate is flagged only when + # today's median is BOTH >= yellow_factor x its own recent history AND at + # least min_delta_s slower in absolute terms. Both gates, deliberately: the + # ratio alone screams at jitter (host load alone has produced 7x errors in + # this corpus, and an alarm that cries wolf gets ignored), while the absolute + # floor alone would miss a large relative drift on a cheap gate. Advisory — + # a slowed gate never reds the readiness verdict. + ci_timing: + yellow_factor: 1.5 # median / recent-history median >= this, AND + min_delta_s: 120 # ... at least this many seconds slower + history_cap: 30 # days of self-carried per-gate history worktree_drift: orphan_red: true # orphan WT with uncommitted work → red orphan_yellow: true # orphan WT (clean) → yellow diff --git a/heart/checks/ci_timing.py b/heart/checks/ci_timing.py new file mode 100644 index 00000000..f7c00b5a --- /dev/null +++ b/heart/checks/ci_timing.py @@ -0,0 +1,673 @@ +"""heart/checks/ci_timing.py — CI wall-clock per tracked workflow (the speed leg). + +The speed of development is the speed of the gates a change must pass, and +until now that number was only recoverable by hand-scraping job logs: every +timing diagnosis in the record ("the diagnosis had to be rebuilt from CI job +logs by hand") started with an archaeology session. This check makes the +wall-clock of every tracked gate a *standing* observation — measured daily from +the Actions REST API, carried forward with its own history, and rendered on the +board with a ready-to-paste prompt on every actionable row. + +Two modes, same module: + +* **per-repo** (``--name/--group/--owner``) — the bash entry point pipes one + repo's ``GET /repos/{owner}/{repo}/actions/runs`` payload in; we time each + tracked workflow and write ``$HEART_PER_REPO_DIR/.ci_timing.json``. +* **aggregate** (``--aggregate``) — read every sidecar plus the *previously + published* ``board.json`` and write the global rollup at + ``$HEART_STATE_DIR/ci_timing.json``: per-gate numbers, drift classification + against the gate's own history, the rolled-forward history, and the events. + +Deliberate choices, each one a recorded lesson: + +* **duration = ``updated_at`` − ``run_started_at``, never ``created_at``.** A + re-attempted run keeps its original ``created_at``, so the ``created_at`` + arithmetic reports multi-day durations for runs that took nine minutes. Runs + with no ``run_started_at`` are skipped outright rather than guessed at. +* **No branch filter, no ``exclude_pull_requests``.** The contributor-facing + number *is* the PR gate: what someone waits on before a merge. ``pull_request`` + runs are the point of the query, and are also medianed separately + (``pr_median_s``) from everything else. +* **Medians over ``success`` runs only.** A failed run stops early and a + cancelled one stops arbitrarily; pooling them into the median makes a gate + look faster the more it breaks. The conclusion *mix* is recorded beside the + median so the coverage behind the number stays visible. +* **``cancelled`` is disambiguated, not counted.** The concurrency block + cancels superseded PR runs by design — benign. A ``cancelled`` run on ``main``, + or one with no newer run of the same workflow on the same branch, is a + kill/hang suspect and becomes an *event*. ``timed_out`` is always an event. +* **Drift needs BOTH gates.** A gate is flagged ``warn`` only when today's + median is ≥ ``yellow_factor`` × its recent history *and* ≥ ``min_delta_s`` + above it in absolute terms — the profiling conductor's doctrine. The ratio + alone screams at jitter on fast gates; the absolute floor alone misses a big + relative drift on a cheap one, and an alarm that cries wolf gets ignored. +* **Drift is advisory.** Gates are ``ok`` or ``warn``, never ``fail``; only + events (hangs, kill-timer suspects) are hard rows. The four-tier readiness + verdict is untouched by this check — it is a dashboard leg, not a gate. +* **A failed fetch is not a quiet repo.** ``--fetch-error`` records the reason + and writes empty ``workflows``/``events``; "we could not ask" must never + render as "all quiet". + +Per-repo sidecar schema (``.ci_timing.json``):: + + { + "name": "RepoA", "group": "workspaces", "owner": "OwnerX", + "error": "", # non-empty => the runs fetch failed + "ts": "...", + "workflows": { + "Smoke Tests": { + "median_s": 553.0, # p50 over SUCCESS runs (all events) + "pr_median_s": 601.0, # p50 over SUCCESS pull_request runs + "queue_median_s": 12.0, # p50 queue delay over the same runs + "max_s": 912.0, "runs_counted": 14, + "window_from": "2026-08-17T...", + "conclusions": {"success": 14, "failure": 1, "cancelled": 3, + "timed_out": 0}, + "superseded": 2, # of those `cancelled`, benign ones + "actions_url": "https://github.com/OwnerX/RepoA/actions" + } + }, + "events": [{"kind": "timed_out", "workflow": ..., "run_url": ..., + "duration_s": ..., "head_branch": ..., "at": ..., + "prompt": "/bug kill timer: ..."}] + } + +Global rollup schema (``ci_timing.json``):: + + {"ts", "gates": [...], "history": [...], "events": [...], + "errors": [{"repo", "error"}], "thresholds": {...}} + +Every actionable row — a warn gate, an event — carries its own ready-to-paste +prompt string. The producer writes the prompt; the renderer never re-derives it. +""" + +from __future__ import annotations + +import argparse +import datetime +import json +import statistics +import sys +from pathlib import Path +from typing import Any + +HEART_HOME = Path(__file__).resolve().parents[2] +CONFIG_PATH = HEART_HOME / "config" / "repos.yaml" + +# Conclusions whose *count* is recorded per workflow. `cancelled` is recorded +# raw (superseded PR runs included) with the benign share reported separately +# as `superseded`, so the mix always adds up to what the API actually said. +TRACKED_CONCLUSIONS = ("success", "failure", "cancelled", "timed_out") + +# Fallback when config/repos.yaml is unreadable; kept in sync with the YAML. +DEFAULT_CI_TIMING_THRESHOLDS = { + "yellow_factor": 1.5, + "min_delta_s": 120, + "history_cap": 30, +} + + +# --- config ------------------------------------------------------------------ +def _load_config(config_path: Path | str = CONFIG_PATH) -> dict[str, Any]: + try: + import yaml + + cfg = yaml.safe_load(Path(config_path).read_text()) or {} + return cfg if isinstance(cfg, dict) else {} + except Exception: + return {} + + +def load_thresholds(config_path: Path | str = CONFIG_PATH) -> dict[str, float]: + """Return the ``thresholds.ci_timing`` block, defaulted key by key.""" + out = dict(DEFAULT_CI_TIMING_THRESHOLDS) + block = ((_load_config(config_path).get("thresholds") or {}).get("ci_timing") or {}) + if isinstance(block, dict): + for key in out: + if isinstance(block.get(key), (int, float)): + out[key] = block[key] + return out + + +def tracked_workflows( + repo: str, group: str, config_path: Path | str = CONFIG_PATH +) -> list[str]: + """Workflow display names to time for ``repo``. + + The repo group's ``required_workflows`` (the gates that already decide + whether a release is safe — the same names, so the board's speed row and + its health row can never be about different workflows) PLUS any + ``performance.extra_workflows`` entry naming this repo. Names live in + declared config, never in organ code (the tenant firewall). + """ + cfg = _load_config(config_path) + names: list[str] = [] + required = (cfg.get("required_workflows") or {}).get(group) + if isinstance(required, list): + names.extend(str(w) for w in required) + extra = (cfg.get("performance") or {}).get("extra_workflows") + if isinstance(extra, list): + for item in extra: + if not isinstance(item, dict): + continue + if str(item.get("repo") or "") == repo and item.get("workflow"): + names.append(str(item["workflow"])) + # Stable order, no duplicates. + seen: set[str] = set() + return [n for n in names if not (n in seen or seen.add(n))] + + +# --- pure timing helpers ----------------------------------------------------- +def _parse_iso(value: Any) -> datetime.datetime | None: + if not value: + return None + try: + dt = datetime.datetime.fromisoformat(str(value).replace("Z", "+00:00")) + except (TypeError, ValueError): + return None + return dt if dt.tzinfo else dt.replace(tzinfo=datetime.timezone.utc) + + +def normalize_runs(payload: Any) -> list[dict[str, Any]]: + """Coerce a runs payload into the internal shape (REST or a bare list). + + Accepts the REST ``{"workflow_runs": [...]}`` object ``ci_timing.sh`` sends + and a bare list of runs. Unlike ``ci_status`` there is **no branch filter**: + PR-gate runs are exactly what this check is here to time. + """ + if isinstance(payload, dict): + raw = payload.get("workflow_runs") or [] + elif isinstance(payload, list): + raw = payload + else: + raw = [] + + runs: list[dict[str, Any]] = [] + for run in raw: + if not isinstance(run, dict) or "workflow_runs" in run: + continue + runs.append( + { + "workflow": str(run.get("name") or run.get("workflowName") or ""), + "conclusion": str(run.get("conclusion") or ""), + "status": str(run.get("status") or ""), + "event": str(run.get("event") or ""), + "head_branch": str(run.get("head_branch") or run.get("headBranch") or ""), + "created_at": str(run.get("created_at") or run.get("createdAt") or ""), + "run_started_at": str( + run.get("run_started_at") or run.get("runStartedAt") or "" + ), + "updated_at": str(run.get("updated_at") or run.get("updatedAt") or ""), + "url": str(run.get("html_url") or run.get("url") or ""), + } + ) + return runs + + +def duration_s(run: dict[str, Any]) -> float | None: + """Wall-clock seconds: ``updated_at`` − ``run_started_at``. + + NEVER ``created_at``: a re-attempted run keeps its original creation stamp, + so that arithmetic reports multi-day durations for a nine-minute run (the + trap the Hands release board already hit). No ``run_started_at`` → no + duration; the run is skipped rather than guessed at. + """ + started = _parse_iso(run.get("run_started_at")) + ended = _parse_iso(run.get("updated_at")) + if started is None or ended is None: + return None + return round(max(0.0, (ended - started).total_seconds()), 1) + + +def queue_s(run: dict[str, Any]) -> float | None: + """Queue delay: ``run_started_at`` − ``created_at``, floored at 0.""" + created = _parse_iso(run.get("created_at")) + started = _parse_iso(run.get("run_started_at")) + if created is None or started is None: + return None + return round(max(0.0, (started - created).total_seconds()), 1) + + +def classify_cancelled(run: dict[str, Any], siblings: list[dict[str, Any]]) -> str: + """``"superseded"`` (benign) or ``"suspect"`` (a kill/hang candidate). + + The concurrency block cancels superseded PR runs by design, so a cancelled + ``pull_request`` run with a NEWER run of the same workflow on the same + ``head_branch`` is benign and is only counted. A cancelled run on ``main`` + — or one with no successor — is nobody's design: it is a kill-timer or hang + suspect and becomes an event with its run URL. + """ + if str(run.get("head_branch") or "") == "main": + return "suspect" + if str(run.get("event") or "") != "pull_request": + return "suspect" + branch = run.get("head_branch") + workflow = run.get("workflow") + mine = run.get("created_at") or run.get("run_started_at") or "" + for other in siblings: + if other is run: + continue + if other.get("workflow") != workflow or other.get("head_branch") != branch: + continue + theirs = other.get("created_at") or other.get("run_started_at") or "" + if theirs > mine: + return "superseded" + return "suspect" + + +def event_prompt(repo: str, event: dict[str, Any]) -> str: + """The self-contained /bug prompt a hang/kill row copies.""" + return ( + f"/bug kill timer: {repo} {event.get('workflow')} {event.get('kind')} after " + f"{int(round(float(event.get('duration_s') or 0)))}s on " + f"{event.get('head_branch') or '?'} — {event.get('run_url') or '?'}" + ) + + +def gate_prompt(repo: str, workflow: str, old_s: float, new_s: float, + actions_url: str) -> str: + """The self-contained /bug prompt a slowed gate copies.""" + return ( + f"/bug smoke gate {repo}: {workflow} median wall-clock rose " + f"{int(round(old_s))}s → {int(round(new_s))}s vs its recent history — " + f"{actions_url}" + ) + + +def _median(values: list[float]) -> float | None: + return round(statistics.median(values), 1) if values else None + + +def time_workflow( + repo: str, workflow: str, runs: list[dict[str, Any]], actions_url: str +) -> tuple[dict[str, Any], list[dict[str, Any]]]: + """Time one workflow's runs → (entry, events). + + Only *completed* runs with a usable ``run_started_at`` participate: an + in-flight run has no duration, and a run with no start stamp cannot be + timed honestly. + """ + mine = [ + r for r in runs + if r.get("workflow") == workflow and r.get("conclusion") and r.get("run_started_at") + ] + durations: list[float] = [] + pr_durations: list[float] = [] + queues: list[float] = [] + conclusions = {k: 0 for k in TRACKED_CONCLUSIONS} + superseded = 0 + events: list[dict[str, Any]] = [] + window_from = "" + + for run in mine: + concl = str(run.get("conclusion") or "") + if concl in conclusions: + conclusions[concl] += 1 + dur = duration_s(run) + if dur is None: + continue + started = str(run.get("run_started_at") or "") + if started and (not window_from or started < window_from): + window_from = started + + if concl == "success": + durations.append(dur) + q = queue_s(run) + if q is not None: + queues.append(q) + if str(run.get("event") or "") == "pull_request": + pr_durations.append(dur) + + kind = "" + if concl == "timed_out": + kind = "timed_out" + elif concl == "cancelled": + if classify_cancelled(run, mine) == "superseded": + superseded += 1 + else: + kind = "suspect_cancelled" + if kind: + event = { + "kind": kind, + "workflow": workflow, + "run_url": str(run.get("url") or ""), + "duration_s": dur, + "head_branch": str(run.get("head_branch") or ""), + "at": started, + } + event["prompt"] = event_prompt(repo, event) + events.append(event) + + entry = { + "median_s": _median(durations), + "pr_median_s": _median(pr_durations), + "queue_median_s": _median(queues), + "max_s": round(max(durations), 1) if durations else None, + "runs_counted": len(durations), + "window_from": window_from, + "conclusions": conclusions, + "superseded": superseded, + "actions_url": actions_url, + } + return entry, events + + +def build_sidecar( + name: str, + group: str, + owner: str, + runs: Any, + ts: str, + config_path: Path | str = CONFIG_PATH, + error: str = "", +) -> dict[str, Any]: + """Construct one repo's ci_timing sidecar. + + ``error`` is the reason the runs fetch failed. When set the sidecar carries + NO workflows and NO events: a dead query must never render as a quiet repo. + """ + actions_url = f"https://github.com/{owner}/{name}/actions" if owner else "" + if error: + return { + "name": name, "group": group, "owner": owner, "error": error, + "ts": ts, "workflows": {}, "events": [], + } + + normalized = normalize_runs(runs) + workflows: dict[str, Any] = {} + events: list[dict[str, Any]] = [] + for workflow in tracked_workflows(name, group, config_path): + entry, evts = time_workflow(name, workflow, normalized, actions_url) + # A workflow with no completed runs in the window is not evidence of + # anything; recording it as a zero-run gate keeps the board honest + # about coverage rather than dropping it silently. + workflows[workflow] = entry + events.extend(evts) + + return { + "name": name, "group": group, "owner": owner, "error": "", + "ts": ts, "workflows": workflows, "events": events, + } + + +# --- aggregate --------------------------------------------------------------- +def gate_key(repo: str, workflow: str) -> str: + return f"{repo}/{workflow}" + + +def history_baseline(history: list[dict[str, Any]], key: str, today: str) -> float | None: + """Median of a gate's historical p50s, over PREVIOUS days only. + + Today's own entry is excluded so a re-render cannot compare a gate against + itself and conclude everything is fine. + """ + values: list[float] = [] + for entry in history or []: + if not isinstance(entry, dict) or str(entry.get("date") or "") == today: + continue + gates = entry.get("gates") + if not isinstance(gates, dict): + continue + row = gates.get(key) + if isinstance(row, dict) and isinstance(row.get("p50_s"), (int, float)): + values.append(float(row["p50_s"])) + return round(statistics.median(values), 1) if values else None + + +def classify_drift( + median_s: float | None, baseline_s: float | None, thresholds: dict[str, float] +) -> tuple[str, float | None, float | None]: + """(state, ratio, delta_s) — ``warn`` needs BOTH gates, else ``ok``. + + Ratio alone screams at jitter on a fast gate ("host load alone has produced + 7× errors in this corpus"); the absolute floor alone misses a large relative + drift on a cheap one. Requiring both is the profiling conductor's doctrine, + carried over verbatim. + """ + if not median_s or not baseline_s: + return "ok", None, None + ratio = round(median_s / baseline_s, 2) + delta = round(median_s - baseline_s, 1) + if (ratio >= float(thresholds.get("yellow_factor", 1.5)) + and delta >= float(thresholds.get("min_delta_s", 120))): + return "warn", ratio, delta + return "ok", ratio, delta + + +def roll_history( + prev_history: Any, gates: list[dict[str, Any]], today: str, cap: int +) -> list[dict[str, Any]]: + """Self-carrying roll-forward: drop today, append today, cap. + + One entry per date, so re-rendering the same day is idempotent rather than + stacking duplicate points into the sparkline. + """ + kept = [ + e for e in (prev_history if isinstance(prev_history, list) else []) + if isinstance(e, dict) and str(e.get("date") or "") != today and e.get("date") + ] + today_gates = { + gate_key(g["repo"], g["workflow"]): { + "p50_s": g["median_s"], "runs": g["runs_counted"], + } + for g in gates + if g.get("median_s") is not None + } + kept.append({"date": today, "gates": today_gates}) + return kept[-int(cap):] if cap and cap > 0 else kept + + +def prev_history_of(prev_board: Any) -> list[dict[str, Any]]: + """``performance.history`` out of a previously published board.json. + + Anything unexpected — missing file, a 404 page, half a JSON document, an + older board with no performance block — degrades to no history. A publish + gap costs a sparkline, never a render. + """ + if not isinstance(prev_board, dict): + return [] + perf = prev_board.get("performance") + if not isinstance(perf, dict): + return [] + hist = perf.get("history") + return [e for e in hist if isinstance(e, dict)] if isinstance(hist, list) else [] + + +def aggregate( + sidecars: list[dict[str, Any]], + prev_board: Any, + today: str, + ts: str, + thresholds: dict[str, float] | None = None, +) -> dict[str, Any]: + """Fold the per-repo sidecars + the previous board into the global rollup.""" + thr = dict(thresholds or DEFAULT_CI_TIMING_THRESHOLDS) + history_in = prev_history_of(prev_board) + + gates: list[dict[str, Any]] = [] + events: list[dict[str, Any]] = [] + errors: list[dict[str, str]] = [] + + for side in sorted(sidecars, key=lambda s: str(s.get("name") or "")): + if not isinstance(side, dict): + continue + repo = str(side.get("name") or "") + if side.get("error"): + errors.append({"repo": repo, "error": str(side["error"])}) + continue + workflows = side.get("workflows") + if not isinstance(workflows, dict): + continue + for workflow in sorted(workflows): + entry = workflows[workflow] + if not isinstance(entry, dict): + continue + key = gate_key(repo, workflow) + baseline = history_baseline(history_in, key, today) + median = entry.get("median_s") + state, ratio, delta = classify_drift(median, baseline, thr) + actions_url = str(entry.get("actions_url") or "") + gates.append({ + "repo": repo, + "workflow": workflow, + "median_s": median, + "pr_median_s": entry.get("pr_median_s"), + "queue_median_s": entry.get("queue_median_s"), + "max_s": entry.get("max_s"), + "runs_counted": entry.get("runs_counted", 0), + "window_from": entry.get("window_from", ""), + "conclusions": entry.get("conclusions") or {}, + "superseded": entry.get("superseded", 0), + "actions_url": actions_url, + "baseline_s": baseline, + "ratio": ratio, + "delta_s": delta, + "state": state, + "prompt": (gate_prompt(repo, workflow, baseline, median, actions_url) + if state == "warn" else None), + }) + for event in side.get("events") or []: + if isinstance(event, dict): + events.append(dict(event, repo=repo)) + + history = roll_history(history_in, gates, today, int(thr.get("history_cap", 30))) + return { + "ts": ts, + "gates": gates, + "history": history, + "events": events, + "errors": errors, + "thresholds": thr, + } + + +def read_sidecars(per_repo_dir: Path) -> list[dict[str, Any]]: + """Every ``*.ci_timing.json`` sidecar under ``per_repo_dir`` (I/O).""" + out: list[dict[str, Any]] = [] + for path in sorted(Path(per_repo_dir).glob("*.ci_timing.json")): + try: + data = json.loads(path.read_text()) + except (OSError, ValueError): + continue + if isinstance(data, dict): + out.append(data) + return out + + +def read_prev_board(path: str | Path | None) -> Any: + """The previously published board.json, or ``{}`` on any problem.""" + if not path: + return {} + try: + return json.loads(Path(path).read_text()) + except (OSError, ValueError): + return {} + + +# --- summary lines ----------------------------------------------------------- +def repo_summary_line(sidecar: dict[str, Any]) -> str: + """Coloured one-line per-repo summary for the daemon log.""" + from heart.heart_color import ( + c_info, c_meta, c_ok, c_warn, glyph_ok, glyph_warn, + ) + + name = sidecar.get("name", "?") + if sidecar.get("error"): + return (f"{glyph_warn()} {c_info(name)} {c_warn('ci_timing UNAVAILABLE')} " + f"{c_meta(str(sidecar['error']))}") + workflows = sidecar.get("workflows") or {} + timed = sum(1 for e in workflows.values() + if isinstance(e, dict) and e.get("runs_counted")) + events = sidecar.get("events") or [] + if events: + return (f"{glyph_warn()} {c_info(name)} " + f"{c_warn(f'{len(events)} hang/kill event(s)')} " + f"{c_meta(f'{timed} gate(s) timed')}") + return (f"{glyph_ok()} {c_info(name)} {c_ok(f'{timed} gate(s) timed')} " + f"{c_meta(f'{len(workflows)} tracked')}") + + +def summary_line(rollup: dict[str, Any]) -> str: + """Coloured one-line summary of the global rollup.""" + from heart.heart_color import ( + c_info, c_meta, c_ok, c_warn, glyph_ok, glyph_warn, + ) + + gates = rollup.get("gates") or [] + timed = sum(1 for g in gates if g.get("runs_counted")) + slowed = sum(1 for g in gates if g.get("state") == "warn") + events = len(rollup.get("events") or []) + errors = len(rollup.get("errors") or []) + body = f"{timed} gates timed, {slowed} slowed, {events} hang events" + if errors: + body += f", {errors} unavailable" + glyph = glyph_warn() if (slowed or events or errors) else glyph_ok() + tint = c_warn if (slowed or events or errors) else c_ok + return (f"{glyph} {c_info('ci_timing:')} {tint(body)} " + f"{c_meta(f'({len(gates)} tracked)')}") + + +# --- I/O shell --------------------------------------------------------------- +def _write(out_path: Path, payload: dict[str, Any]) -> None: + sys.path.insert(0, str(HEART_HOME)) + from heart import state + + state.atomic_write_json(out_path, payload) + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(prog="heart.checks.ci_timing") + ap.add_argument("--aggregate", action="store_true", + help="fold the per-repo sidecars into the global rollup") + ap.add_argument("--name", default="") + ap.add_argument("--group", default="") + ap.add_argument("--owner", default="") + ap.add_argument("--ts", default="") + ap.add_argument("--out", required=True) + ap.add_argument("--prev-board", default="", + help="previously published board.json (aggregate mode); " + "missing/unreadable => no history, never an error") + ap.add_argument("--today", default="", + help="ISO date for the history entry (default: today, UTC)") + ap.add_argument("--per-repo-dir", default="", + help="where the sidecars live (default: $HEART_STATE_DIR/per-repo)") + ap.add_argument("--fetch-error", default="", + help="reason the runs fetch failed; recorded instead of a bogus quiet repo") + ns = ap.parse_args(argv) + + ts = ns.ts or datetime.datetime.now(datetime.timezone.utc).isoformat() + + if ns.aggregate: + sys.path.insert(0, str(HEART_HOME)) + from heart import state as _state + + per_repo = Path(ns.per_repo_dir) if ns.per_repo_dir else _state.HEART_PER_REPO_DIR + today = ns.today or datetime.datetime.now(datetime.timezone.utc).date().isoformat() + rollup = aggregate( + read_sidecars(per_repo), read_prev_board(ns.prev_board), today, ts, + load_thresholds(), + ) + _write(Path(ns.out), rollup) + print(summary_line(rollup)) + return 0 + + if not ns.name or not ns.group: + ap.error("--name and --group are required outside --aggregate mode") + + error = ns.fetch_error + try: + runs: Any = json.load(sys.stdin) + except (json.JSONDecodeError, ValueError): + # Unparseable stdin is itself a fetch failure — say so rather than + # writing an empty, quiet-looking sidecar. + runs = [] + error = error or "runs payload was not valid JSON" + + sidecar = build_sidecar(ns.name, ns.group, ns.owner, runs, ts, error=error) + _write(Path(ns.out), sidecar) + print(repo_summary_line(sidecar)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/heart/checks/ci_timing.sh b/heart/checks/ci_timing.sh new file mode 100644 index 00000000..34ca6e71 --- /dev/null +++ b/heart/checks/ci_timing.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# heart/checks/ci_timing.sh — CI wall-clock per tracked workflow (the speed leg). +# +# For each polled repo this fetches the recent workflow runs via `gh api` (cheap +# metadata only) and pipes them to `heart.checks.ci_timing`, which times each +# tracked gate — the group's `required_workflows` plus any +# `performance.extra_workflows` entry naming the repo — and writes +# $HEART_PER_REPO_DIR/.ci_timing.json. A second, aggregate pass folds every +# sidecar plus the PREVIOUSLY PUBLISHED board.json into the global rollup at +# $HEART_STATE_DIR/ci_timing.json (per-gate p50/max, drift vs the gate's own +# history, the rolled-forward history, hang/kill events). +# +# Unlike ci_status.sh the query carries NO `branch=main` filter and NO +# `exclude_pull_requests`: the contributor-facing number is exactly what someone +# waits on before a merge, so `pull_request` runs are the point of the query. +# `per_page=50` gives a week or two of runs on the busy gates without paging. +# +# The history is *self-carrying*: instead of committing baselines, the aggregate +# step re-reads the board.json this repo published yesterday, drops any entry for +# today, appends today's p50 per gate, and caps the list. Free, idempotent per +# date, no state to corrupt — and a publish gap costs a sparkline, never a +# render. HEART_PREV_BOARD_URL overrides the URL (tests, staging boards); any +# fetch failure degrades to "no history", never to an error. +# +# Observer boundary: everything written lives under $HEART_STATE_DIR. A repo +# whose runs fetch fails records the reason and NO workflows — "we could not +# ask" must never render as "all quiet". + +set -u +source "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../_common.sh" + +# Recent runs, newest first, every branch and every event. +_CI_TIMING_RUNS_PATH="actions/runs?per_page=50" + +time_one_repo_ci() { + local owner_name="$1" + local group="$2" + local name="${owner_name##*/}" + local owner="${owner_name%%/*}" + + local runs ts err rc + err="$(mktemp)" + runs="$(gh api "repos/$owner_name/$_CI_TIMING_RUNS_PATH" 2>"$err")" + rc=$? + ts="$(date -Iseconds)" + + local fetch_error="" + if [[ $rc -ne 0 || -z "$runs" ]]; then + # Collapse gh's stderr to one line so it fits the sidecar and the log. + fetch_error="$(tr '\n' ' ' <"$err" | cut -c1-200)" + [[ -z "${fetch_error// }" ]] && fetch_error="gh api exited $rc" + runs='{}' + fi + rm -f "$err" + + printf '%s' "$runs" | PYTHONPATH="$HEART_HOME" python3 -m heart.checks.ci_timing \ + --name "$name" --group "$group" --owner "$owner" --ts "$ts" \ + --fetch-error "$fetch_error" \ + --out "$HEART_PER_REPO_DIR/$name.ci_timing.json" +} + +# Print the path of a tempfile holding the previously published board.json, or +# nothing at all when it cannot be had. Never fails the check. +_ci_timing_prev_board() { + local url tmp + url="${HEART_PREV_BOARD_URL:-}" + if [[ -z "$url" ]]; then + url="$(PYTHONPATH="$HEART_HOME" python3 -c \ + "from heart.dashboard import PAGES_URL; print(PAGES_URL.rstrip('/') + '/board.json')" \ + 2>/dev/null || true)" + fi + [[ -z "$url" ]] && return 0 + tmp="$(mktemp)" + if curl -fsS --max-time 15 "$url" -o "$tmp" 2>/dev/null; then + printf '%s' "$tmp" + else + rm -f "$tmp" + fi +} + +check_ci_timing_all() { + heart_state_dir + heart_log INFO "$(c_info "ci_timing: timing $(load_repos_yaml | wc -l) repos' gates via gh (wall-clock, PR runs included)")" + while read -r line; do + [[ -z "$line" ]] && continue + local owner_name group + owner_name="${line%% *}" + group="${line##* }" + time_one_repo_ci "$owner_name" "$group" & + done < <(load_repos_yaml) + wait + + local prev + prev="$(_ci_timing_prev_board)" + PYTHONPATH="$HEART_HOME" python3 -m heart.checks.ci_timing \ + --aggregate --prev-board "$prev" --ts "$(date -Iseconds)" \ + --out "$HEART_STATE_DIR/ci_timing.json" + [[ -n "$prev" ]] && rm -f "$prev" + + heart_log OK "$(c_ok "ci_timing: done")" +} + +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then + check_ci_timing_all +fi diff --git a/heart/checks/no_run_census.py b/heart/checks/no_run_census.py new file mode 100644 index 00000000..e3e26b05 --- /dev/null +++ b/heart/checks/no_run_census.py @@ -0,0 +1,307 @@ +"""heart/checks/no_run_census.py — the census of skipped workspace scripts. + +Every workspace carries a ``config/build/no_run.yaml``: the list of scripts the +release run skips. Three marker tiers are established convention, written as a +trailing comment on the entry:: + + - path/to/script.py # SLOW 2026-07-14 - takes 233.7s, over the 300s cap + - path/to/other.py # NEEDS_FIX 2026-07-14 - raises on the new API + - path/to/generator.py # (untagged: correct by design) + +The board treats these as *claims with timestamps, not facts*, because the +record says so repeatedly: "a SLOW marker is not evidence of slowness" (the +first SLOW-marked entry ever measured was wrong by ~50×), "a NEEDS_FIX marker is +a claim with a timestamp" (a census where the marker had already evaporated), +and a purge that found 41% of entries dead. So the census does three things a +plain YAML load cannot: + +1. **Counts the tiers**, so the collapsed "permanent" bulk stays out of the way + while the to-do rows surface. +2. **Flags unmeasured SLOW rows** — a SLOW claim whose reason carries no actual + seconds figure has never been measured against the real cap, and is the + single most likely row to be wrong. +3. **Carries a ready-to-paste prompt on every actionable row**, so acting on one + is a paste rather than an archaeology session. + +**Parsed line-based, never by ``yaml.safe_load`` alone.** Two recorded traps +force this: the markers live in ``#`` comments, which a YAML load discards +outright; and a bare ``- off`` / ``- on`` / ``- yes`` entry parses as a YAML +*boolean*, which crashed ``should_skip`` in production. Reading the raw text +line by line sees the comments, and treats ``off`` as the five-letter path it +actually is. + +**The measured heuristic, precisely.** A SLOW reason counts as measured iff it +carries a seconds figure that is NOT a mention of the cap: ``"takes 233.7s"`` is +a measurement, ``"flakes at the 1800s cap"`` is not — it names the limit the +script hit, which is exactly the "no measurement" case this check exists to +find. Hence the negative lookahead on ``cap`` in :data:`SECONDS_RE`. + +Per-repo sidecar (``.no_run_census.json``):: + + {"name", "group", "present", "slow", "needs_fix", "permanent", + "unmeasured_slow", "rows": [{entry, marker, date, reason, measured, prompt}], + "ts"} + +``present: false`` is honest data, not an error: at least one workspace_test repo +genuinely has no ``no_run.yaml`` at all. + +Global rollup (``no_run_census.json``): ``{"ts", "totals", "repos", "rows"}``, +where ``rows`` is the actionable set only (unmeasured SLOW first, then +NEEDS_FIX, then measured SLOW), worst first, each with its repo and prompt. +""" + +from __future__ import annotations + +import argparse +import datetime +import json +import re +import sys +from pathlib import Path +from typing import Any + +HEART_HOME = Path(__file__).resolve().parents[2] + +# `- ` with an optional trailing `# comment`. Entries are single tokens +# (paths / globs), which is what every real no_run.yaml carries. +ENTRY_RE = re.compile(r"^\s*-\s*(?P\S+)\s*(?:#\s*(?P.*))?$") + +# The marker grammar inside the comment: a tier, an optional ISO date, an +# optional dash (ASCII or en dash), then free-text reason. +MARKER_RE = re.compile( + r"^(?PSLOW|NEEDS_FIX)\s*(?P\d{4}-\d{2}-\d{2})?\s*[-–]?\s*(?P.*)$" +) + +# A real seconds figure — but NOT one that merely names the cap. "233.7s" is a +# measurement; "the 1800s cap" is the limit the script hit, which is precisely +# the unmeasured case. +SECONDS_RE = re.compile(r"\d+(?:\.\d+)?\s*s\b(?!\s*cap)", re.IGNORECASE) + +PERMANENT = "permanent" +SLOW = "SLOW" +NEEDS_FIX = "NEEDS_FIX" + +# How much of a marker reason a prompt carries. Long enough to be the whole +# reason in practice, short enough that a pathological comment cannot bloat the +# board's JSON. +REASON_LIMIT = 120 + +# Worst-first ordering for the actionable rows: an unmeasured SLOW claim is the +# most likely to be simply wrong, a NEEDS_FIX is a to-do with a timestamp, and a +# measured SLOW is at least honest about its own cost. +ROW_RANK = {("SLOW", False): 0, ("NEEDS_FIX", False): 1, ("NEEDS_FIX", True): 1, + ("SLOW", True): 2} + + +def is_measured(reason: str) -> bool: + """True iff ``reason`` carries a real seconds figure (not a cap mention).""" + return bool(SECONDS_RE.search(reason or "")) + + +def _truncate(text: str, limit: int = REASON_LIMIT) -> str: + text = (text or "").strip() + return text if len(text) <= limit else text[:limit].rstrip() + + +def row_prompt(repo: str, entry: str, marker: str, date: str, reason: str, + measured: bool) -> str | None: + """The ready-to-paste /bug prompt for one row (None for permanent skips).""" + when = date or "unknown date" + if marker == SLOW and not measured: + return (f"/bug no_run: {repo} {entry} SLOW since {when} with no measurement — " + f"retime against the real cap, then fix it or delete the marker") + if marker == SLOW: + return f"/bug no_run: {repo} {entry} SLOW since {when} — {_truncate(reason)}" + if marker == NEEDS_FIX: + return (f"/bug no_run: {repo} {entry} NEEDS_FIX since {when} — " + f"{_truncate(reason)}. Reproduce before fixing: stale markers have " + f"evaporated before") + return None + + +def parse_no_run(text: str, repo: str) -> list[dict[str, Any]]: + """Parse a raw ``no_run.yaml`` into rows. Line-based, comments preserved. + + Never ``yaml.safe_load``: the markers live in the comments a YAML load + throws away, and a bare ``- off`` entry would come back as the boolean + ``False`` rather than the path it is. + """ + rows: list[dict[str, Any]] = [] + for line in (text or "").splitlines(): + if not line.strip() or line.lstrip().startswith("#"): + continue + m = ENTRY_RE.match(line) + if not m: + continue + entry = m.group("entry").strip().strip("'\"") + if not entry: + continue + comment = (m.group("comment") or "").strip() + marker, date, reason = PERMANENT, "", "" + mm = MARKER_RE.match(comment) if comment else None + if mm: + marker = mm.group("marker") + date = mm.group("date") or "" + reason = (mm.group("reason") or "").strip() + measured = marker == SLOW and is_measured(reason) + rows.append({ + "entry": entry, + "marker": marker, + "date": date, + "reason": reason, + "measured": measured, + "prompt": row_prompt(repo, entry, marker, date, reason, measured), + }) + return rows + + +def build_sidecar( + name: str, group: str, text: str, ts: str, present: bool = True +) -> dict[str, Any]: + """One repo's census sidecar. ``present=False`` => no ``no_run.yaml`` at all.""" + rows = parse_no_run(text, name) if present else [] + slow = [r for r in rows if r["marker"] == SLOW] + return { + "name": name, + "group": group, + "present": bool(present), + "slow": len(slow), + "needs_fix": sum(1 for r in rows if r["marker"] == NEEDS_FIX), + "permanent": sum(1 for r in rows if r["marker"] == PERMANENT), + "unmeasured_slow": sum(1 for r in slow if not r["measured"]), + "rows": rows, + "ts": ts, + } + + +def _row_sort_key(row: dict[str, Any]) -> tuple: + rank = ROW_RANK.get((row.get("marker"), bool(row.get("measured"))), 3) + return (rank, str(row.get("repo") or ""), str(row.get("entry") or "")) + + +def aggregate(sidecars: list[dict[str, Any]], ts: str) -> dict[str, Any]: + """Fold the per-repo sidecars into the global census rollup.""" + repos: list[dict[str, Any]] = [] + rows: list[dict[str, Any]] = [] + totals = {"slow": 0, "needs_fix": 0, "permanent": 0, "unmeasured_slow": 0, + "repos": 0, "repos_present": 0} + + for side in sorted(sidecars, key=lambda s: str(s.get("name") or "")): + if not isinstance(side, dict): + continue + repo = str(side.get("name") or "") + totals["repos"] += 1 + present = bool(side.get("present")) + if present: + totals["repos_present"] += 1 + for key in ("slow", "needs_fix", "permanent", "unmeasured_slow"): + totals[key] += int(side.get(key) or 0) + repos.append({ + "repo": repo, + "present": present, + "slow": int(side.get("slow") or 0), + "needs_fix": int(side.get("needs_fix") or 0), + "permanent": int(side.get("permanent") or 0), + "unmeasured_slow": int(side.get("unmeasured_slow") or 0), + }) + # Only the actionable tiers travel into the rollup; the permanent bulk + # is a count, collapsed, exactly as the board renders it. + for row in side.get("rows") or []: + if isinstance(row, dict) and row.get("marker") in (SLOW, NEEDS_FIX): + rows.append(dict(row, repo=repo)) + + rows.sort(key=_row_sort_key) + return {"ts": ts, "totals": totals, "repos": repos, "rows": rows} + + +def read_sidecars(per_repo_dir: Path) -> list[dict[str, Any]]: + """Every ``*.no_run_census.json`` sidecar under ``per_repo_dir`` (I/O).""" + out: list[dict[str, Any]] = [] + for path in sorted(Path(per_repo_dir).glob("*.no_run_census.json")): + try: + data = json.loads(path.read_text()) + except (OSError, ValueError): + continue + if isinstance(data, dict): + out.append(data) + return out + + +# --- summary lines ----------------------------------------------------------- +def repo_summary_line(sidecar: dict[str, Any]) -> str: + """Coloured one-line per-repo summary for the daemon log.""" + from heart.heart_color import c_info, c_meta, c_ok, c_warn, glyph_info, glyph_ok, glyph_warn + + name = sidecar.get("name", "?") + if not sidecar.get("present"): + return f"{glyph_info()} {c_info(name)} {c_meta('no no_run.yaml')}" + unmeasured = int(sidecar.get("unmeasured_slow") or 0) + needs_fix = int(sidecar.get("needs_fix") or 0) + body = (f"{sidecar.get('slow', 0)} SLOW ({unmeasured} unmeasured) / " + f"{needs_fix} NEEDS_FIX / {sidecar.get('permanent', 0)} permanent") + if unmeasured or needs_fix: + return f"{glyph_warn()} {c_info(name)} {c_warn(body)}" + return f"{glyph_ok()} {c_info(name)} {c_ok(body)}" + + +def summary_line(rollup: dict[str, Any]) -> str: + """Coloured one-line summary of the global census.""" + from heart.heart_color import c_info, c_meta, c_ok, c_warn, glyph_ok, glyph_warn + + t = rollup.get("totals") or {} + unmeasured = int(t.get("unmeasured_slow") or 0) + needs_fix = int(t.get("needs_fix") or 0) + body = (f"{t.get('slow', 0)} SLOW ({unmeasured} unmeasured) / " + f"{needs_fix} NEEDS_FIX / {t.get('permanent', 0)} permanent") + tail = c_meta(f"across {t.get('repos_present', 0)} workspaces") + if unmeasured or needs_fix: + return f"{glyph_warn()} {c_info('no_run_census:')} {c_warn(body)} {tail}" + return f"{glyph_ok()} {c_info('no_run_census:')} {c_ok(body)} {tail}" + + +# --- I/O shell --------------------------------------------------------------- +def _write(out_path: Path, payload: dict[str, Any]) -> None: + sys.path.insert(0, str(HEART_HOME)) + from heart import state + + state.atomic_write_json(out_path, payload) + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(prog="heart.checks.no_run_census") + ap.add_argument("--aggregate", action="store_true", + help="fold the per-repo sidecars into the global census") + ap.add_argument("--name", default="") + ap.add_argument("--group", default="") + ap.add_argument("--ts", default="") + ap.add_argument("--out", required=True) + ap.add_argument("--missing", action="store_true", + help="this repo has no config/build/no_run.yaml (honest data, not an error)") + ap.add_argument("--per-repo-dir", default="", + help="where the sidecars live (default: $HEART_STATE_DIR/per-repo)") + ns = ap.parse_args(argv) + + ts = ns.ts or datetime.datetime.now(datetime.timezone.utc).isoformat() + + if ns.aggregate: + sys.path.insert(0, str(HEART_HOME)) + from heart import state as _state + + per_repo = Path(ns.per_repo_dir) if ns.per_repo_dir else _state.HEART_PER_REPO_DIR + rollup = aggregate(read_sidecars(per_repo), ts) + _write(Path(ns.out), rollup) + print(summary_line(rollup)) + return 0 + + if not ns.name: + ap.error("--name is required outside --aggregate mode") + + text = "" if ns.missing else sys.stdin.read() + sidecar = build_sidecar(ns.name, ns.group, text, ts, present=not ns.missing) + _write(Path(ns.out), sidecar) + print(repo_summary_line(sidecar)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/heart/checks/no_run_census.sh b/heart/checks/no_run_census.sh new file mode 100644 index 00000000..87d6166e --- /dev/null +++ b/heart/checks/no_run_census.sh @@ -0,0 +1,91 @@ +#!/usr/bin/env bash +# heart/checks/no_run_census.sh — census of every workspace's skipped scripts. +# +# For each polled workspace / workspace_test / HowTo repo this fetches +# `config/build/no_run.yaml` via the contents API (one cheap call per repo) and +# pipes the RAW YAML TEXT to `heart.checks.no_run_census`, which parses it +# line-based — the marker tiers live in `#` comments a YAML load would discard, +# and a bare `- off` entry parses as a YAML boolean (a recorded crash) — and +# writes $HEART_PER_REPO_DIR/.no_run_census.json. A second, aggregate pass +# folds the sidecars into $HEART_STATE_DIR/no_run_census.json. +# +# A repo with no `no_run.yaml` is passed `--missing` and recorded as +# `present: false`. That is honest data, not an error: at least one +# workspace_test repo genuinely has no such file, and inventing an empty census +# for it would read as "nothing skipped here". +# +# Only the groups that HAVE a no_run.yaml are polled (workspaces, +# workspaces_test, howto) — asking a library for one would manufacture a repo +# full of false "missing" rows. +# +# Observer boundary: everything written lives under $HEART_STATE_DIR. + +set -u +source "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../_common.sh" + +_NO_RUN_PATH="contents/config/build/no_run.yaml" +_NO_RUN_GROUPS="workspaces workspaces_test howto" + +census_one_repo() { + local owner_name="$1" + local group="$2" + local name="${owner_name##*/}" + + local raw body ts err rc + err="$(mktemp)" + # `--jq .content` yields base64 wrapped at 60 columns; strip the newlines + # before decoding so every base64 implementation accepts it. The decode is a + # separate step so `rc` is *gh's* exit status, not base64's. + raw="$(gh api "repos/$owner_name/$_NO_RUN_PATH" --jq '.content' 2>"$err")" + rc=$? + body="" + if [[ $rc -eq 0 && -n "$raw" ]]; then + body="$(printf '%s' "$raw" | tr -d '\n' | base64 -d 2>/dev/null || true)" + fi + ts="$(date -Iseconds)" + + if [[ $rc -ne 0 || -z "$body" ]]; then + # A 404 is the expected "this repo has none"; anything else is a query we + # could not make, which is worth a log line even though the census row is + # the same honest `present: false`. + if ! grep -qi '404\|not found' "$err"; then + heart_log WARN "$(c_warn "no_run_census: $name fetch failed: $(tr '\n' ' ' <"$err" | cut -c1-160)")" + fi + rm -f "$err" + PYTHONPATH="$HEART_HOME" python3 -m heart.checks.no_run_census \ + --name "$name" --group "$group" --ts "$ts" --missing \ + --out "$HEART_PER_REPO_DIR/$name.no_run_census.json" str: return glyph_info() +# The sparkline ramp. Eight levels is enough resolution for a 30-point daily +# history and narrow enough to sit inside a table cell on a phone. +SPARK_CHARS = "▁▂▃▄▅▆▇█" + + +def sparkline(values: Sequence[Any]) -> str: + """A unicode sparkline over ``values``; "" under two points. + + Pure and defensive: non-numeric entries are dropped, and a flat series + renders mid-ramp rather than dividing by zero. One point is not a trend — + the empty string keeps the board from drawing a shape that means nothing + (the "every stored history is one value repeated seven times" lesson). + """ + nums = [float(v) for v in (values or []) if isinstance(v, (int, float))] + if len(nums) < 2: + return "" + lo, hi = min(nums), max(nums) + if hi <= lo: + return SPARK_CHARS[len(SPARK_CHARS) // 2] * len(nums) + span = hi - lo + last = len(SPARK_CHARS) - 1 + return "".join( + SPARK_CHARS[min(last, int((n - lo) / span * len(SPARK_CHARS)))] for n in nums + ) + + +def _dur(seconds: Any) -> str: + """Compact wall-clock: minutes above a minute, seconds below it.""" + if not isinstance(seconds, (int, float)) or seconds <= 0: + return "?" + if seconds < 60: + return f"{int(round(seconds))}s" + return f"{int(round(seconds / 60))}m" + + +def _gate_spark(history: Sequence[Any], key: str) -> str: + """The sparkline of one gate's daily p50s, oldest first.""" + values: list[float] = [] + for entry in sorted( + (e for e in (history or []) if isinstance(e, dict)), + key=lambda e: str(e.get("date") or ""), + ): + row = (entry.get("gates") or {}).get(key) if isinstance(entry.get("gates"), dict) else None + if isinstance(row, dict) and isinstance(row.get("p50_s"), (int, float)): + values.append(float(row["p50_s"])) + return sparkline(values) + + def _worst(states: Iterable[str]) -> str: order = {FAIL: 3, WARN: 2, UNOBS: 1, INFO: 1, OK: 0} best = OK @@ -631,6 +686,13 @@ def build_board( details.append(f"{stale_n} stale parked script(s)") sections.append(Section("test_run", "Test run", st, summary, details)) + # CI wall-clock + the NO_RUN census (the ⏱ performance surface) ----------- + # Both are CLOUD-observed (the Actions API + the contents API), so they are + # deliberately NOT in LOCAL_ONLY_FAMILIES: the scheduled job measures them + # first-hand and must not mark them "not observed here". Timing rows are + # advisory — they never move the readiness verdict. + performance = _performance_sections(snapshot, sections) + # Version skew ----------------------------------------------------------- if "version_skew" in unobserved: sections.append(_unobs_section("version_skew", "Version skew")) @@ -745,9 +807,152 @@ def build_board( sections=sections, stale_reasons=stale_reasons, blockers=_structure_reasons(red, yellow, stale_reasons, repos), + performance=performance, ) +def _ci_timing_section(ct: dict, gates: list[dict], events: list[dict], + errors: list, history: list[dict]) -> Section: + """The CI wall-clock row: how long the gates a change must pass now take.""" + timed = [g for g in gates if _as_int(g.get("runs_counted"))] + warned = [g for g in gates if g.get("state") == "warn"] + # Events (a hang, a kill-timer suspect) are the only hard rows here; a + # slowed gate is advisory by construction — an alarm that cries wolf on + # timing jitter gets ignored, and then so does the real one. + if events: + st = FAIL + elif warned or errors: + st = WARN + else: + st = OK + + bits = [f"{len(timed)} gates"] + slowest = max(timed, key=lambda g: g.get("median_s") or 0, default=None) + if slowest: + bits.append(f"slowest {slowest.get('repo')} {slowest.get('workflow')} " + f"{_dur(slowest.get('median_s'))}") + if warned: + bits.append(f"{len(warned)} slowed") + if events: + bits.append(f"{len(events)} hang event" + ("" if len(events) == 1 else "s")) + if errors: + bits.append(f"{len(errors)} unavailable") + + details = [] + for g in sorted(timed, key=lambda g: g.get("median_s") or 0, reverse=True)[:5]: + # Coverage beside time, always: a speed row without the run count + # rewards a gate that got faster by running less. + line = (f"{g.get('repo')} {g.get('workflow')} p50 {_dur(g.get('median_s'))} " + f"max {_dur(g.get('max_s'))} ({_as_int(g.get('runs_counted'))} runs)") + spark = _gate_spark(history, f"{g.get('repo')}/{g.get('workflow')}") + details.append(f"{line} {spark}" if spark else line) + + links = [ + {"label": f"{e.get('repo')} {e.get('kind')}", "url": str(e.get("run_url")), + "prompt": str(e.get("prompt") or "")} + for e in events if e.get("run_url") + ][:4] + + # A slowed gate has no run URL of its own (it is a distribution, not a run), + # so its prompt rides the row's 📋 when exactly one gate slowed. More than + # one and the board would have to pick a favourite — they all stay in the + # `performance` block instead, where each carries its own prompt. + action = None + if len(warned) == 1 and warned[0].get("prompt"): + action = {"label": "copy the slowdown prompt", "payload": str(warned[0]["prompt"])} + + return Section("ci_timing", "CI wall-clock", st, " · ".join(bits), details, + links=links, action=action) + + +def _no_run_section(totals: dict, rows: list[dict], repo_rows: list[dict]) -> Section: + """The NO_RUN census row: what the release run is not running, and why.""" + slow = _as_int(totals.get("slow")) + needs_fix = _as_int(totals.get("needs_fix")) + permanent = _as_int(totals.get("permanent")) + unmeasured = _as_int(totals.get("unmeasured_slow")) + present = _as_int(totals.get("repos_present")) + + if unmeasured or needs_fix: + st = WARN + elif not slow and not needs_fix and permanent: + st = INFO # only correct-by-design skips: a fact, not a to-do + else: + st = OK + summary = (f"{slow} SLOW ({unmeasured} unmeasured) / {needs_fix} NEEDS_FIX / " + f"{permanent} permanent across {present} workspaces") + + details = [ + f"{r.get('repo')}: {r.get('entry')} {r.get('marker')} {r.get('date') or 'undated'}" + for r in rows[:5] + ] + absent = [str(r.get("repo")) for r in repo_rows if not r.get("present")] + if absent: + # Honest data, not an error — some repos genuinely have no no_run.yaml. + details.append(f"no no_run.yaml: {', '.join(absent[:4])}") + + action = None + if rows and rows[0].get("prompt"): + action = {"label": "copy the fix prompt", "payload": str(rows[0]["prompt"])} + return Section("no_run_census", "NO_RUN census", st, summary, details, action=action) + + +def _performance_sections(snapshot: dict, sections: list[Section]) -> dict | None: + """Append the two ⏱ rows (when observed) and return the `performance` block. + + The block is the contract the Brain board consumes verbatim: every + actionable row inside it — a slowed gate, a hang event, a marker row — + carries its own ready-to-paste prompt string, written by the producer and + never re-derived by a renderer. + """ + ct = snapshot.get("ci_timing") + ct = ct if isinstance(ct, dict) else {} + nr = snapshot.get("no_run_census") + nr = nr if isinstance(nr, dict) else {} + if not ct and not nr: + return None + + gates = [g for g in (ct.get("gates") or []) if isinstance(g, dict)] + events = [e for e in (ct.get("events") or []) if isinstance(e, dict)] + history = [h for h in (ct.get("history") or []) if isinstance(h, dict)] + errors = list(ct.get("errors") or []) + totals = nr.get("totals") if isinstance(nr.get("totals"), dict) else {} + rows = [r for r in (nr.get("rows") or []) if isinstance(r, dict)] + repo_rows = [r for r in (nr.get("repos") or []) if isinstance(r, dict)] + + if ct: + sections.append(_ci_timing_section(ct, gates, events, errors, history)) + if nr: + sections.append(_no_run_section(totals, rows, repo_rows)) + + return { + "schema": 1, + "gates": [ + { + "repo": g.get("repo"), + "workflow": g.get("workflow"), + "median_s": g.get("median_s"), + "pr_median_s": g.get("pr_median_s"), + "max_s": g.get("max_s"), + "runs_counted": _as_int(g.get("runs_counted")), + "state": g.get("state") or OK, + "prompt": g.get("prompt"), + "actions_url": g.get("actions_url") or "", + "spark": _gate_spark(history, f"{g.get('repo')}/{g.get('workflow')}"), + } + for g in gates + ], + "history": history, + "events": events, + "errors": errors, + "no_run": { + "totals": totals, + "repos": repo_rows, + "rows": rows[:10], + }, + } + + def _unobs_section(key: str, title: str) -> Section: watches = UNOBS_WATCHES.get(key) return Section( @@ -1120,7 +1325,7 @@ def _render_html(board: Board) -> str: def to_dict(board: Board) -> dict[str, Any]: """The machine surface (fmt='json') the Health Agent + mobile consume.""" - return { + payload: dict[str, Any] = { "schema_version": SCHEMA_VERSION, "verdict": board.verdict, "score": board.score, @@ -1151,6 +1356,13 @@ def to_dict(board: Board) -> dict[str, Any]: for s in board.sections ], } + # The ⏱ performance block, additive (schema v2 stays v2). Emitted only when + # something was actually measured — a consumer must be able to tell "no + # timing observed" from "timing observed, nothing to report", and this is + # also the block the NEXT render reads back as its own history. + if board.performance is not None: + payload["performance"] = board.performance + return payload def badge_endpoint(board: Board) -> dict[str, Any]: diff --git a/heart/state.py b/heart/state.py index 14af1d0b..7ace1e35 100644 --- a/heart/state.py +++ b/heart/state.py @@ -78,6 +78,8 @@ def aggregate() -> dict[str, Any]: "unit_test_timing": _read_json_or_default(HEART_STATE_DIR / "unit_test_timing.json", {}), "profiling_drift": _read_json_or_default(HEART_STATE_DIR / "profiling_drift.json", {}), "test_run": _read_json_or_default(HEART_STATE_DIR / "test_run.json", {}), + "ci_timing": _read_json_or_default(HEART_STATE_DIR / "ci_timing.json", {}), + "no_run_census": _read_json_or_default(HEART_STATE_DIR / "no_run_census.json", {}), "workspace_testmode_timing": _read_json_or_default(HEART_STATE_DIR / "workspace_testmode_timing.json", {}), "version_skew": _read_json_or_default(HEART_STATE_DIR / "version_skew.json", {}), "version_skew_pypi": _read_json_or_default(HEART_STATE_DIR / "version_skew_pypi.json", {}), diff --git a/tests/test_ci_timing.py b/tests/test_ci_timing.py new file mode 100644 index 00000000..353714c8 --- /dev/null +++ b/tests/test_ci_timing.py @@ -0,0 +1,466 @@ +"""tests/test_ci_timing.py — CI wall-clock timing, drift, and hang events. + +Fake repo/workflow names throughout (the tenant firewall): instance facts live +in `config/repos.yaml`, which is the declared surface, never in test data. +""" + +from __future__ import annotations + +import json + +from heart.checks import ci_timing as ct + +REPO = "RepoA" +ACTIONS = "https://github.invalid/OwnerX/RepoA/actions" + + +def _run( + workflow="Gate One", + conclusion="success", + *, + created="2026-08-20T09:00:00Z", + started="2026-08-20T09:00:00Z", + updated="2026-08-20T09:10:00Z", + event="push", + branch="main", + url="https://github.invalid/run/1", + status="completed", +): + """A run in the REST /actions/runs shape.""" + return { + "name": workflow, "display_title": "some commit subject", + "conclusion": conclusion, "status": status, "event": event, + "head_branch": branch, "created_at": created, "run_started_at": started, + "updated_at": updated, "html_url": url, + } + + +def _cfg(tmp_path, extra: str = "") -> str: + cfg = tmp_path / "repos.yaml" + cfg.write_text( + "required_workflows:\n" + " workspaces: ['Gate One', 'Gate Two']\n" + " libraries: ['Gate One']\n" + "thresholds:\n" + " ci_timing:\n" + " yellow_factor: 1.5\n" + " min_delta_s: 120\n" + " history_cap: 30\n" + + extra + ) + return str(cfg) + + +# --- duration comes from run_started_at, never created_at ------------------- + +def test_duration_uses_run_started_at_not_created_at(): + """The re-attempt trap: a re-run keeps its ORIGINAL created_at, so + created_at arithmetic reports multi-day durations for a ten-minute run.""" + reattempt = _run( + created="2026-08-18T09:00:00Z", # two days earlier — the trap + started="2026-08-20T09:00:00Z", + updated="2026-08-20T09:10:00Z", + ) + assert ct.duration_s(ct.normalize_runs([reattempt])[0]) == 600.0 + + +def test_reattempted_run_does_not_distort_the_median(tmp_path): + payload = {"workflow_runs": [ + _run(updated="2026-08-20T09:10:00Z"), # 600s + _run(created="2026-08-18T09:00:00Z", # re-attempt + updated="2026-08-20T09:10:00Z", url="https://github.invalid/run/2"), + ]} + side = ct.build_sidecar(REPO, "libraries", "OwnerX", payload, "T", + config_path=_cfg(tmp_path)) + wf = side["workflows"]["Gate One"] + assert wf["median_s"] == 600.0 + assert wf["max_s"] == 600.0 # never the multi-day created_at figure + + +def test_run_without_run_started_at_is_skipped(): + assert ct.duration_s({"run_started_at": "", "updated_at": "2026-08-20T09:10:00Z"}) is None + + +# --- medians over success runs only ----------------------------------------- + +def test_medians_are_success_only_and_split_by_event(tmp_path): + payload = {"workflow_runs": [ + _run(updated="2026-08-20T09:10:00Z"), # 600s push + _run(updated="2026-08-20T09:05:00Z", event="pull_request", branch="f1"), # 300s PR + _run(updated="2026-08-20T09:15:00Z", event="pull_request", branch="f2"), # 900s PR + # A failure stops early; pooling it would make the gate look faster the + # more it breaks. + _run("Gate One", "failure", updated="2026-08-20T09:00:30Z"), + ]} + side = ct.build_sidecar(REPO, "libraries", "OwnerX", payload, "T", + config_path=_cfg(tmp_path)) + wf = side["workflows"]["Gate One"] + assert wf["median_s"] == 600.0 # 300, 600, 900 + assert wf["pr_median_s"] == 600.0 # 300, 900 + assert wf["runs_counted"] == 3 + assert wf["conclusions"] == {"success": 3, "failure": 1, "cancelled": 0, + "timed_out": 0} + assert wf["actions_url"] == "https://github.com/OwnerX/RepoA/actions" + + +def test_queue_seconds_floor_at_zero(): + # A clock-skewed payload where the run "started" before it was created must + # not produce a negative queue delay. + assert ct.queue_s({"created_at": "2026-08-20T09:00:00Z", + "run_started_at": "2026-08-20T08:59:50Z"}) == 0.0 + assert ct.queue_s({"created_at": "2026-08-20T09:00:00Z", + "run_started_at": "2026-08-20T09:00:30Z"}) == 30.0 + + +def test_queue_median_recorded(tmp_path): + payload = {"workflow_runs": [ + _run(created="2026-08-20T08:59:00Z", started="2026-08-20T09:00:00Z", + updated="2026-08-20T09:10:00Z"), + ]} + side = ct.build_sidecar(REPO, "libraries", "OwnerX", payload, "T", + config_path=_cfg(tmp_path)) + assert side["workflows"]["Gate One"]["queue_median_s"] == 60.0 + + +# --- cancelled disambiguation ------------------------------------------------ + +def test_cancelled_pr_run_with_newer_same_branch_run_is_superseded(tmp_path): + payload = {"workflow_runs": [ + _run("Gate One", "cancelled", event="pull_request", branch="feat/x", + created="2026-08-20T09:00:00Z", updated="2026-08-20T09:01:00Z"), + _run("Gate One", "success", event="pull_request", branch="feat/x", + created="2026-08-20T09:30:00Z", started="2026-08-20T09:30:00Z", + updated="2026-08-20T09:40:00Z"), + ]} + side = ct.build_sidecar(REPO, "libraries", "OwnerX", payload, "T", + config_path=_cfg(tmp_path)) + assert side["events"] == [] # benign + assert side["workflows"]["Gate One"]["superseded"] == 1 + assert side["workflows"]["Gate One"]["conclusions"]["cancelled"] == 1 + + +def test_cancelled_on_main_is_always_suspect(tmp_path): + payload = {"workflow_runs": [ + _run("Gate One", "cancelled", branch="main", + created="2026-08-20T09:00:00Z", updated="2026-08-20T09:50:00Z"), + _run("Gate One", "success", branch="main", + created="2026-08-20T10:00:00Z", started="2026-08-20T10:00:00Z", + updated="2026-08-20T10:10:00Z"), + ]} + side = ct.build_sidecar(REPO, "libraries", "OwnerX", payload, "T", + config_path=_cfg(tmp_path)) + (event,) = side["events"] + assert event["kind"] == "suspect_cancelled" + assert side["workflows"]["Gate One"]["superseded"] == 0 + + +def test_cancelled_pr_run_with_no_successor_is_suspect(tmp_path): + payload = {"workflow_runs": [ + _run("Gate One", "cancelled", event="pull_request", branch="feat/y", + created="2026-08-20T09:00:00Z", updated="2026-08-20T09:55:00Z", + url="https://github.invalid/run/77"), + ]} + side = ct.build_sidecar(REPO, "libraries", "OwnerX", payload, "T", + config_path=_cfg(tmp_path)) + (event,) = side["events"] + assert event["kind"] == "suspect_cancelled" + assert event["run_url"] == "https://github.invalid/run/77" + assert event["prompt"] == ( + "/bug kill timer: RepoA Gate One suspect_cancelled after 3300s on feat/y " + "— https://github.invalid/run/77" + ) + + +def test_timed_out_is_always_an_event_with_its_prompt(tmp_path): + payload = {"workflow_runs": [ + _run("Gate One", "timed_out", branch="main", + started="2026-08-20T09:00:00Z", updated="2026-08-20T14:00:00Z", + url="https://github.invalid/run/9"), + ]} + side = ct.build_sidecar(REPO, "libraries", "OwnerX", payload, "T", + config_path=_cfg(tmp_path)) + (event,) = side["events"] + assert event["kind"] == "timed_out" + assert event["duration_s"] == 18000.0 + assert event["head_branch"] == "main" + assert event["at"] == "2026-08-20T09:00:00Z" + assert event["prompt"] == ( + "/bug kill timer: RepoA Gate One timed_out after 18000s on main " + "— https://github.invalid/run/9" + ) + + +# --- tracked workflow selection --------------------------------------------- + +def test_extra_workflows_are_timed_beyond_the_required_set(tmp_path): + cfg = _cfg(tmp_path, + "performance:\n" + " extra_workflows:\n" + " - repo: RepoA\n" + " workflow: 'Nightly Thing'\n" + " - repo: RepoB\n" + " workflow: 'Other Thing'\n") + assert ct.tracked_workflows("RepoA", "libraries", cfg) == ["Gate One", "Nightly Thing"] + assert ct.tracked_workflows("RepoB", "libraries", cfg) == ["Gate One", "Other Thing"] + assert ct.tracked_workflows("RepoA", "workspaces", cfg) == [ + "Gate One", "Gate Two", "Nightly Thing"] + + +def test_untracked_workflows_are_ignored(tmp_path): + payload = {"workflow_runs": [_run("Some Other Workflow", "success")]} + side = ct.build_sidecar(REPO, "libraries", "OwnerX", payload, "T", + config_path=_cfg(tmp_path)) + assert list(side["workflows"]) == ["Gate One"] + assert side["workflows"]["Gate One"]["runs_counted"] == 0 + assert side["workflows"]["Gate One"]["median_s"] is None + + +# --- fetch errors ------------------------------------------------------------ + +def test_fetch_error_sidecar_records_the_reason_and_no_quiet(tmp_path): + """"We could not ask" must never render as "all quiet".""" + side = ct.build_sidecar(REPO, "libraries", "OwnerX", + {"workflow_runs": [_run()]}, "T", + config_path=_cfg(tmp_path), error="gh api exited 1") + assert side["error"] == "gh api exited 1" + assert side["workflows"] == {} + assert side["events"] == [] + + +def test_aggregate_reports_errored_repos(tmp_path): + roll = ct.aggregate( + [{"name": "RepoA", "error": "boom", "workflows": {}, "events": []}], + {}, "2026-08-24", "T", ct.DEFAULT_CI_TIMING_THRESHOLDS) + assert roll["errors"] == [{"repo": "RepoA", "error": "boom"}] + assert roll["gates"] == [] + + +# --- aggregate: drift needs BOTH gates --------------------------------------- + +def _sidecar(median, workflow="Gate One", repo="RepoA"): + return { + "name": repo, "group": "libraries", "owner": "OwnerX", "error": "", + "workflows": {workflow: { + "median_s": median, "pr_median_s": median, "queue_median_s": 5.0, + "max_s": median, "runs_counted": 6, "window_from": "2026-08-17T00:00:00Z", + "conclusions": {"success": 6, "failure": 0, "cancelled": 0, "timed_out": 0}, + "superseded": 0, "actions_url": ACTIONS, + }}, + "events": [], + } + + +def _prev(history): + return {"performance": {"history": history}} + + +def _hist(date, p50, key="RepoA/Gate One", runs=6): + return {"date": date, "gates": {key: {"p50_s": p50, "runs": runs}}} + + +def test_drift_needs_ratio_and_absolute_delta(): + thr = {"yellow_factor": 1.5, "min_delta_s": 120, "history_cap": 30} + # Both gates cleared: 600 -> 1200 is 2.0x and +600s. + assert ct.classify_drift(1200.0, 600.0, thr)[0] == "warn" + # Ratio alone (a fast gate jittering): 4.0x but only +30s. + assert ct.classify_drift(40.0, 10.0, thr)[0] == "ok" + # Absolute alone (a slow gate creeping): +300s but only 1.15x. + assert ct.classify_drift(2300.0, 2000.0, thr)[0] == "ok" + # No baseline at all → never a warn. + assert ct.classify_drift(1200.0, None, thr)[0] == "ok" + + +def test_aggregate_flags_a_slowed_gate_with_its_prompt(): + prev = _prev([_hist("2026-08-22", 600.0), _hist("2026-08-23", 600.0)]) + roll = ct.aggregate([_sidecar(1200.0)], prev, "2026-08-24", "T", + {"yellow_factor": 1.5, "min_delta_s": 120, "history_cap": 30}) + (gate,) = roll["gates"] + assert gate["state"] == "warn" + assert gate["baseline_s"] == 600.0 + assert gate["prompt"] == ( + "/bug smoke gate RepoA: Gate One median wall-clock rose 600s → 1200s " + f"vs its recent history — {ACTIONS}" + ) + + +def test_aggregate_ok_gate_carries_no_prompt(): + prev = _prev([_hist("2026-08-23", 600.0)]) + roll = ct.aggregate([_sidecar(620.0)], prev, "2026-08-24", "T", + ct.DEFAULT_CI_TIMING_THRESHOLDS) + (gate,) = roll["gates"] + assert gate["state"] == "ok" + assert gate["prompt"] is None + + +def test_gates_are_never_fail_only_advisory(): + prev = _prev([_hist("2026-08-23", 10.0)]) + roll = ct.aggregate([_sidecar(9000.0)], prev, "2026-08-24", "T", + ct.DEFAULT_CI_TIMING_THRESHOLDS) + assert {g["state"] for g in roll["gates"]} <= {"ok", "warn"} + + +# --- aggregate: history roll-forward ----------------------------------------- + +def test_history_rolls_forward_and_replaces_todays_entry(): + prev = _prev([_hist("2026-08-23", 600.0), _hist("2026-08-24", 111.0)]) + roll = ct.aggregate([_sidecar(650.0)], prev, "2026-08-24", "T", + ct.DEFAULT_CI_TIMING_THRESHOLDS) + dates = [e["date"] for e in roll["history"]] + assert dates == ["2026-08-23", "2026-08-24"] # one entry per date + assert roll["history"][-1]["gates"]["RepoA/Gate One"]["p50_s"] == 650.0 + # ...and the prior day is preserved verbatim. + assert roll["history"][0]["gates"]["RepoA/Gate One"]["p50_s"] == 600.0 + + +def test_history_re_render_is_idempotent(): + prev = _prev([_hist("2026-08-23", 600.0)]) + once = ct.aggregate([_sidecar(650.0)], prev, "2026-08-24", "T", + ct.DEFAULT_CI_TIMING_THRESHOLDS) + twice = ct.aggregate([_sidecar(650.0)], {"performance": once}, "2026-08-24", "T", + ct.DEFAULT_CI_TIMING_THRESHOLDS) + assert once["history"] == twice["history"] + + +def test_history_cap_is_honoured(): + prev = _prev([_hist(f"2026-07-{d:02d}", 600.0) for d in range(1, 31)]) + roll = ct.aggregate([_sidecar(600.0)], prev, "2026-08-24", "T", + {"yellow_factor": 1.5, "min_delta_s": 120, "history_cap": 5}) + assert len(roll["history"]) == 5 + assert roll["history"][-1]["date"] == "2026-08-24" + + +def test_missing_or_corrupt_prev_board_means_no_history(): + for prev in (None, {}, "not a board", {"performance": "nope"}, + {"performance": {"history": "nope"}}): + roll = ct.aggregate([_sidecar(600.0)], prev, "2026-08-24", "T", + ct.DEFAULT_CI_TIMING_THRESHOLDS) + assert [e["date"] for e in roll["history"]] == ["2026-08-24"] + assert roll["gates"][0]["state"] == "ok" # no baseline → never a warn + + +def test_history_baseline_ignores_todays_entry(): + history = [_hist("2026-08-23", 600.0), _hist("2026-08-24", 5000.0)] + assert ct.history_baseline(history, "RepoA/Gate One", "2026-08-24") == 600.0 + + +def test_read_prev_board_degrades_on_bad_json(tmp_path): + bad = tmp_path / "board.json" + bad.write_text("404") + assert ct.read_prev_board(bad) == {} + assert ct.read_prev_board(tmp_path / "absent.json") == {} + assert ct.read_prev_board("") == {} + + +# --- aggregate: events + summary --------------------------------------------- + +def test_aggregate_concatenates_events_with_repo_context(): + side = _sidecar(600.0) + side["events"] = [{"kind": "timed_out", "workflow": "Gate One", + "run_url": "u", "duration_s": 900.0, "head_branch": "main", + "at": "t", "prompt": "/bug kill timer: RepoA ..."}] + roll = ct.aggregate([side], {}, "2026-08-24", "T", ct.DEFAULT_CI_TIMING_THRESHOLDS) + assert roll["events"][0]["repo"] == "RepoA" + assert roll["events"][0]["prompt"].startswith("/bug kill timer:") + + +def test_summary_line_counts_gates_slowdowns_and_events(monkeypatch): + monkeypatch.setenv("NO_COLOR", "1") + prev = _prev([_hist("2026-08-23", 600.0)]) + side = _sidecar(1200.0) + side["events"] = [{"kind": "timed_out", "workflow": "Gate One", "run_url": "u", + "duration_s": 1.0, "head_branch": "main", "at": "t", + "prompt": "p"}] + roll = ct.aggregate([side], prev, "2026-08-24", "T", + ct.DEFAULT_CI_TIMING_THRESHOLDS) + line = ct.summary_line(roll) + assert "1 gates timed, 1 slowed, 1 hang events" in line + + +def test_repo_summary_line_flags_unavailable(monkeypatch): + monkeypatch.setenv("NO_COLOR", "1") + line = ct.repo_summary_line({"name": "RepoA", "error": "gh api exited 1", + "workflows": {}, "events": []}) + assert "UNAVAILABLE" in line + + +# --- normalize / robustness --------------------------------------------------- + +def test_normalize_keeps_pull_request_runs_and_every_branch(): + """ci_status filters to main; this check must NOT — the PR gate is the point.""" + payload = {"workflow_runs": [ + _run(event="pull_request", branch="feat/x"), + _run(event="push", branch="main"), + ]} + assert len(ct.normalize_runs(payload)) == 2 + + +def test_normalize_handles_garbage(): + assert ct.normalize_runs(None) == [] + assert ct.normalize_runs({}) == [] + assert ct.normalize_runs({"workflow_runs": [None, "x"]}) == [] + + +def test_thresholds_load_from_config(tmp_path): + thr = ct.load_thresholds(_cfg(tmp_path)) + assert thr == {"yellow_factor": 1.5, "min_delta_s": 120, "history_cap": 30} + assert ct.load_thresholds(tmp_path / "absent.yaml") == ct.DEFAULT_CI_TIMING_THRESHOLDS + + +def test_real_config_declares_the_ci_timing_thresholds(): + """The shipped policy file must carry the block the check reads.""" + thr = ct.load_thresholds() + assert thr["yellow_factor"] >= 1.0 and thr["min_delta_s"] >= 1 + assert thr["history_cap"] >= 2 + + +# --- main wiring -------------------------------------------------------------- + +def test_main_writes_sidecar_then_aggregates(tmp_path, monkeypatch, capsys): + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + per_repo = tmp_path / "per-repo" + per_repo.mkdir() + payload = json.dumps({"workflow_runs": [ + _run("Tests", "success", updated="2026-08-20T09:10:00Z"), + ]}) + monkeypatch.setattr("sys.stdin", __import__("io").StringIO(payload)) + rc = ct.main(["--name", "LibA", "--group", "libraries", "--owner", "OwnerX", + "--ts", "T", "--out", str(per_repo / "LibA.ci_timing.json")]) + assert rc == 0 + side = json.loads((per_repo / "LibA.ci_timing.json").read_text()) + # Uses the real config/repos.yaml: libraries gate on "Tests". + assert side["workflows"]["Tests"]["median_s"] == 600.0 + + out = tmp_path / "ci_timing.json" + rc = ct.main(["--aggregate", "--per-repo-dir", str(per_repo), "--ts", "T", + "--today", "2026-08-24", "--out", str(out)]) + assert rc == 0 + roll = json.loads(out.read_text()) + assert roll["gates"][0]["repo"] == "LibA" + assert roll["history"][-1]["date"] == "2026-08-24" + assert "gates timed" in capsys.readouterr().out + + +def test_main_records_fetch_error(tmp_path, monkeypatch, capsys): + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + out = tmp_path / "RepoA.ci_timing.json" + monkeypatch.setattr("sys.stdin", __import__("io").StringIO("{}")) + rc = ct.main(["--name", "RepoA", "--group", "libraries", "--ts", "T", + "--out", str(out), "--fetch-error", "gh api exited 1"]) + assert rc == 0 + side = json.loads(out.read_text()) + assert side["error"] == "gh api exited 1" and side["workflows"] == {} + assert "UNAVAILABLE" in capsys.readouterr().out + + +def test_main_treats_unparseable_stdin_as_fetch_error(tmp_path, monkeypatch, capsys): + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + out = tmp_path / "RepoA.ci_timing.json" + monkeypatch.setattr("sys.stdin", __import__("io").StringIO("not json at all")) + rc = ct.main(["--name", "RepoA", "--group", "libraries", "--ts", "T", + "--out", str(out)]) + assert rc == 0 + assert json.loads(out.read_text())["error"] + capsys.readouterr() diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index af67398a..e143aca8 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -580,3 +580,250 @@ def test_json_v2_carries_blockers_and_actions(): assert d["blockers"][0]["prompt"].startswith("/bug ") unobs = [s for s in d["sections"] if s["state"] == "unobserved"] assert unobs and all(s["action"]["payload"].startswith("pyauto-heart") for s in unobs) + + +# --- the ⏱ performance surface: CI wall-clock + the NO_RUN census ------------ +# Fake repo/workflow names (the tenant firewall): the real ones live in +# config/repos.yaml, which is the declared surface, never in test data. +EVENT_URL = "https://ci.invalid/actions/runs/9" +GATE_URL = "https://ci.invalid/RepoA/actions" +EVENT_PROMPT = ( + "/bug kill timer: RepoA Gate One timed_out after 18000s on main " + f"— {EVENT_URL}" +) +GATE_PROMPT = ( + "/bug smoke gate RepoA: Gate One median wall-clock rose 600s → 900s vs its " + f"recent history — {GATE_URL}" +) +ROW_PROMPT = ( + "/bug no_run: RepoA imaging/x.py SLOW since 2026-07-14 with no measurement — " + "retime against the real cap, then fix it or delete the marker" +) + + +def _ci_timing_slice(*, events=True, warn=True): + return { + "ts": TS, + "gates": [ + {"repo": "RepoA", "workflow": "Gate One", "median_s": 900.0, + "pr_median_s": 960.0, "queue_median_s": 12.0, "max_s": 1200.0, + "runs_counted": 17, "conclusions": {"success": 17}, "superseded": 2, + "actions_url": GATE_URL, "baseline_s": 600.0, "ratio": 1.5, + "delta_s": 300.0, "state": "warn" if warn else "ok", + "prompt": GATE_PROMPT if warn else None}, + {"repo": "RepoB", "workflow": "Gate Two", "median_s": 45.0, + "pr_median_s": None, "queue_median_s": 3.0, "max_s": 60.0, + "runs_counted": 4, "conclusions": {"success": 4}, "superseded": 0, + "actions_url": "https://ci.invalid/RepoB/actions", "baseline_s": None, + "ratio": None, "delta_s": None, "state": "ok", "prompt": None}, + ], + "history": [ + {"date": "2026-08-22", "gates": {"RepoA/Gate One": {"p50_s": 600.0, "runs": 10}}}, + {"date": "2026-08-23", "gates": {"RepoA/Gate One": {"p50_s": 700.0, "runs": 12}}}, + {"date": "2026-08-24", "gates": {"RepoA/Gate One": {"p50_s": 900.0, "runs": 17}}}, + ], + "events": ([{"kind": "timed_out", "repo": "RepoA", "workflow": "Gate One", + "run_url": EVENT_URL, "duration_s": 18000.0, + "head_branch": "main", "at": TS, "prompt": EVENT_PROMPT}] + if events else []), + "errors": [], + } + + +def _no_run_slice(): + return { + "ts": TS, + "totals": {"slow": 21, "needs_fix": 4, "permanent": 46, + "unmeasured_slow": 7, "repos": 11, "repos_present": 10}, + "repos": [ + {"repo": "RepoA", "present": True, "slow": 3, "needs_fix": 1, + "permanent": 5, "unmeasured_slow": 2}, + {"repo": "RepoB", "present": False, "slow": 0, "needs_fix": 0, + "permanent": 0, "unmeasured_slow": 0}, + ], + "rows": [ + {"repo": "RepoA", "entry": "imaging/x.py", "marker": "SLOW", + "date": "2026-07-14", "reason": "too slow", "measured": False, + "prompt": ROW_PROMPT}, + {"repo": "RepoA", "entry": "imaging/y.py", "marker": "NEEDS_FIX", + "date": "", "reason": "raises", "measured": False, + "prompt": "/bug no_run: RepoA imaging/y.py NEEDS_FIX since unknown date"}, + ], + } + + +def _perf_snapshot(**kw): + return make_snapshot(ci_timing=_ci_timing_slice(**kw), no_run_census=_no_run_slice()) + + +def test_sparkline_is_pure_and_needs_two_points(): + assert dashboard.sparkline([]) == "" + assert dashboard.sparkline([5]) == "" # one point is not a trend + assert dashboard.sparkline([1, 2, 3, 4]) == "▁▃▆█" + assert dashboard.sparkline([7, 7, 7]) == "▅▅▅" # flat, never a div-by-zero + assert dashboard.sparkline([1, "x", 3]) == "▁█" # garbage dropped + + +def test_both_performance_sections_render_in_every_fmt(): + snap = _perf_snapshot() + v = make_verdict() + board = dashboard.build_board(snap, v, now=FRESH_NOW) + keys = [s.key for s in board.sections] + assert "ci_timing" in keys and "no_run_census" in keys + # ...and they sit after the Test run row, where the spec puts them. + assert keys.index("ci_timing") > keys.index("test_run") + for fmt in ("term", "md", "html", "json"): + # term upper-cases its row titles, so compare case-insensitively. + out = dashboard.render(snap, v, fmt=fmt, now=FRESH_NOW).lower() + assert "ci wall-clock" in out and "no_run census" in out + + +def test_ci_timing_section_states_and_summary(): + sec = _section(dashboard.build_board(_perf_snapshot(), make_verdict(), now=FRESH_NOW), + "ci_timing") + assert sec.state == dashboard.FAIL # an event is a hard row + assert "2 gates" in sec.summary + assert "slowest RepoA Gate One 15m" in sec.summary + assert "1 slowed" in sec.summary and "1 hang event" in sec.summary + # coverage beside time, always — and the gate's own history as a sparkline + assert sec.details[0].startswith("RepoA Gate One p50 15m max 20m (17 runs)") + assert sec.details[0].rstrip().endswith("▁▃█") + + +def test_ci_timing_without_events_is_warn_when_a_gate_slowed(): + sec = _section(dashboard.build_board(_perf_snapshot(events=False), make_verdict(), + now=FRESH_NOW), "ci_timing") + assert sec.state == dashboard.WARN + # exactly one slowed gate has no run URL of its own → its prompt rides the row + assert sec.action["payload"] == GATE_PROMPT + + +def test_ci_timing_all_quiet_is_ok(): + sec = _section(dashboard.build_board(_perf_snapshot(events=False, warn=False), + make_verdict(), now=FRESH_NOW), "ci_timing") + assert sec.state == dashboard.OK + assert sec.action is None and sec.links == [] + + +def test_ci_timing_errors_are_warn_not_silence(): + slice_ = _ci_timing_slice(events=False, warn=False) + slice_["errors"] = [{"repo": "RepoC", "error": "gh api exited 1"}] + board = dashboard.build_board(make_snapshot(ci_timing=slice_), make_verdict(), + now=FRESH_NOW) + sec = _section(board, "ci_timing") + assert sec.state == dashboard.WARN + assert "1 unavailable" in sec.summary + + +def test_ci_timing_links_are_events_with_their_own_prompts(): + sec = _section(dashboard.build_board(_perf_snapshot(), make_verdict(), now=FRESH_NOW), + "ci_timing") + (link,) = sec.links + assert link["label"] == "RepoA timed_out" + assert link["url"] == EVENT_URL + assert link["prompt"] == EVENT_PROMPT + + +def test_no_run_section_summary_details_and_action(): + sec = _section(dashboard.build_board(_perf_snapshot(), make_verdict(), now=FRESH_NOW), + "no_run_census") + assert sec.state == dashboard.WARN + assert sec.summary == ("21 SLOW (7 unmeasured) / 4 NEEDS_FIX / 46 permanent " + "across 10 workspaces") + assert sec.details[0] == "RepoA: imaging/x.py SLOW 2026-07-14" + assert any("no no_run.yaml: RepoB" in d for d in sec.details) + assert sec.links == [] + assert sec.action == {"label": "copy the fix prompt", "payload": ROW_PROMPT} + + +def test_no_run_only_permanent_is_info_not_a_todo(): + slice_ = {"ts": TS, + "totals": {"slow": 0, "needs_fix": 0, "permanent": 46, + "unmeasured_slow": 0, "repos": 10, "repos_present": 10}, + "repos": [], "rows": []} + sec = _section(dashboard.build_board(make_snapshot(no_run_census=slice_), + make_verdict(), now=FRESH_NOW), "no_run_census") + assert sec.state == dashboard.INFO + assert sec.action is None + + +def test_no_run_measured_slow_only_is_ok(): + slice_ = {"ts": TS, + "totals": {"slow": 3, "needs_fix": 0, "permanent": 5, + "unmeasured_slow": 0, "repos": 2, "repos_present": 2}, + "repos": [], "rows": []} + sec = _section(dashboard.build_board(make_snapshot(no_run_census=slice_), + make_verdict(), now=FRESH_NOW), "no_run_census") + assert sec.state == dashboard.OK + + +def test_performance_rows_are_cloud_observed_not_local_only(): + """Both slices come from the GitHub API, so the cloud job measures them + first-hand — marking them "not observed here" would be a lie.""" + assert "ci_timing" not in dashboard.LOCAL_ONLY_FAMILIES + assert "no_run_census" not in dashboard.LOCAL_ONLY_FAMILIES + board = dashboard.build_board(_perf_snapshot(), make_verdict(), + unobserved=dashboard.LOCAL_ONLY_FAMILIES, now=FRESH_NOW) + assert _section(board, "ci_timing").state == dashboard.FAIL + assert _section(board, "no_run_census").state == dashboard.WARN + + +def test_board_json_carries_the_performance_block_with_prompts_verbatim(): + """The contract the Brain board consumes: every actionable row carries its + own ready-to-paste prompt, written by the producer, never re-derived.""" + d = json.loads(dashboard.render(_perf_snapshot(), make_verdict(), fmt="json", + now=FRESH_NOW)) + perf = d["performance"] + assert perf["schema"] == 1 + gate = next(g for g in perf["gates"] if g["state"] == "warn") + assert {"repo", "workflow", "median_s", "pr_median_s", "max_s", "runs_counted", + "state", "prompt", "actions_url", "spark"} == set(gate) + assert gate["prompt"] == GATE_PROMPT # verbatim, not re-derived + assert gate["spark"] == "▁▃█" + (event,) = perf["events"] + assert event["prompt"] == EVENT_PROMPT + assert event["run_url"] == EVENT_URL and event["repo"] == "RepoA" + assert perf["no_run"]["totals"]["unmeasured_slow"] == 7 + assert perf["no_run"]["rows"][0]["prompt"] == ROW_PROMPT + assert len(perf["history"]) == 3 + # schema v2 stays v2 — the performance block is purely additive. + assert d["schema_version"] == 2 + + +def test_performance_no_run_rows_are_capped_at_ten(): + slice_ = _no_run_slice() + slice_["rows"] = [dict(slice_["rows"][0], entry=f"s{i}.py") for i in range(25)] + board = dashboard.build_board(make_snapshot(no_run_census=slice_), make_verdict(), + now=FRESH_NOW) + assert len(board.performance["no_run"]["rows"]) == 10 + + +def test_html_carries_the_event_prompt_in_a_data_copy_attribute(): + out = dashboard.render(_perf_snapshot(), make_verdict(), fmt="html", now=FRESH_NOW) + assert f'data-copy="{_html_escape(EVENT_PROMPT)}"' in out + assert EVENT_URL in out + + +def _html_escape(text: str) -> str: + import html as _h + return _h.escape(text, quote=True) + + +def test_empty_slices_mean_no_sections_and_no_performance_block(): + """An ABSENT block is honest; an empty one would imply "measured, nothing + there" — the distinction a consumer needs.""" + board = dashboard.build_board(make_snapshot(), make_verdict(), now=FRESH_NOW) + keys = [s.key for s in board.sections] + assert "ci_timing" not in keys and "no_run_census" not in keys + assert board.performance is None + assert "performance" not in json.loads( + dashboard.render(make_snapshot(), make_verdict(), fmt="json", now=FRESH_NOW)) + + +def test_malformed_performance_slices_never_break_the_board(): + for snap in (make_snapshot(ci_timing="nope", no_run_census=[]), + make_snapshot(ci_timing={"gates": "nope", "events": None}), + make_snapshot(no_run_census={"rows": [None, "x"], "totals": None})): + for fmt in ("term", "md", "html", "json"): + assert isinstance(dashboard.render(snap, make_verdict(), fmt=fmt, + now=FRESH_NOW), str) diff --git a/tests/test_no_run_census.py b/tests/test_no_run_census.py new file mode 100644 index 00000000..e7204b4a --- /dev/null +++ b/tests/test_no_run_census.py @@ -0,0 +1,237 @@ +"""tests/test_no_run_census.py — the NO_RUN marker census. + +Fake repo names throughout (the tenant firewall). The parser is line-based on +purpose; the two traps it exists to survive — markers living in `#` comments, +and a bare `- off` entry parsing as a YAML boolean — are asserted directly. +""" + +from __future__ import annotations + +import json + +from heart.checks import no_run_census as nrc + +SAMPLE = """\ +# Scripts the release run does not execute. +scripts: + - imaging/slow_measured.py # SLOW 2026-07-14 - takes 233.7s, over the 300s cap + - imaging/slow_capped.py # SLOW 2026-07-14 - flakes at the 1800s cap + - imaging/slow_undated.py # SLOW - never timed + - imaging/broken.py # NEEDS_FIX 2026-07-14 - raises on the new API + - imaging/broken_undated.py # NEEDS_FIX - fails on import + - off + - generated/plot_maker.py + - "quoted/entry.py" +""" + + +def _rows(text=SAMPLE, repo="RepoA"): + return {r["entry"]: r for r in nrc.parse_no_run(text, repo)} + + +# --- tiers ------------------------------------------------------------------- + +def test_parses_all_three_tiers(): + rows = _rows() + assert rows["imaging/slow_measured.py"]["marker"] == "SLOW" + assert rows["imaging/slow_measured.py"]["date"] == "2026-07-14" + assert rows["imaging/broken.py"]["marker"] == "NEEDS_FIX" + assert rows["generated/plot_maker.py"]["marker"] == "permanent" + assert rows["generated/plot_maker.py"]["prompt"] is None + + +def test_undated_markers_keep_their_tier(): + rows = _rows() + assert rows["imaging/slow_undated.py"]["marker"] == "SLOW" + assert rows["imaging/slow_undated.py"]["date"] == "" + assert rows["imaging/broken_undated.py"]["marker"] == "NEEDS_FIX" + assert rows["imaging/broken_undated.py"]["reason"] == "fails on import" + + +def test_bare_off_entry_is_a_permanent_path_not_a_boolean(): + """The recorded crash: `- off` is a YAML boolean, and `should_skip` died on + it. Line-based parsing sees the five-letter path it actually is.""" + rows = _rows() + assert "off" in rows + assert rows["off"]["marker"] == "permanent" + assert rows["off"]["entry"] == "off" + + +def test_quoted_entries_are_unquoted(): + assert "quoted/entry.py" in _rows() + + +def test_section_keys_and_comment_lines_are_not_entries(): + rows = _rows() + assert "scripts:" not in rows + assert not any(e.startswith("#") for e in rows) + + +# --- the measured heuristic --------------------------------------------------- + +def test_a_real_seconds_figure_is_a_measurement(): + assert nrc.is_measured("takes 233.7s, over the 300s cap") is True + assert nrc.is_measured("ran in 45 s locally") is True + + +def test_a_bare_cap_mention_is_not_a_measurement(): + """"flakes at the 1800s cap" names the LIMIT the script hit, not its + runtime — exactly the unmeasured claim this census exists to surface.""" + assert nrc.is_measured("flakes at the 1800s cap") is False + assert nrc.is_measured("over the 300 s cap") is False + assert nrc.is_measured("too slow") is False + + +def test_measured_flag_lands_on_the_row(): + rows = _rows() + assert rows["imaging/slow_measured.py"]["measured"] is True + assert rows["imaging/slow_capped.py"]["measured"] is False + assert rows["imaging/slow_undated.py"]["measured"] is False + + +# --- prompts (verbatim; the producer writes them, no renderer re-derives) ----- + +def test_unmeasured_slow_prompt_is_exact(): + assert _rows()["imaging/slow_capped.py"]["prompt"] == ( + "/bug no_run: RepoA imaging/slow_capped.py SLOW since 2026-07-14 with no " + "measurement — retime against the real cap, then fix it or delete the marker" + ) + + +def test_undated_unmeasured_slow_says_unknown_date(): + assert _rows()["imaging/slow_undated.py"]["prompt"] == ( + "/bug no_run: RepoA imaging/slow_undated.py SLOW since unknown date with no " + "measurement — retime against the real cap, then fix it or delete the marker" + ) + + +def test_measured_slow_prompt_is_exact(): + assert _rows()["imaging/slow_measured.py"]["prompt"] == ( + "/bug no_run: RepoA imaging/slow_measured.py SLOW since 2026-07-14 — " + "takes 233.7s, over the 300s cap" + ) + + +def test_needs_fix_prompt_is_exact(): + assert _rows()["imaging/broken.py"]["prompt"] == ( + "/bug no_run: RepoA imaging/broken.py NEEDS_FIX since 2026-07-14 — " + "raises on the new API. Reproduce before fixing: stale markers have " + "evaporated before" + ) + + +def test_needs_fix_undated_prompt_says_unknown_date(): + assert "NEEDS_FIX since unknown date" in _rows()["imaging/broken_undated.py"]["prompt"] + + +def test_long_reasons_are_truncated(): + long_reason = "x" * 300 + row = nrc.parse_no_run(f" - a.py # NEEDS_FIX 2026-07-14 - {long_reason}", "RepoA")[0] + assert row["reason"] == long_reason # the row keeps the whole thing + assert ("x" * 121) not in row["prompt"] # the prompt is bounded + + +# --- sidecars ----------------------------------------------------------------- + +def test_sidecar_counts_every_tier(): + side = nrc.build_sidecar("RepoA", "workspaces", SAMPLE, "T") + assert side["present"] is True + assert side["slow"] == 3 + assert side["unmeasured_slow"] == 2 + assert side["needs_fix"] == 2 + assert side["permanent"] == 3 # off, generated/plot_maker.py, quoted + assert side["ts"] == "T" + + +def test_missing_file_is_present_false_not_an_error(): + """One workspace_test repo genuinely has no no_run.yaml. That is honest + data; an empty census would read as "nothing skipped here".""" + side = nrc.build_sidecar("RepoB", "workspaces_test", "", "T", present=False) + assert side["present"] is False + assert side["rows"] == [] + assert side["slow"] == side["needs_fix"] == side["permanent"] == 0 + + +def test_empty_but_present_file_is_a_clean_census(): + side = nrc.build_sidecar("RepoC", "workspaces", "scripts:\n", "T") + assert side["present"] is True and side["rows"] == [] + + +# --- aggregate ---------------------------------------------------------------- + +def _agg(): + a = nrc.build_sidecar("RepoA", "workspaces", SAMPLE, "T") + b = nrc.build_sidecar("RepoB", "workspaces_test", "", "T", present=False) + c = nrc.build_sidecar( + "RepoC", "howto", + " - slow/one.py # SLOW 2026-08-01 - 91.2s measured\n" + " - fine/two.py\n", "T") + return nrc.aggregate([a, b, c], "T") + + +def test_aggregate_totals(): + roll = _agg() + assert roll["totals"] == {"slow": 4, "needs_fix": 2, "permanent": 4, + "unmeasured_slow": 2, "repos": 3, "repos_present": 2} + + +def test_aggregate_repo_summaries_include_the_absent_repo(): + roll = _agg() + by_repo = {r["repo"]: r for r in roll["repos"]} + assert by_repo["RepoB"]["present"] is False + assert by_repo["RepoC"]["slow"] == 1 + + +def test_aggregate_rows_are_worst_first_and_actionable_only(): + roll = _agg() + markers = [(r["marker"], r["measured"]) for r in roll["rows"]] + # unmeasured SLOW, then NEEDS_FIX, then measured SLOW; permanent never. + assert markers == [("SLOW", False), ("SLOW", False), + ("NEEDS_FIX", False), ("NEEDS_FIX", False), + ("SLOW", True), ("SLOW", True)] + assert all(r["prompt"] for r in roll["rows"]) + assert all(r["repo"] for r in roll["rows"]) + + +def test_summary_lines(monkeypatch): + monkeypatch.setenv("NO_COLOR", "1") + roll = _agg() + line = nrc.summary_line(roll) + assert "4 SLOW (2 unmeasured) / 2 NEEDS_FIX / 4 permanent" in line + assert "across 2 workspaces" in line + absent = nrc.repo_summary_line({"name": "RepoB", "present": False}) + assert "no no_run.yaml" in absent + + +# --- main wiring -------------------------------------------------------------- + +def test_main_writes_sidecar_then_aggregates(tmp_path, monkeypatch, capsys): + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + per_repo = tmp_path / "per-repo" + per_repo.mkdir() + monkeypatch.setattr("sys.stdin", __import__("io").StringIO(SAMPLE)) + rc = nrc.main(["--name", "RepoA", "--group", "workspaces", "--ts", "T", + "--out", str(per_repo / "RepoA.no_run_census.json")]) + assert rc == 0 + side = json.loads((per_repo / "RepoA.no_run_census.json").read_text()) + assert side["unmeasured_slow"] == 2 + + out = tmp_path / "no_run_census.json" + rc = nrc.main(["--aggregate", "--per-repo-dir", str(per_repo), "--ts", "T", + "--out", str(out)]) + assert rc == 0 + roll = json.loads(out.read_text()) + assert roll["totals"]["slow"] == 3 + assert "SLOW" in capsys.readouterr().out + + +def test_main_missing_writes_present_false(tmp_path, monkeypatch, capsys): + monkeypatch.setenv("HEART_STATE_DIR", str(tmp_path)) + monkeypatch.setenv("NO_COLOR", "1") + out = tmp_path / "RepoB.no_run_census.json" + rc = nrc.main(["--name", "RepoB", "--group", "workspaces_test", "--ts", "T", + "--missing", "--out", str(out)]) + assert rc == 0 + assert json.loads(out.read_text())["present"] is False + assert "no no_run.yaml" in capsys.readouterr().out