From 70e1177db4f57a942d25911d0036f9f7829d4eeb Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 2 Oct 2026 10:00:00 +0100 Subject: [PATCH] fix: score and repair the complete Heart monitoring inventory --- docs/internals.md | 34 +++ heart/checks/import_time.py | 3 + heart/checks/manifest_drift.py | 3 + heart/checks/profiling_drift.py | 3 + heart/checks/required_workflow_drift.py | 3 + heart/checks/script_timing.py | 7 +- heart/checks/smoke_timings.py | 1 + heart/checks/unit_test_timing.py | 3 + heart/checks/unit_timings.py | 6 + heart/checks/version_skew.py | 2 + heart/checks/workspace_testmode_timing.py | 3 + heart/checks/worktree_drift.py | 3 + heart/dashboard.py | 89 +++++- heart/monitoring.py | 316 ++++++++++++++++++++++ heart/publish.py | 27 ++ tests/test_dashboard.py | 22 +- tests/test_dashboard_disclosures.py | 4 +- tests/test_dashboard_reasons.py | 2 +- tests/test_monitoring.py | 175 ++++++++++++ tests/test_unit_timings.py | 4 +- tests/test_version_skew.py | 3 +- 21 files changed, 683 insertions(+), 30 deletions(-) create mode 100644 heart/monitoring.py create mode 100644 tests/test_monitoring.py diff --git a/docs/internals.md b/docs/internals.md index 464436c9..32ac74a9 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -129,3 +129,37 @@ time (the earlier stage start), so a new cloud runner cannot rejuvenate an old pass. Installation checks retain their own timestamps and source/index. Readiness still checks release fidelity, current library SHAs and evidence age. This bounded search is daily-only and does not add work to the fast local tick. + +## Monitoring completeness + +The dashboard's headline is `monitoring.score`; `verdict`, `score`, and +`penalties` retain their release-readiness meanings for existing consumers. +Release gating is unchanged. Badges label both assessments. The cockpit +`state.status` remains the release verdict (the development entry guard reads +it); its headline and items also report monitoring findings. + +`heart.monitoring` owns the complete inventory: expected active check families, +all configured repositories (including organs and developer workspaces), raw +nested observations, and missing evidence. `monitoring.checks` includes passing +and explicitly inapplicable observations; `findings` includes every unresolved +one with a stable ID, source, timestamp, and remedy. Repair consumers must read +this full inventory, not the capped visual summaries or clipboard prompt. +`pyauto-brain health --scope dashboard` adopts this assessment. Release GREEN +alone cannot complete that loop. + +Monitoring starts at 100. Each family deducts its worst unresolved status: +red 10, yellow 5, missing/expired evidence 2, with a total floor of zero. +Multiple projections of a family cannot multiply its penalty. A score of 100 +requires fresh green evidence across all applicable checks. Permanent exclusions +are explicit N/A records. Missing comparisons, unfinished baselines and zero +measured tests are gaps; the retired workspace-testmode collector is not an +expected check (its replacement is smoke timings). + +Observation age comes from the collector, never a new aggregation timestamp. +The monitoring freshness windows are two days for local/coverage checks, seven +days for timing evidence, and fourteen for installation/rehearsal evidence; +release-specific source and freshness rules still apply through readiness. +Old adverse results remain adverse. Undated results require a collector refresh. +Published local observations carry their full inventory and per-repository +checkout evidence. Private records retain their status and an opaque ID with a +local investigation action; private paths never travel to the public board. diff --git a/heart/checks/import_time.py b/heart/checks/import_time.py index 71589de8..f8c47c5f 100644 --- a/heart/checks/import_time.py +++ b/heart/checks/import_time.py @@ -174,7 +174,10 @@ def run( "samples": len(prior), }) + import datetime as observation_time + summary = { + "ts": observation_time.datetime.now(observation_time.timezone.utc).isoformat(), "python": python, "packages_measured": measured, "packages_unavailable": unavailable, diff --git a/heart/checks/manifest_drift.py b/heart/checks/manifest_drift.py index ff2f1542..1ecef40a 100644 --- a/heart/checks/manifest_drift.py +++ b/heart/checks/manifest_drift.py @@ -92,6 +92,9 @@ def run() -> dict[str, Any]: sys.path.insert(0, str(HEART_HOME)) from heart import state + import datetime as observation_time + result["ts"] = observation_time.datetime.now(observation_time.timezone.utc).isoformat() + state.atomic_write_json(HEART_STATE_DIR / "manifest_drift.json", result) return result diff --git a/heart/checks/profiling_drift.py b/heart/checks/profiling_drift.py index b307fd7f..887be585 100644 --- a/heart/checks/profiling_drift.py +++ b/heart/checks/profiling_drift.py @@ -108,6 +108,9 @@ def run(results_root: Path | None = None) -> dict[str, Any]: sys.path.insert(0, str(HEART_HOME)) from heart import state + import datetime as observation_time + summary["ts"] = observation_time.datetime.now(observation_time.timezone.utc).isoformat() + state.atomic_write_json(HEART_STATE_DIR / "profiling_drift.json", summary) return summary diff --git a/heart/checks/required_workflow_drift.py b/heart/checks/required_workflow_drift.py index c621d2f2..bfd753c9 100644 --- a/heart/checks/required_workflow_drift.py +++ b/heart/checks/required_workflow_drift.py @@ -182,6 +182,9 @@ def run(config_path: Path | str = CONFIG_PATH) -> dict[str, Any]: sys.path.insert(0, str(HEART_HOME)) from heart import state + import datetime as observation_time + result["ts"] = observation_time.datetime.now(observation_time.timezone.utc).isoformat() + state.atomic_write_json( HEART_STATE_DIR / "required_workflow_drift.json", result ) diff --git a/heart/checks/script_timing.py b/heart/checks/script_timing.py index c1bbe8f5..654faaa1 100644 --- a/heart/checks/script_timing.py +++ b/heart/checks/script_timing.py @@ -326,6 +326,7 @@ def scan_latest_results(results_dir: Path) -> list[dict[str, Any]]: "directory": directory, "file": file_path, "duration": float(duration), + "observed_at": datetime.datetime.fromtimestamp(json_path.stat().st_mtime, datetime.timezone.utc).isoformat(), }) return entries @@ -350,6 +351,9 @@ def run(results_dir: Path | None = None) -> dict[str, Any]: migrations: list[dict[str, str]] = [] scanned = scan_latest_results(results_dir) + # Reading yesterday's run again is not a new timing observation. + observed_times = [e["observed_at"] for e in scanned if e.get("observed_at")] + evidence_ts = min(observed_times) if observed_times else None slugs = [slug_for(e["project"], e["directory"], e["file"]) for e in scanned] touched = set(slugs) # Anything this scan does not write to is a candidate stranded baseline. @@ -396,6 +400,7 @@ def run(results_dir: Path | None = None) -> dict[str, Any]: findings[category].append(record) summary = { + "ts": evidence_ts, "results_dir": str(results_dir), "run_id": run_id, "total_scripts": total, @@ -404,7 +409,7 @@ def run(results_dir: Path | None = None) -> dict[str, Any]: "migrated_count": len(migrations), "orphaned_count": len(orphans), "migrated": migrations[:MAX_LISTED], - "orphaned": orphans[:MAX_LISTED], + "orphaned": orphans, "red_count": len(findings["red"]), "yellow_count": len(findings["yellow"]), "green_count": len(findings["green"]), diff --git a/heart/checks/smoke_timings.py b/heart/checks/smoke_timings.py index 26d96d5d..b40343a0 100644 --- a/heart/checks/smoke_timings.py +++ b/heart/checks/smoke_timings.py @@ -813,6 +813,7 @@ def _name_of(side: Any) -> str: prev_run_id = (prev_row or {}).get("run_id") prev_run_url = str((prev_row or {}).get("run_url") or "") leg_rows.append({ + "at": at, "repo": repo, "python": python, "entry": name, diff --git a/heart/checks/unit_test_timing.py b/heart/checks/unit_test_timing.py index cd7153d0..df30fafb 100644 --- a/heart/checks/unit_test_timing.py +++ b/heart/checks/unit_test_timing.py @@ -178,7 +178,10 @@ def run(runner: Runner | None = None, repos: list[str] | None = None) -> dict[st "samples": len(history) - 1, }) + import datetime as observation_time + summary = { + "ts": observation_time.datetime.now(observation_time.timezone.utc).isoformat(), "python": python, "repos_measured": repos_measured, "repos_unavailable": unavailable, diff --git a/heart/checks/unit_timings.py b/heart/checks/unit_timings.py index 50a00465..d717246a 100644 --- a/heart/checks/unit_timings.py +++ b/heart/checks/unit_timings.py @@ -628,6 +628,7 @@ def _name_of(side: Any) -> str: prev_run_id = (prev_row or {}).get("run_id") prev_run_url = str((prev_row or {}).get("run_url") or "") tests.append({ + "at": at, "repo": repo, "python": python, "nodeid": nodeid, @@ -652,6 +653,7 @@ def _name_of(side: Any) -> str: import_s, history.get((repo, package, python)), thr ) imports.append({ + "at": at, "repo": repo, "package": package, "python": python, @@ -757,7 +759,10 @@ def legacy_summaries( else: unit["green"].append(entry) + evidence_times = [str(r.get("at")) for r in repos if r.get("at")] + evidence_ts = min(evidence_times) if evidence_times else None unit_summary = { + "ts": evidence_ts, "python": LEGACY_PYTHON, "repos_measured": len(measured), "repos_unavailable": unavailable, @@ -800,6 +805,7 @@ def legacy_summaries( imports.get(state, imports["green"]).append(entry) import_summary = { + "ts": evidence_ts, "python": LEGACY_PYTHON, "packages_measured": packages_measured, "packages_unavailable": packages_unavailable, diff --git a/heart/checks/version_skew.py b/heart/checks/version_skew.py index 853dd1e9..0e7fd48b 100644 --- a/heart/checks/version_skew.py +++ b/heart/checks/version_skew.py @@ -255,6 +255,8 @@ def main(argv: list[str]) -> int: # clobber live state. The --pypi leg gets its own sidecar so the tick's # version_skew.json rewrite never clobbers on-demand PyPI evidence. name = "version_skew_pypi.json" if pypi else "version_skew.json" + import datetime + result["ts"] = datetime.datetime.now(datetime.timezone.utc).isoformat() state.atomic_write_json(HEART_STATE_DIR / name, result) from heart.heart_color import c_ok, c_warn, c_fail, c_info, c_meta, glyph_ok, glyph_warn, glyph_fail diff --git a/heart/checks/workspace_testmode_timing.py b/heart/checks/workspace_testmode_timing.py index e6893ed4..ad28a2b3 100644 --- a/heart/checks/workspace_testmode_timing.py +++ b/heart/checks/workspace_testmode_timing.py @@ -170,7 +170,10 @@ def run(runner: Runner | None = None, scripts: list[tuple[str, str]] | None = No "samples": len(history) - 1, }) + import datetime as observation_time + summary = { + "ts": observation_time.datetime.now(observation_time.timezone.utc).isoformat(), "python": python, "mode": "PYAUTO_TEST_MODE=2 PYAUTO_WORKSPACE_SMALL_DATASETS=1", "scripts_measured": measured, diff --git a/heart/checks/worktree_drift.py b/heart/checks/worktree_drift.py index 3bf27abd..f9febfa5 100644 --- a/heart/checks/worktree_drift.py +++ b/heart/checks/worktree_drift.py @@ -184,6 +184,9 @@ def main(argv: list[str] | None = None) -> int: sys.path.insert(0, str(HEART_HOME)) from heart import state + import datetime as observation_time + result["ts"] = observation_time.datetime.now(observation_time.timezone.utc).isoformat() + state.atomic_write_json(HEART_STATE_DIR / "worktree_drift.json", result) from heart.heart_color import c_fail, c_info, c_ok, c_warn, glyph_fail, glyph_ok, glyph_warn diff --git a/heart/dashboard.py b/heart/dashboard.py index 4b274237..38af20a5 100644 --- a/heart/dashboard.py +++ b/heart/dashboard.py @@ -275,6 +275,7 @@ class Board: red_reasons: list[str] yellow_reasons: list[str] sections: list[Section] + monitoring: dict | None = None # readiness freshness tier: evidence missing/expired, nothing known-bad # (heart/readiness.py) — distinct from the tick-age `stale` bool above. stale_reasons: list[str] = field(default_factory=list) @@ -724,6 +725,16 @@ def build_board( repository_reasons=repository_reasons, ts=ts) if ws_sec: sections.append(ws_sec) + other_entries = [] + for name, body in sorted(repos.items()): + if isinstance(body, dict) and not _is_library(name, body) and _repo_group(body) not in GATED_WORKSPACE_GROUPS: + other_entries.extend(_repo_entries(name, body, unobserved=unobserved, + repository_reasons=repository_reasons, ts=ts)) + if other_entries: + sections.append(Section("other_repositories", "Other monitored repositories", + _worst(e["state"] for e in other_entries), + f"{len({e['subject'] for e in other_entries})} repos", + entries=other_entries)) # Worktree drift --------------------------------------------------------- if "worktree_drift" in unobserved: @@ -1118,6 +1129,8 @@ def build_board( devbox_observed=(f"dev box last observed {format_age(_age_seconds(devbox.get('ts'), now))}" if isinstance(devbox, dict) and devbox.get("ts") else None), ) + from heart import monitoring + board.monitoring = monitoring.assess(board, snapshot, devbox=devbox, now=now) board.fix_plan = build_fix_plan(board, snapshot, devbox=devbox) return board @@ -1131,6 +1144,11 @@ def build_fix_plan(board: Board, snapshot: dict | None = None, *, """ lines = [ "Use the health skill. Work through this Heart dashboard systematically in this chat.", + "Scope: every monitored check. Run pyauto-brain health --scope dashboard --json. " + "Read monitoring.checks and monitoring.findings in the full board JSON before acting. " + "Release GREEN is not completion: finish only when monitoring.complete is true, " + "or report every unresolved finding, evidence gap and environment blocker. " + "Reconcile the same finding IDs after refresh; do not stop at a green release verdict.", f"Snapshot: {board.ts or 'unknown'}; verdict: {board.verdict}; score: {board.score}.", "1. Read current authoritative Heart evidence first. Reconcile older dev-box " "observations and the published board before acting; this snapshot may be stale.", @@ -1155,6 +1173,11 @@ def build_fix_plan(board: Board, snapshot: dict | None = None, *, for key in ("run_url", "command", "prompt"): if item.get(key): lines.append(f" {key}: {item[key]}") + if board.monitoring: + lines += ["", "Complete monitoring inventory (full records in monitoring.checks):"] + for finding in board.monitoring["findings"][:20]: + lines.append(f"- {finding['id']} [{finding['status']}]: {finding['summary']}") + lines.append(f"{len(board.monitoring['findings'])} total findings; read monitoring.findings for every ID and remedy.") if board.stale_plan: lines += ["", "Refresh missing evidence:", board.stale_plan["prompt"]] lines += ["", "Section observations (not additional readiness blockers):"] @@ -1182,7 +1205,7 @@ def build_fix_plan(board: Board, snapshot: dict | None = None, *, "unit_test_timing", "unit_timings", "ci_timing", "smoke_timings", "test_run", "validation_report", "verify_install", "url_check", "version_skew", "profiling_drift", "manifest_drift", - "required_workflow_drift", "no_run_census"): + "required_workflow_drift", "no_run_census", "workspace_testmode_timing", "version_skew_pypi"): if source.get(key): evidence[key] = source[key] if devbox: @@ -1199,7 +1222,7 @@ def build_fix_plan(board: Board, snapshot: dict | None = None, *, evidence_note = ( "\n\nFull evidence: read the published Heart board.json at " - f"{PAGES_URL}board.json, including blockers, sections, performance and " + f"{PAGES_URL}board.json, including monitoring.checks, monitoring.findings, blockers, sections, performance and " "fix_plan.evidence. For local evidence use pyauto-heart dashboard --json " "and the state.json/release_ready.json files in HEART_STATE_DIR " "(default ~/.pyauto-heart). Reconcile timestamps before acting. " @@ -1755,7 +1778,7 @@ def _devbox_enrich( [str(x) for x in (d.get("details") or [])][:8], links=sec.links, action=sec.action, observed_ago=f"observed {ago} on the dev box", - entries=[{**e, "source": "published dev-box observation", + entries=[{**e, "original_source": e.get("source"), "source": "published dev-box observation", "observed_at": devbox.get("ts")} for e in d.get("entries", []) if isinstance(e, dict)], )) @@ -1810,6 +1833,7 @@ def _render_term(board: Board, verdict: dict, *, quiet: bool) -> str: if board.stale: out.append(" " + c_warn("! board is stale — run `pyauto-heart tick` for fresh numbers")) out.append("") + out.append(f"MONITORING {monitoring_score(board)}/100 — {(board.monitoring or {}).get('status', 'unknown').upper()}") out.extend(render_readiness_block(verdict, quiet=quiet)) out.append("") for sec in board.sections: @@ -1834,7 +1858,7 @@ def _render_oneline(board: Board) -> str: tail = "all green" age = format_age(board.age_seconds, stale=board.stale) coloured_word = _colour(state, f"{word} {board.score}") - return f"PyAuto {dot} {coloured_word} {tail} (tick {age})" + return f"PyAuto monitoring {monitoring_score(board)}/100; release {dot} {coloured_word} {tail} (tick {age})" def _shown_reasons(board: Board) -> tuple[str, list[dict]]: @@ -1888,7 +1912,7 @@ def _render_md(board: Board) -> str: emoji = _STATE_MD[_VERDICT_STATE.get(board.verdict, OK)] age = format_age(board.age_seconds, stale=board.stale) lines = [ - f"## {emoji} PyAutoHeart Dashboard — **{word}** (score {board.score})", + f"## {emoji} PyAutoHeart Dashboard — monitoring {monitoring_score(board)}/100; release **{word}**", "", f"_snapshot `{board.ts}` · {age}_" + (" ⚠️ **stale — run `pyauto-heart tick`**" if board.stale else ""), @@ -1922,7 +1946,7 @@ def _render_md_brief(board: Board) -> str: word = _VERDICT_WORD.get(board.verdict, "GREEN") emoji = _STATE_MD[_VERDICT_STATE.get(board.verdict, OK)] lines = [ - f"{emoji} **{word}** · score {board.score} · [dashboard →]({PAGES_URL})" + f"{emoji} Monitoring {monitoring_score(board)}/100 · release **{word}** · [dashboard →]({PAGES_URL})" ] if board.verdict in ("red", "yellow"): label, items = _shown_reasons(board) @@ -2139,6 +2163,26 @@ def _html_entries(entries: list[dict]) -> str: return '' +def monitoring_score(board: Board) -> int: + return board.monitoring["score"] if board.monitoring else board.score + + +def _html_monitoring(board: Board) -> str: + if not board.monitoring: + return "" + findings = board.monitoring["findings"] + rows = [] + for item in findings: + action = item.get("action") or {} + button = _copy_btn(action["payload"], "inspect finding") if action.get("payload") else "" + rows.append(f'
  • {_html.escape(item["subject"])} [{item["status"]}]: ' + f'{_html.escape(item["summary"])} {button}' + f'
    {_html.escape(item["id"])} · {_html.escape(item["source"])} · ' + f'{_html.escape(str(item["observed_at"] or "time unknown"))}
  • ') + return (f'
    All monitoring findings ({len(findings)})' + f'
    ') + + def _html_score(board: Board) -> str: if board.penalties is None: body = "This older verdict did not record a breakdown. Refresh Heart evidence to see it." @@ -2159,7 +2203,16 @@ def _html_score(board: Board) -> str: body = ("Start at 100; subtract these capped penalties, with a floor of 0. " "The verdict is determined by the reasons, not the score.") - return f'
    Why this score: {board.score}/100{body}
    ' + release = f'
    Release readiness score: {board.score}/100{body}
    ' + if not board.monitoring: + return release + m = board.monitoring + rows = "".join(f"
  • {_html.escape(p['key'])}: −{p['points']} ({p['count']} unresolved observations; family cap 10)
  • " for p in m["penalties"]) + return (f'
    Why this monitoring score: {m["score"]}/100' + 'Start at 100. Each family deducts its worst unresolved status: red 10, yellow 5, missing or expired evidence 2; ' + 'summary and individual rows are charged once per family, with a total floor of 0. ' + '100 requires fresh green evidence for every applicable check. Explicit permanent exclusions are listed separately.' + f'
    ' + release) def _html_actions(board: Board) -> str: @@ -2282,7 +2335,8 @@ def _render_html(board: Board) -> str:
    {''.join(rows)}

    Score

    -

    {board.score}/100 +

    {monitoring_score(board)}/100 +Monitoring: {(board.monitoring or {}).get("status", "unknown").upper()} Release readiness: {word}

    snapshot {_html.escape(board.ts)} · {age} · markdown version{github_link}

    @@ -2290,6 +2344,7 @@ def _render_html(board: Board) -> str:

    {_html.escape(board.vantage)} · {_html.escape(board.devbox_observed or ('no dev-box observation attached' if board.vantage == 'cloud snapshot' else 'observed on this dev box'))}

    {_html_score(board)} +{_html_monitoring(board)}

    {len(board.red_reasons)} release blockers · {len(board.yellow_reasons)} warnings · {len(board.stale_reasons)} evidence gaps

    @@ -2311,7 +2366,8 @@ def to_dict(board: Board) -> dict[str, Any]: payload: dict[str, Any] = { "schema_version": SCHEMA_VERSION, "verdict": board.verdict, - "score": board.score, + "score": board.score, # legacy release score; monitoring.score is the headline + "monitoring": board.monitoring, "ts": board.ts, "age_seconds": board.age_seconds, "stale": board.stale, @@ -2367,8 +2423,8 @@ def badge_endpoint(board: Board) -> dict[str, Any]: return { "schemaVersion": 1, "label": "health", - "message": f"{word} · {board.score}", - "color": _BADGE_COLOR.get(board.verdict, "lightgrey"), + "message": f"Monitoring {(board.monitoring or {}).get('status', 'unknown').upper()} · {monitoring_score(board)}; release {word}", + "color": _BADGE_COLOR.get((board.monitoring or {}).get("status", board.verdict), "lightgrey"), } @@ -2437,10 +2493,12 @@ def to_state(board: Board) -> dict[str, Any]: return grey_state() first = next((r for rs in (board.red_reasons, board.yellow_reasons, board.stale_reasons) for r in rs), None) - if first is not None: + if board.monitoring: + headline = f"Release {status.upper()}; monitoring {board.monitoring['status'].upper()} · {monitoring_score(board)}/100 · {len(board.monitoring['findings'])} unresolved" + elif first is not None: headline = str(first) else: - headline = f"{_VERDICT_WORD.get(status, 'GREEN')} \u00b7 {board.score} \u2014 all clear" + headline = f"Release {status.upper()} · {board.score} — monitoring not assessed" items: list[dict[str, Any]] = [] for b in board.blockers: sev = b.get("severity") @@ -2455,6 +2513,11 @@ def to_state(board: Board) -> dict[str, Any]: if not any(b.get("severity") == "stale" for b in board.blockers): items += [{"severity": "info", "text": _clip(r), "url": None, "prompt": None} for r in board.stale_reasons] + if board.monitoring: + for finding in board.monitoring["findings"]: + items.append({"severity": finding["status"] if finding["status"] in ("red", "yellow") else "info", + "text": _clip(finding["subject"] + ": " + finding["summary"]), "url": None, + "prompt": (finding.get("action") or {}).get("payload")}) state = grey_state() state.update(status=status, headline=_clip(headline), updated=_iso_z(board.ts), items=items) diff --git a/heart/monitoring.py b/heart/monitoring.py new file mode 100644 index 00000000..b8613cef --- /dev/null +++ b/heart/monitoring.py @@ -0,0 +1,316 @@ +"""Complete dashboard coverage, separate from the authoritative release gate. + +Pure projection: no checks run here. Family penalties are capped so one large +repo cannot dominate the score. Every unresolved observation remains in the +inventory, including those omitted by display and clipboard budgets. +""" +from __future__ import annotations + +import datetime as dt +import hashlib +from collections import Counter +from pathlib import Path + +import yaml + +# Expected evidence produced by tick or the daily/deep collectors. Metadata +# (timings_record) and duplicate unit timing summaries are not separate checks. +FAMILIES = { + "worktree_drift": "Worktree drift", + "script_timing": "Script timing", + "import_time": "Import timing", + "unit_test_timing": "Unit-test timing", + "profiling_drift": "Profiling drift", + "test_run": "Workspace validation", + "ci_timing": "CI wall-clock", + "smoke_timings": "Smoke scripts", + "no_run_census": "Skipped-script census", + "version_skew": "Version floors", + "version_skew_pypi": "PyPI version floors", + "manifest_drift": "Repository manifest drift", + "required_workflow_drift": "Required workflow coverage", + "verify_install": "Install verification", + "url_check": "URL hygiene", + "validation_report": "Release validation", +} +ALIASES = {"release_validation": "validation_report"} +STATES = {"ok": "green", "success": "green", "passed": "green", "pass": "green", + "warn": "yellow", "fail": "red", "failed": "red", "failure": "red", + "timed_out": "red", "timeout": "red", "unobserved": "grey", + "info": "grey", "unknown": "grey", "building": "grey", + "satisfiable": "green", "unsatisfiable": "red", "bad": "red", + "floor_yanked": "yellow", "in_progress": "grey", "queued": "grey"} +ORDER = {"red": 0, "yellow": 1, "stale": 2, "grey": 3, "green": 4, "na": 5} +POINTS = {"red": 10, "yellow": 5, "stale": 2, "grey": 2} + + +def status(value): + value = str(value or "grey").lower() + return value if value in ORDER else STATES.get(value, "grey") + + +def timestamp(value): + try: + t = dt.datetime.fromisoformat(str(value).replace("Z", "+00:00")) + return t.replace(tzinfo=dt.timezone.utc) if t.tzinfo is None else t + except (ValueError, TypeError): + return None + + +def remedy(family, subject, gap=False): + if family in {"worktree_drift", "repo_state"}: + text = (f"Use the health and repo-cleanup skills. Inspect {subject} in the canonical " + "checkout and active task ledger on the dev box. Preserve edits and claims; " + "refresh with pyauto-heart tick and publish with pyauto-heart publish. " + "Do not delete, reset, merge or close work without authorization.") + elif family in {"validation_report", "test_run", "verify_install"}: + text = (f"Use the health and release skills to inspect {subject}. " + "For missing evidence, use the documented validation or install-verification " + "procedure in the required environment, ingest results and re-assess. " + "A rehearsal is not authorization to publish a release.") + elif family in {"import_time", "unit_test_timing", "unit_timings", "ci_timing", "smoke_timings", "script_timing", "workspace_testmode_timing", "no_run_census"}: + text = (f"Use the hygiene and ci-speedup skills to inspect {subject}. Read the full " + f"{family} evidence and its collector instructions. Obtain missing runtime " + "measurements or baselines in the required environment; diagnose regressions " + "and skipped scripts through start-dev. Refresh the collector and publish " + "Heart evidence. A tick alone does not run deep timing measurements.") + elif family == "url_check": + text = "Use the hygiene skill. Run pyauto-heart url_sweep; route broken links through start-dev, then refresh and publish the evidence." + elif family == "profiling_drift": + text = "Use the profiling skill. Inspect pinned results and the available local results checkout; obtain missing evidence through the profiling workflow, then refresh Heart and publish." + else: + text = (f"Use the health skill to inspect {subject} ({family}) and its source collector. " + "Refresh missing evidence in the required environment; route confirmed defects " + "through bug and start-dev. Report the missing capability if observation is " + "unavailable. Re-assess and publish Heart evidence.") + return {"kind": "prompt", "label": "refresh evidence" if gap else "inspect finding", "payload": text} + + +def expected_repos(): + config = yaml.safe_load((Path(__file__).parents[1] / "config/repos.yaml").read_text()) + return [r["name"] for rows in config["repos"].values() for r in rows] + + +def assess(board, snapshot, *, devbox=None, now=None, repos=None, families=None): + """Return one uncapped inventory used by score, repair and all consumers. + + ``repos``/``families`` let tests exercise small complete universes; production + always uses Heart's complete configured registry. N/A requires an explicit + applicability reason, never merely an absent checkout or measurement. + """ + now = now or dt.datetime.now(dt.timezone.utc) + if now.tzinfo is None: + now = now.replace(tzinfo=dt.timezone.utc) + snapshot = snapshot if isinstance(snapshot, dict) else {} + devbox = devbox if isinstance(devbox, dict) else {} + checks = {} + + def add(family, subject, state, summary, evidence=None, *, source=None, + observed_at=None, action=None, identity=None, na_reason=None): + state = status(state) + parsed = timestamp(observed_at) + max_age = (14 if family in {"verify_install", "validation_report"} else + 7 if "timing" in family or family == "import_time" else 2) * 86400 + fresh = parsed is not None and -300 <= (now - parsed).total_seconds() <= max_age + if na_reason: + state = "na" + elif state in {"green", "na"} and not fresh: + state = "stale" if parsed else "grey" + summary += " — evidence expired" if parsed else " — observation time missing" + identity = identity or f"{family}:{subject}" + item = {"id": identity, "family": family, "subject": subject, + "status": state, "summary": summary, "observed_at": observed_at, + "fresh": fresh, "source": source or f"snapshot.{family}", + "owner": "health" if family == "release" else family, + "applicable": not bool(na_reason), "applicability_reason": na_reason, + "evidence": evidence, "action": action, + "blocked_reason": None} + if state not in {"green", "na"}: + item["action"] = action or remedy(family, subject, state in {"grey", "stale"}) + if state in {"grey", "stale"}: + item["blocked_reason"] = "Fresh evidence required from the named collector and environment." + existing = checks.get(identity) + if existing is None or ORDER[state] < ORDER[existing["status"]]: + checks[identity] = item + + def walk(family, value, path, inherited_ts): + """Read typed child results without scanning history or deriving thresholds.""" + if isinstance(value, list): + for i, row in enumerate(value): + walk(family, row, f"{path}/{i}", inherited_ts) + return + if not isinstance(value, dict): + return + ts = value.get("ts") or value.get("observed_at") or value.get("at") or inherited_ts + if family == "unit_timings": + if value.get("package") and "seconds" in value: + family = "import_time" + elif value.get("nodeid"): + family = "unit_test_timing" + subject = "/".join(str(value[k]) for k in ("repo", "name", "workspace", "project", "workflow", "package", "entry", "nodeid", "test", "file", "check", "python") if value.get(k)) or path + raw = value.get("state", value.get("status")) + if value.get("conclusion"): + raw = value["conclusion"] + if not any(value.get(k) for k in ("repo", "name", "workspace", "project", "workflow", "package", "entry", "nodeid", "test", "file", "check")) and value.get("reason"): + subject = str(value["reason"]) + if value.get("marker") in {"SLOW", "NEEDS_FIX"}: + raw = "yellow" + elif value.get("marker") == "permanent": + raw = "na" + if value.get("error") or value.get("available") is False or value.get("observed") is False: + raw = "grey" + if value.get("ok") is False or value.get("ready") is False: + raw = "red" + if value.get("kind") in {"suspect_cancelled", "timed_out", "timeout", "hang", "kill_timer"}: + raw = "red" + if raw is not None: + summary = str(value.get("reason") or value.get("detail") or value.get("error") or value.get("marker") or raw) + action = value.get("action") + if value.get("prompt"): + action = {"kind": "prompt", "payload": value["prompt"]} + # Semantic identity is stable under row reordering and deduplicates + # the same measurement in rows/slowed/events projections. + discriminator = value.get("run_id") or value.get("run_url") or "" + identity = f"{family}:{subject}:{discriminator}" + add(family, subject, raw, summary, value, source=f"snapshot.{family}:{path}", + observed_at=ts, action=action, identity=identity, + na_reason="Permanent exclusion by design" if value.get("marker") == "permanent" else None) + for key, rows in value.items(): + if key in {"history", "spark", "thresholds", "evidence", "action", "commit_shas"}: + continue + if key in {"red", "yellow", "events", "errors", "findings", "failures", "problems", + "orphans", "orphaned", "missing", "dirty", "canonical_dirty", "packages_unavailable", "repos_unavailable", + "failing_scripts", "parked_stale"} and isinstance(rows, list): + for i, row in enumerate(rows): + row = dict(row) if isinstance(row, dict) else {"reason": str(row)} + row.setdefault("state", "red" if key in {"red", "events", "failures", "dirty", "missing", "failing_scripts"} else + "grey" if key in {"errors", "packages_unavailable", "repos_unavailable"} else "yellow") + walk(family, row, f"{path}/{key}/{i}", ts) + elif isinstance(rows, (list, dict)): + walk(family, rows, f"{path}/{key}", ts) + + section_map = {ALIASES.get(s.key, s.key): s for s in board.sections} + selected = FAMILIES if families is None else families + for family in selected: + sec = section_map.get(family) + data = snapshot.get(family) + # Unit summaries are generated from the unit artifact collector, whose + # timestamp is the evidence timestamp (aggregate time must not refresh it). + ts = (data.get("ts") if isinstance(data, dict) else None) + if family in {"import_time", "unit_test_timing"} and not ts and not (isinstance(data, dict) and "ts" in data): + ts = (snapshot.get("unit_timings") if isinstance(snapshot.get("unit_timings"), dict) else {}).get("ts") + ds = (devbox.get("sections") or {}).get(family) + published = sec is not None and sec.observed_ago and isinstance(ds, dict) + if published: + ts = devbox.get("ts") + label = FAMILIES.get(family, family) + state = status(sec.state) if sec else "grey" + summary = sec.summary if sec else "No observation available" + if isinstance(data, dict) and data and not sec: + if data.get("available") is True and "checks" in data: + state = "green" if all(c.get("ok") for c in data["checks"].values()) and data["checks"] else "grey" + elif data.get("available") is True and "repos" in data: + state = "yellow" if (data.get("drift_count") or data.get("missing_count") or data.get("error_count")) else "green" + elif "workspaces" in data: + state = "green" if data["workspaces"] and all(str(w.get("status")).upper() in {"OK", "SATISFIABLE"} for w in data["workspaces"]) else "grey" + summary = f"{label}: {state}" + if isinstance(data, dict) and (data.get("available") is False or data.get("observed") is False): + state, summary = "grey", str(data.get("reason") or "Collector could not observe this check") + # An INFO state may mean an unfinished baseline; only explicit permanent + # exclusions are inapplicable. No inference from colours alone. + na_reason = None + if family == "no_run_census" and isinstance(data, dict): + totals = data.get("totals") or {} + if totals.get("permanent") and not totals.get("slow") and not totals.get("needs_fix"): + na_reason = "Only permanent exclusions by design; no repairable skips" + if not published and family in {"script_timing", "unit_test_timing", "workspace_testmode_timing"} and isinstance(data, dict): + if not any(data.get(k) for k in ("green_count", "red_count", "yellow_count")): + state, summary = "grey", "No comparisons measured; collect timings and establish baselines" + add(family, label, state, summary, source=f"devbox.sections.{family}" if published else None, + observed_at=ts or (devbox.get("ts") if published else None), + action=sec.action if sec and state not in {"grey", "stale"} else None, + identity=f"{family}:coverage", na_reason=na_reason) + if isinstance(data, dict): + for counter in ("new_scripts_no_baseline", "building_count", "new_tests_no_baseline", "new_packages_no_baseline"): + if data.get(counter): + add(family, counter, "grey", f"{data[counter]} observations lack a baseline comparison", observed_at=ts) + if data.get("orphaned_count", 0) > len(data.get("orphaned") or []): + add(family, "orphaned baseline details", "grey", "Collector omitted orphaned baseline details; refresh the complete collector", observed_at=ts) + if data: + walk(family, data, family, ts) + if published: + stored = ds.get("monitoring_checks") + if isinstance(stored, list): + for item in stored: + if isinstance(item, dict): + add(family, item.get("subject", label), item.get("status"), item.get("summary", ""), + item.get("evidence"), observed_at=item.get("observed_at") or ts, + action=item.get("action"), identity=item.get("id"), source=f"devbox.sections.{family}", na_reason=item.get("applicability_reason")) + else: + add(family, label + " full detail", "grey", "Published summary lacks the complete inventory; republish from the dev box", observed_at=ts) + # Raw unit evidence carries individual rows omitted from legacy summaries. + if isinstance(snapshot.get("unit_timings"), dict) and snapshot["unit_timings"]: + walk("unit_timings", snapshot["unit_timings"], "unit_timings", snapshot["unit_timings"].get("ts")) + + for sec in board.sections: + family = ALIASES.get(sec.key, sec.key) + if family not in selected and not sec.entries: + na = "Only active PR information; no failed checks" if sec.state == "info" and sec.entries and all(e.get("state") in {"ok", "info"} and (e.get("state") == "ok" or e.get("key") == "open_pr") for e in sec.entries) else None + add(family, sec.title, sec.state, sec.summary, observed_at=board.ts, action=sec.action, identity=f"{family}:coverage", na_reason=na) + for entry in sec.entries: + state = entry.get("state") + na = "Open PR is active work, not a failed check" if entry.get("key") == "open_pr" and state == "info" else None + entry_family = {"CI": "ci_status", "local checkout": "repo_state", "GitHub PRs": "open_prs"}.get(entry.get("original_source", entry.get("source")), family) + # Full repo observations below cover these missing local summaries. + if entry.get("key") == "checkout_unobserved": + subject = entry.get("subject") + raw_local = ((snapshot.get("repos") or {}).get(subject) or {}).get("repo_state") or {} + published_local = ((devbox.get("repo_observations") or {}).get(subject) or {}).get("repo_state") or {} + if raw_local.get("branch") or published_local.get("branch"): + continue + add(entry_family, entry.get("subject", sec.title), state, entry.get("reason", ""), entry.get("evidence"), + observed_at=entry.get("observed_at"), action=entry.get("action"), identity=entry.get("id"), na_reason=na) + for name in expected_repos() if repos is None else repos: + data = (snapshot.get("repos") or {}).get(name) or {} + published_repo = (devbox.get("repo_observations") or {}).get(name) or {} + for family in ("ci_status", "repo_state", "open_prs"): + obs = data.get(family) or {} + if family == "repo_state" and not obs.get("branch") and published_repo.get("repo_state"): + obs = published_repo["repo_state"] + observed = isinstance(obs, dict) and bool(obs) and not obs.get("error") + if family == "ci_status": + observed = observed and bool(obs.get("conclusion") or obs.get("status") or obs.get("workflows")) + if family == "repo_state": + observed = observed and bool(obs.get("branch")) + if family == "open_prs": + observed = observed and "open_count" in obs + add(family, name, "green" if observed else "grey", "Observed" if observed else "Observation missing or unavailable", + observed_at=obs.get("ts"), identity=f"{family}:{name}:coverage") + if family == "repo_state" and observed: + for key in ("dirty_real", "behind", "ahead"): + if obs.get(key): + add(family, name + ":" + key, "yellow", f"{key}: {obs[key]}", observed_at=obs.get("ts"), evidence=obs) + if obs.get("branch") != "main": + add(family, name + ":branch", "yellow", "Checkout is not on main", observed_at=obs.get("ts"), evidence=obs) + walk(family, obs, name, obs.get("ts")) + for item in board.blockers: + add("release", item.get("repo") or "Release readiness", item["severity"], item["text"], item, + identity="release:" + hashlib.sha256(item["text"].encode()).hexdigest()[:16], + action={"kind": "prompt", "payload": item["prompt"]} if item.get("prompt") else None, observed_at=board.ts) + if board.verdict != "green" and not board.blockers: + add("release", "Release readiness", board.verdict, "Release verdict requires attention") + if timestamp(board.ts) is None: + add("snapshot", "Heart snapshot", "grey", "Snapshot timestamp missing") + + inventory = sorted(checks.values(), key=lambda c: (ORDER[c["status"]], c["id"])) + findings = [c for c in inventory if c["status"] not in {"green", "na"}] + by_family = {} + for finding in findings: + by_family.setdefault(finding["family"], []).append(finding) + penalties = [{"key": key, "count": len(rows), "weight": max(POINTS[r["status"]] for r in rows), "cap": 10, + "points": max(POINTS[r["status"]] for r in rows)} + for key, rows in sorted(by_family.items())] + return {"schema_version": 1, "status": findings[0]["status"] if findings else "green", + "score": max(0, 100 - sum(p["points"] for p in penalties)), + "complete": not findings, "counts": dict(Counter(c["status"] for c in inventory)), + "checks": inventory, "findings": findings, "penalties": penalties} diff --git a/heart/publish.py b/heart/publish.py index 056471ff..bb59d362 100644 --- a/heart/publish.py +++ b/heart/publish.py @@ -57,6 +57,21 @@ def _scrub(lines: list[str]) -> list[str]: return out +def _public_monitoring(item: dict) -> dict: + """Retain an honest unresolved record when private evidence cannot travel.""" + if _scrub([json.dumps(item, ensure_ascii=False)]): + return item + import hashlib + from heart.monitoring import remedy + identity = hashlib.sha256(item["id"].encode()).hexdigest()[:16] + return {"id": item["family"] + ":private:" + identity, "family": item["family"], + "subject": "Local observation (private details)", "status": item["status"], + "summary": "Inspect full evidence on the dev box; private paths omitted", + "observed_at": item.get("observed_at"), "source": "devbox", + "action": remedy(item["family"], "private local finding"), + "applicability_reason": item.get("applicability_reason")} + + def build_devbox_board(snapshot: dict | None, verdict: dict | None) -> dict[str, Any]: """Distill the LOCAL board's local-only families. Pure; never raises.""" board = dashboard.build_board(snapshot, verdict, unobserved=()) @@ -71,6 +86,11 @@ def build_devbox_board(snapshot: dict | None, verdict: dict | None) -> dict[str, "summary": sec.summary, "details": _scrub(sec.details)[:8], } + if board.monitoring: + sections[sec.key]["monitoring_checks"] = [ + _public_monitoring(item) for item in board.monitoring["checks"] + if item["family"] == sec.key + ] if sec.entries: # Structured observations obey the same public-path boundary as # plain detail lines, including paths inside prompts/evidence. @@ -82,6 +102,13 @@ def build_devbox_board(snapshot: dict | None, verdict: dict | None) -> dict[str, "schema_version": DEVBOX_SCHEMA_VERSION, "ts": (snapshot or {}).get("ts") or "", "sections": sections, + "repo_observations": { + name: {"repo_state": {k: v for k, v in body.get("repo_state", {}).items() + if k in {"ts", "branch", "dirty_real", "dirty_files", "ahead", "behind", "error"} + and _scrub([json.dumps(v)])}} + for name, body in (snapshot or {}).get("repos", {}).items() + if isinstance(body, dict) and isinstance(body.get("repo_state"), dict) + }, } diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 4330ba26..3cb8dd85 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -140,12 +140,13 @@ def test_unify_invariant_verdict_and_score_agree(verdict, score): v = make_verdict(verdict, score, red_reasons=["a blocker"] if verdict == "red" else [], yellow_reasons=["a warning"] if verdict != "green" else []) - seen = set() - for fmt in ("term", "oneline", "md", "json"): + board = dashboard.build_board(snap, v, now=FRESH_NOW) + doc = dashboard.to_dict(board) + assert doc["verdict"] == verdict and doc["score"] == score + for fmt in ("term", "oneline", "md", "html"): out = dashboard.render(snap, v, fmt=fmt, now=FRESH_NOW) - seen.add(_extract(out, fmt)) - # All surfaces must extract to exactly one (verdict-word, score) pair. - assert seen == {(dashboard._VERDICT_WORD[verdict], score)} + assert str(board.monitoring["score"]) in out + assert dashboard._VERDICT_WORD[verdict] in out # --- staleness path ---------------------------------------------------------- @@ -334,7 +335,7 @@ def test_badge_endpoint_colour(verdict, color): b = dashboard.badge_endpoint(board) assert b["schemaVersion"] == 1 assert b["label"] == "health" - assert b["color"] == color + assert b["color"] == dashboard._BADGE_COLOR.get(board.monitoring["status"], "lightgrey") assert dashboard._VERDICT_WORD[verdict] in b["message"] @@ -1735,7 +1736,8 @@ def test_to_state_green_board(): _assert_valid_state(doc) assert doc["status"] == "green" assert doc["updated"] == "2026-06-01T00:00:00Z" - assert "100" in doc["headline"] and doc["items"] == [] + assert "Release GREEN; monitoring" in doc["headline"] + assert doc["items"] # this fixture lacks complete monitoring evidence def test_to_state_red_items_carry_url_and_prompt(): @@ -1747,7 +1749,7 @@ def test_to_state_red_items_carry_url_and_prompt(): doc = dashboard.to_state(dashboard.build_board(snap, v, now=FRESH_NOW)) _assert_valid_state(doc) assert doc["status"] == "red" - assert doc["headline"].startswith("PyAutoFit: CI failure") + assert doc["headline"].startswith("Release RED; monitoring RED") red = [i for i in doc["items"] if i["severity"] == "red"] assert red and red[0]["url"].endswith("/actions/runs/1") assert red[0]["prompt"].startswith("Use the bug skill.") @@ -1760,8 +1762,8 @@ def test_to_state_stale_reasons_become_info_items(): doc = dashboard.to_state(dashboard.build_board(make_snapshot(), v, now=FRESH_NOW)) _assert_valid_state(doc) assert doc["status"] == "stale" - assert doc["headline"] == "release validation: evidence expired" - assert [i["severity"] for i in doc["items"]] == ["info"] + assert doc["headline"].startswith("Release STALE; monitoring STALE") + assert any(i["text"] == "release validation: evidence expired" and i["severity"] == "info" for i in doc["items"]) def test_to_state_naive_and_microsecond_ts_normalise_to_z(): diff --git a/tests/test_dashboard_disclosures.py b/tests/test_dashboard_disclosures.py index 2c803c65..51e0f574 100644 --- a/tests/test_dashboard_disclosures.py +++ b/tests/test_dashboard_disclosures.py @@ -107,7 +107,7 @@ def test_timing_cards_are_inside_category_and_checks_precede_score_actions_gaps( assert list(timing.find(cls='timing-card')) assert all('timing-card' not in n.attrs.get('class', '') for c in checks for n in next(c.find('summary')).find()) - assert (html.index('
    ') < html.index('Why this score:') < + assert (html.index('
    ') < html.index('Release readiness score:') < html.index('Fix Heart systematically') < html.index('Evidence gaps (')) assert '[these guys are giving me life]' not in html @@ -136,7 +136,7 @@ def test_score_and_resusitate_sections_keep_breakdown_and_readiness(): score = next(s for s in root.find('section') if s.attrs.get('aria-labelledby') == 'score-heading') assert '65/100' in score.text() and 'Release readiness: STALE' in score.text() - assert 'Why this score: 65/100' in score.text() + assert 'Release readiness score: 65/100' in score.text() assert 'Missing workspace test report: −10 (1 × 10, cap 10)' in score.text() assert 'Missing install verification: −10 (1 × 10, cap 10)' in score.text() assert 'Missing release validation: −15 (1 × 15, cap 15)' in score.text() diff --git a/tests/test_dashboard_reasons.py b/tests/test_dashboard_reasons.py index 190bad5f..232607e7 100644 --- a/tests/test_dashboard_reasons.py +++ b/tests/test_dashboard_reasons.py @@ -94,7 +94,7 @@ def test_score_breakdown_reproduces_caps_and_floor(): assert penalties["lib_behind"] == {"key": "lib_behind", "count": 5, "weight": 20, "cap": 40, "points": 40} assert v["score"] == max(0, 100-sum(p["points"] for p in v["penalties"])) == 0 html = dashboard.render({"ts": TS, "repos": repos}, v, fmt="html", now=NOW) - assert "Why this score: 0/100" in html and "floor of 0" in html + assert "Release readiness score: 0/100" in html and "floor of 0" in html assert "Library checkout behind origin" in html diff --git a/tests/test_monitoring.py b/tests/test_monitoring.py new file mode 100644 index 00000000..c8a16578 --- /dev/null +++ b/tests/test_monitoring.py @@ -0,0 +1,175 @@ +"""Monitoring and repair must account for the same complete evidence set.""" +import datetime as dt +from types import SimpleNamespace + +import pytest + +from heart import dashboard, monitoring, readiness + +TS = "2026-10-02T10:00:00+00:00" +NOW = dt.datetime.fromisoformat(TS) + + +def board(sections=(), **kw): + return SimpleNamespace(ts=TS, sections=list(sections), verdict="green", blockers=[], **kw) + + +def assess(b, s, families=(), repos=()): + return monitoring.assess(b, s, now=NOW, families=families, repos=repos) + + +def test_fresh_green_complete_inventory_scores_100(): + sec = dashboard.Section("script_timing", "Scripts", "ok", "1 compared") + m = assess(board([sec]), {"script_timing": {"ts": TS, "green_count": 1}}, families=["script_timing"]) + assert m["score"] == 100 and m["complete"] and m["status"] == "green" + assert not m["findings"] + + +@pytest.mark.parametrize("state", ["warn", "fail", "unobserved", "info"]) +def test_every_non_green_section_prevents_100(state): + sec = dashboard.Section("custom", "Custom check", state, "Inspect") + m = assess(board([sec]), {}) + assert m["score"] < 100 and not m["complete"] + assert all(c["action"]["payload"] for c in m["findings"]) + + +def test_expected_missing_check_and_missing_repository_are_not_success(): + m = assess(board(), {}, families=["url_check"], repos=["Example"]) + assert {c["family"] for c in m["findings"]} == {"url_check", "ci_status", "repo_state", "open_prs"} + assert all(c["status"] == "grey" for c in m["findings"]) + + +def test_aggregate_timestamp_does_not_rejuvenate_old_sidecar(): + sec = dashboard.Section("script_timing", "Scripts", "ok", "1 compared") + m = assess(board([sec]), {"script_timing": {"ts": "2026-09-01T00:00:00Z", "green_count": 1}}, families=["script_timing"]) + assert m["findings"][0]["status"] == "stale" + assert m["score"] < 100 + + +def test_adverse_old_evidence_remains_adverse(): + sec = dashboard.Section("script_timing", "Scripts", "fail", "regression") + m = assess(board([sec]), {"script_timing": {"ts": "2026-09-01T00:00:00Z", "red_count": 1}}, families=["script_timing"]) + assert m["status"] == "red" + + +def test_zero_compared_tests_is_evidence_gap(): + sec = dashboard.Section("unit_test_timing", "Tests", "ok", "0 tracked tests within baseline") + m = assess(board([sec]), {"unit_test_timing": {"repos_measured": 5, "green_count": 0}}, families=["unit_test_timing"]) + assert m["findings"][0]["status"] == "grey" + + +def test_permanent_exclusions_are_explicitly_inapplicable(): + sec = dashboard.Section("no_run_census", "Skips", "info", "Permanent exclusions") + m = assess(board([sec]), {"no_run_census": {"ts": TS, "totals": {"permanent": 3}, "rows": []}}, families=["no_run_census"]) + assert m["complete"] and m["score"] == 100 + assert m["checks"][0]["applicability_reason"] + assert m["checks"][0]["applicable"] is False + + +def test_full_skip_rows_beyond_display_limit_and_stable_ids(): + rows = [{"repo": "Example", "entry": f"script{i}.py", "marker": "NEEDS_FIX", "prompt": f"Repair script {i}"} for i in range(30)] + s = {"no_run_census": {"ts": TS, "rows": rows}} + first = assess(board(), s, families=["no_run_census"]) + s["no_run_census"]["rows"] = list(reversed(rows)) + second = assess(board(), s, families=["no_run_census"]) + assert {c["id"] for c in first["findings"]} == {c["id"] for c in second["findings"]} + assert any(c["action"]["payload"] == "Repair script 29" for c in first["findings"]) + + +def test_nested_non_gating_workflow_failure_is_not_hidden_by_rollup(): + obs = {"ts": TS, "status": "completed", "conclusion": "success", + "workflows": {"Optional": {"status": "completed", "conclusion": "failure"}}} + m = assess(board(), {"repos": {"Example": {"ci_status": obs}}}, repos=["Example"]) + assert any(c["status"] == "red" and "Optional" in c["subject"] for c in m["findings"]) + assert not any(c["status"] == "grey" and c["family"] == "ci_status" for c in m["findings"]) + + +def test_monitoring_does_not_change_release_gate_and_prompt_uses_complete_scope(): + s = {"ts": TS, "ci_timing": {"ts": TS, "events": [{"repo": "Example", "kind": "suspect_cancelled"}]}} + before = readiness.compute(s) + b = dashboard.build_board(s, {"verdict": "green", "score": 100}, now=NOW) + assert b.score == 100 and b.verdict == "green" + assert b.monitoring["score"] < 100 and b.monitoring["status"] == "red" + assert readiness.compute(s) == before + assert "--scope dashboard" in b.fix_plan["prompt"] + assert "monitoring.complete" in b.fix_plan["prompt"] + assert len(b.fix_plan["prompt"]) < 45000 + doc = dashboard.to_dict(b) + assert doc["monitoring"]["findings"] == b.monitoring["findings"] + assert "Monitoring RED" in dashboard.badge_endpoint(b)["message"] + assert dashboard.to_state(b)["status"] == "green" # release gate feed compatibility + assert "monitoring RED" in dashboard.to_state(b)["headline"] + + +def test_published_local_inventory_preserves_individual_findings(): + sec = dashboard.Section("worktree_drift", "Drift", "fail", "dirty", observed_ago="observed just now") + item = {"id": "drift:task30", "subject": "task30", "status": "red", "summary": "dirty", "observed_at": TS} + m = monitoring.assess(board([sec]), {}, devbox={"ts": TS, "sections": {"worktree_drift": {"monitoring_checks": [item]}}}, now=NOW, families=["worktree_drift"], repos=[]) + assert any(c["id"] == "drift:task30" for c in m["findings"]) + + +@pytest.mark.parametrize("family,counter", [("script_timing", "new_scripts_no_baseline"), ("script_timing", "building_count"), ("unit_test_timing", "new_tests_no_baseline"), ("import_time", "new_packages_no_baseline")]) +def test_partial_comparison_coverage_cannot_earn_100(family, counter): + sec = dashboard.Section(family, "Timing", "ok", "one green") + m = assess(board([sec]), {family: {"ts": TS, "green_count": 1, counter: 20}}, families=[family]) + assert not m["complete"] and m["score"] < 100 + assert any(c["subject"] == counter for c in m["findings"]) + + +def test_undated_observation_is_not_refreshed_by_aggregate(): + sec = dashboard.Section("script_timing", "Scripts", "ok", "1 compared") + m = assess(board([sec]), {"ts": TS, "script_timing": {"green_count": 1}}, families=["script_timing"]) + assert m["findings"][0]["status"] == "grey" + assert m["findings"][0]["observed_at"] is None + + +def test_raw_local_repo_observations_close_cloud_gaps(): + obs = {"ts": TS, "branch": "main", "dirty_real": 0, "ahead": 0, "behind": 0} + snapshot = {"repos": {"Example": {"ci_status": {"ts": TS, "conclusion": "success"}, "open_prs": {"ts": TS, "open_count": 0}}}} + m = monitoring.assess(board(), snapshot, devbox={"ts": TS, "repo_observations": {"Example": {"repo_state": obs}}}, now=NOW, families=[], repos=["Example"]) + assert m["complete"] and m["score"] == 100 + obs["behind"] = 2 + m = monitoring.assess(board(), snapshot, devbox={"ts": TS, "repo_observations": {"Example": {"repo_state": obs}}}, now=NOW, families=[], repos=["Example"]) + assert not m["complete"] + + +def test_legacy_green_devbox_summary_requires_complete_evidence(): + sec = dashboard.Section("script_timing", "Timing", "ok", "one green", observed_ago="just now") + m = monitoring.assess(board([sec]), {}, devbox={"ts": TS, "sections": {"script_timing": {"state": "ok"}}}, now=NOW, families=["script_timing"], repos=[]) + assert any("complete inventory" in c["summary"] for c in m["findings"]) + + +def test_private_findings_survive_publication_without_private_paths(): + from heart.publish import _public_monitoring + item = {"id": "worktree_drift:/home/private/tree", "family": "worktree_drift", "status": "red", "subject": "/home/private/tree", "observed_at": TS} + public = _public_monitoring(item) + assert public["status"] == "red" + assert "/home/private" not in str(public) + assert public["action"]["payload"] + + +def test_orphaned_baselines_are_not_lost_and_family_is_charged_once(): + sec = dashboard.Section("script_timing", "Timing", "ok", "one green") + data = {"ts": TS, "green_count": 1, "orphaned_count": 2, "orphaned": [{"reason": "old baseline one"}, {"reason": "old baseline two"}]} + m = assess(board([sec]), {"script_timing": data}, families=["script_timing"]) + assert len([c for c in m["findings"] if "old baseline" in c["summary"]]) == 2 + assert m["score"] == 95 + + +def test_fresh_published_complete_timing_survives_empty_cloud_slice(): + sec = dashboard.Section("script_timing", "Scripts", "ok", "all compared", observed_ago="just now") + item = {"id": "script_timing:coverage", "subject": "Scripts", "status": "green", "summary": "all compared", "observed_at": TS} + m = monitoring.assess(board([sec]), {"script_timing": {}}, devbox={"ts": TS, "sections": {"script_timing": {"monitoring_checks": [item]}}}, now=NOW, families=["script_timing"], repos=[]) + assert m["complete"] and m["score"] == 100 + + +def test_source_run_timestamp_survives_reaggregation(tmp_path): + import json + import os + from heart.checks import script_timing + path = tmp_path / "example__script.json" + path.write_text(json.dumps({"project": "Example", "directory": "scripts", "results": [{"status": "passed", "file": "x.py", "duration_seconds": 2}]})) + old = dt.datetime(2026, 9, 1, tzinfo=dt.timezone.utc).timestamp() + os.utime(path, (old, old)) + rows = script_timing.scan_latest_results(tmp_path) + assert rows[0]["observed_at"].startswith("2026-09-01") diff --git a/tests/test_unit_timings.py b/tests/test_unit_timings.py index 02613eeb..39722c39 100644 --- a/tests/test_unit_timings.py +++ b/tests/test_unit_timings.py @@ -486,10 +486,10 @@ def test_aggregate_survives_garbage_sidecars(): # They are the WHOLE point of the ingest: the board's existing sections read # these two files, so the shapes have to match key for key. -LEGACY_UNIT_KEYS = {"python", "repos_measured", "repos_unavailable", +LEGACY_UNIT_KEYS = {"ts", "python", "repos_measured", "repos_unavailable", "new_tests_no_baseline", "red_count", "yellow_count", "green_count", "red", "yellow"} -LEGACY_IMPORT_KEYS = {"python", "packages_measured", "packages_unavailable", +LEGACY_IMPORT_KEYS = {"ts", "python", "packages_measured", "packages_unavailable", "new_packages_no_baseline", "red_count", "yellow_count", "green_count", "red", "yellow"} diff --git a/tests/test_version_skew.py b/tests/test_version_skew.py index f07a8c2d..d09eaa69 100644 --- a/tests/test_version_skew.py +++ b/tests/test_version_skew.py @@ -209,7 +209,8 @@ def test_main_persists_result_to_state_dir(monkeypatch): monkeypatch.setattr(vs, "run", lambda root=vs.PYAUTO_ROOT: {"workspaces": []}) assert vs.main(["version_skew"]) == 0 written = json.loads((Path(os.environ["HEART_STATE_DIR"]) / "version_skew.json").read_text()) - assert written == {"workspaces": []} + assert written["workspaces"] == [] + assert written["ts"] def test_main_pypi_persists_to_sibling_file(monkeypatch):