"""Check a pipeline session JSON (measurements only) before it reaches the coach. For the ML/pipeline engineer: run `python -m ai_coach.validate session.json` on real pipeline output. It lists everything that would make the coach wrong, silent or misleading (errors) or weaker (warnings), using the same rules the coach relies on. Contract: docs/AGENT_INPUT_SPEC.md (v2, measurements only). """ from __future__ import annotations import argparse import json import math import sys from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path from typing import Any from . import knowledge as kb from .input_builder import IGNORED_PIPELINE_KEYS, InputError, build_coach_input from .timing import parse_timing CONFIDENCES = {"high", "medium", "est"} MIN_REPS_FOR_STABLE_RESULT = 3 HIGH_FPS = 120.0 FORBIDDEN_KEYS = ("zone", "band", "ref", "keypoints", "kp", "video", "frames") @dataclass(frozen=True) class Issue: level: str # "error" | "warning" code: str detail: str def __str__(self) -> str: return f"[{self.level}] {self.code}: {self.detail}" def _bounds() -> dict: return kb._load("bounds.yaml") def validate_session(session: Mapping[str, Any]) -> list[Issue]: """All issues found. No error-level issues means the coach can use the session.""" issues: list[Issue] = [] def error(code: str, detail: str) -> None: issues.append(Issue("error", code, detail)) def warn(code: str, detail: str) -> None: issues.append(Issue("warning", code, detail)) discipline = session.get("discipline") if discipline not in ("hitting", "pitching"): error("discipline", f"must be 'hitting' or 'pitching', got {discipline!r}") return issues for key in ("reps", "capture"): if key not in session and not (isinstance(session.get("session"), Mapping) and key in session["session"]): error("missing_field", f"top-level {key!r} is required") if issues: return issues block = session.get("session") if isinstance(session.get("session"), Mapping) else {} if block: warn( "old_format", "metrics wrapped in a 'session' block (contract v1); send v2: capture and arm_care at the top level", ) ignored = sorted({k for k in IGNORED_PIPELINE_KEYS if k in session or k in block}) if ignored: warn("ignored_fields", f"{ignored} are ignored: the agent decides problems, priority fix and drills itself") if not session.get("level"): warn("level_missing", "'level' (hs_jv | hs_varsity | college) is missing: hs_varsity ranges will be assumed") elif session["level"] not in kb.LEVELS: error("level", f"level must be one of {kb.LEVELS}, got {session['level']!r}") fps = session.get("fps") if not isinstance(fps, int | float) or fps <= 0: error("fps", f"fps must be the real capture rate (a positive number), got {fps!r}") elif fps < HIGH_FPS: warn("low_fps", f"{fps:g} fps: timing metrics are unreliable below {HIGH_FPS:g} fps") capture = session.get("capture") or block.get("capture") if not isinstance(capture, Mapping) or "ok" not in capture: error("capture", "capture.ok is required") else: known = set(_bounds()["capture_reasons"]) for reason in capture.get("reasons", []): if reason not in known: warn("unknown_capture_reason", f"{reason!r}: the coach has no caveat wording for it") if not capture["ok"] and not capture.get("reasons"): warn("capture_without_reason", "capture.ok is false but no reasons are given") reps = session["reps"] if len(reps) < MIN_REPS_FOR_STABLE_RESULT: warn("few_reps", f"{len(reps)} rep(s): results are unstable below {MIN_REPS_FOR_STABLE_RESULT}") limits, order = _bounds()[discipline], _bounds()["event_order"][discipline] for rep in reps: _check_rep(rep, rep.get("rep", "?"), discipline, limits, order, error, warn) if session.get("timing") is not None: try: parse_timing(session["timing"]) except InputError as exc: error("timing", str(exc)) try: build_coach_input(session) except (InputError, ValueError, KeyError, TypeError) as exc: error("cannot_build_input", str(exc)[:200]) return issues def _check_rep(rep, rid, discipline, limits, order, error, warn) -> None: events = rep.get("events_ms", {}) times = [events[e] for e in order if e in events] if times != sorted(times): error("event_order", f"rep {rid}: events out of order {events}") unknown_events = set(events) - set(order) if unknown_events: warn("unknown_event", f"rep {rid}: {sorted(unknown_events)} are not part of the {discipline} event list") for bad in FORBIDDEN_KEYS: if bad in rep: warn("ignored_fields", f"rep {rid}: {bad!r} is ignored") for m in rep.get("metrics", []): key = m.get("key") if key not in kb.metric_keys(discipline): warn("unknown_metric", f"rep {rid}: {key!r} is not in the metric list for {discipline}") for bad in ("ref", "zone", "band"): if bad in m: warn("ignored_fields", f"rep {rid} {key}: {bad!r} is ignored (the agent owns the typical ranges)") if m.get("confidence") not in CONFIDENCES: error("confidence", f"rep {rid} {key}: confidence must be high|medium|est, got {m.get('confidence')!r}") value = m.get("value") if value is None: if not m.get("note"): warn("null_without_note", f"rep {rid} {key}: null value should carry a note saying why") continue if not isinstance(value, int | float) or isinstance(value, bool) or not math.isfinite(value): error("value", f"rep {rid} {key}: value must be a finite number, got {value!r}") elif key in limits and not limits[key][0] <= value <= limits[key][1]: error("out_of_bounds", f"rep {rid} {key}={value:g} is outside the plausible range {limits[key]}") def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="ai-coach-validate", description="Validate a measurements session JSON") parser.add_argument("session", type=Path) parser.add_argument("--strict", action="store_true", help="treat warnings as failures") args = parser.parse_args(argv) issues = validate_session(json.loads(args.session.read_text(encoding="utf-8"))) for issue in issues: print(issue) errors = sum(i.level == "error" for i in issues) warnings = len(issues) - errors print(f"{errors} error(s), {warnings} warning(s)", file=sys.stderr) return 1 if errors or (args.strict and warnings) else 0 if __name__ == "__main__": raise SystemExit(main())