diff --git a/docs/internals.md b/docs/internals.md index 80fea312..26dcc990 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -29,6 +29,21 @@ first; read this only when changing Heart's own code. the bash equivalent (`heart_write_json` in `_common.sh`). Concurrent ticks must not corrupt `state.json`. +## Aggregated repository observations + +`heart.state.aggregate()` includes cached per-repository sidecars only for +names in a valid current `config/repos.yaml` monitoring roster. Removing a +repository from that roster removes it from the current snapshot while +preserving every cache file. Global check evidence remains unchanged, and +configured repositories without sidecars remain without observations rather +than receiving fabricated passing evidence. + +The roster must contain a `repos` mapping of named groups to lists of entries +with valid repository names. Explicit empty lists describe an empty roster. +Missing, unreadable or malformed configuration disables exclusion: all cached +observations remain visible, preserving adverse evidence until configuration +can be trusted. + ## Dashboard consumer contract Readiness emits additive `repository_reasons` with gate keys, plus a `penalties` diff --git a/heart/state.py b/heart/state.py index af9df358..565e11c7 100644 --- a/heart/state.py +++ b/heart/state.py @@ -11,10 +11,15 @@ import datetime import json import os +import re import tempfile from pathlib import Path from typing import Any +import yaml + +CONFIG_PATH = Path(__file__).resolve().parents[1] / "config" / "repos.yaml" + HEART_STATE_DIR = Path( os.environ.get("HEART_STATE_DIR") or str(Path.home() / ".pyauto-heart") @@ -54,9 +59,30 @@ def _read_json_or_default(path: Path, default: Any) -> Any: return default +def _configured_repos() -> set[str] | None: + """Return the validated roster, or None when exclusion is not justified.""" + try: + config = yaml.safe_load(CONFIG_PATH.read_text()) + except (OSError, UnicodeError, yaml.YAMLError): + return None + if not isinstance(config, dict) or not isinstance(config.get("repos"), dict): + return None + names: set[str] = set() + for group, entries in config["repos"].items(): + if not isinstance(group, str) or not group.strip() or not isinstance(entries, list): + return None + for entry in entries: + name = entry.get("name") if isinstance(entry, dict) else None + if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_.-]+", name): + return None + names.add(name) + return names + + def aggregate() -> dict[str, Any]: """Collapse per-repo JSON sidecars into one state.json snapshot.""" _ensure_dirs() + configured = _configured_repos() repos: dict[str, dict[str, Any]] = {} for entry in sorted(HEART_PER_REPO_DIR.glob("*.json")): # Filenames: ..json. Group by repo name. @@ -65,6 +91,8 @@ def aggregate() -> dict[str, Any]: if len(parts) < 3 or parts[-1] != "json": continue name = parts[0] + if configured is not None and name not in configured: + continue check_kind = ".".join(parts[1:-1]) data = _read_json_or_default(entry, {}) repos.setdefault(name, {})[check_kind] = data diff --git a/tests/test_state.py b/tests/test_state.py index 56f6d984..5cdec253 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -18,6 +18,9 @@ def temp_state_dir(tmp_path, monkeypatch): import heart.state as state_mod importlib.reload(state_mod) + config = tmp_path / "repos.yaml" + config.write_text("repos:\n test:\n - name: PyAutoFit\n - name: PyAutoArray\n - name: Foo\n") + monkeypatch.setattr(state_mod, "CONFIG_PATH", config, raising=False) return tmp_path, state_mod @@ -70,3 +73,45 @@ def test_load_roundtrips_after_aggregate(temp_state_dir): def test_age_seconds_returns_none_for_missing_cache(temp_state_dir): _, state = temp_state_dir assert state.age_seconds() is None + + +def test_aggregate_filters_retired_repos_without_deleting_evidence(temp_state_dir): + tmp_path, state = temp_state_dir + state.CONFIG_PATH.write_text("repos:\n libraries:\n - name: PyAutoFit\n - name: MissingRepo\n") + retired = tmp_path / "per-repo/PyAutoConf.ci_status.json" + current = tmp_path / "per-repo/PyAutoFit.ci_status.json" + state.atomic_write_json(retired, {"conclusion": "failure"}) + state.atomic_write_json(current, {"conclusion": "failure"}) + state.atomic_write_json(tmp_path / "manifest_drift.json", {"problem_count": 7}) + contents = retired.read_bytes() + snap = state.aggregate() + assert set(snap["repos"]) == {"PyAutoFit"} + assert snap["repos"]["PyAutoFit"]["ci_status"]["conclusion"] == "failure" + assert snap["manifest_drift"] == {"problem_count": 7} + assert retired.read_bytes() == contents + assert not (tmp_path / "per-repo/MissingRepo.ci_status.json").exists() + + +@pytest.mark.parametrize("config", [None, "[invalid", "", "[]", "{}", + "repos: null", "repos: []", "repos: {libraries: null}", + "repos: {libraries: [null]}", "repos: {libraries: [{}]}", + "repos: {libraries: [{name: 123}]}", "repos: {libraries: [{name: ''}]}", + "repos: {libraries: [{name: 'bad name'}]}", + "repos: {libraries: [{name: '../bad'}]}", + "repos: {libraries: [{name: PyAutoFit}, {name: null}]}" ]) +def test_bad_or_missing_config_retains_observations(temp_state_dir, config): + tmp_path, state = temp_state_dir + if config is None: + state.CONFIG_PATH.unlink() + else: + state.CONFIG_PATH.write_text(config) + state.atomic_write_json(tmp_path / "per-repo/PyAutoConf.ci_status.json", + {"conclusion": "failure"}) + assert "PyAutoConf" in state.aggregate()["repos"] + + +def test_explicit_empty_config_roster_excludes_cached_repos(temp_state_dir): + tmp_path, state = temp_state_dir + state.CONFIG_PATH.write_text("repos: {libraries: []}") + state.atomic_write_json(tmp_path / "per-repo/PyAutoConf.ci_status.json", {}) + assert state.aggregate()["repos"] == {}