File size: 16,227 Bytes
66d2e51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
"""Validate saved ML trajectories -> current pitching coach, without another pose run.

Example (offline, no provider requests):
  .venv-product/bin/python tools/validate_pitching_ml_coach.py \
    --source-run artifacts/pitching-validation-2026-11-02/release-1.21.4 \
    --video-dir /path/to/original/videos --output /path/to/new/audit

Add --live [--env-file /private/path/.env] for real text-only coaching generation.
Old artifacts are read-only. Output must be a new directory outside the source run.
This checks reproducibility and evidence handling, not physical pose accuracy.
"""

import argparse
import hashlib
import json
import math
import sqlite3
import sys
import tempfile
from datetime import UTC, datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "AI-coach-agent" / "src"))


class AuditError(ValueError):
    """An explicitly diagnosed audit failure safe to print without credentials."""


def digest(path):
    h = hashlib.sha256()
    with Path(path).open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            h.update(block)
    return h.hexdigest()


def verify_file(path, expected_hash, expected_size=None):
    path = Path(path)
    if not path.is_file():
        raise AuditError(f"Required source file is missing: {path.name}")
    if not expected_hash or digest(path) != expected_hash:
        raise AuditError(f"Source checksum mismatch: {path.name}")
    if expected_size is not None and path.stat().st_size != expected_size:
        raise AuditError(f"Source size mismatch: {path.name}")


def check_output(source_run, output):
    source_run, output = Path(source_run).resolve(), Path(output).resolve()
    if output.exists():
        raise AuditError(
            "Output already exists; choose a new directory to preserve evidence."
        )
    if (
        output == source_run
        or source_run in output.parents
        or output in source_run.parents
    ):
        raise AuditError("Output must be outside the source evidence directory.")


def save(path, value):
    path.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")


def compare_measurements(old, new):
    """Permit stricter abstention, never new values or silently changed geometry."""
    before = {m["metric_id"]: m for m in old["measurements"]}
    after = {m["metric_id"]: m for m in new["measurements"]}
    if before.keys() != after.keys():
        raise AuditError(
            "Scalar measurement definitions changed; review the source run."
        )
    withheld, max_interval_difference = [], 0.0
    for key, current in after.items():
        prior = before[key]
        if current["value"] is None and prior["value"] is not None:
            if current["status"] != "unavailable" or not current["reasons"]:
                raise AuditError(f"Withheld measurement lacks a reason: {key}")
            withheld.append(key)
            continue
        if prior["value"] != current["value"]:
            raise AuditError(
                f"Scalar changed or previously unavailable value became available: {key}"
            )
        for field in (
            "group",
            "unit",
            "reference",
            "event_ids",
            "status",
            "uses_interpolated_input",
        ):
            if prior[field] != current[field]:
                raise AuditError(f"Scalar semantics changed: {key}.{field}")
        a, b = prior["value_interval"], current["value_interval"]
        if (a is None) != (b is None):
            raise AuditError(f"Scalar interval availability changed: {key}")
        if a is not None:
            for bound in ("lower", "upper"):
                delta = abs(a[bound] - b[bound])
                max_interval_difference = max(delta, max_interval_difference)
                if not math.isclose(a[bound], b[bound], rel_tol=1e-10, abs_tol=1e-9):
                    raise AuditError(
                        f"Scalar interval changed beyond floating-point tolerance: {key}"
                    )
    return {
        "rounded_values_preserved_or_withheld": True,
        "newly_withheld": withheld,
        "maximum_interval_roundtrip_difference": max_interval_difference,
    }


def prepare_clip(directory, video_dir):
    from baseball_batting.ingest import iter_frames
    from baseball_batting.motion_export import reproduce_measurements

    manifest = json.loads((directory / "manifest.json").read_text())
    video = video_dir / (directory.name + ".mp4")
    verify_file(video, manifest["source_video"]["sha256"])
    checked = {}
    for key in ("motion", "coach_payload"):
        asset = manifest["artifacts"][key]
        filename = asset.get("filename")
        if (
            asset["status"] != "available"
            or not filename
            or Path(filename).name != filename
        ):
            raise AuditError(f"Required saved artifact unavailable or invalid: {key}")
        path = directory / filename
        verify_file(path, asset["sha256"], asset["size_bytes"])
        checked[key] = {"sha256": asset["sha256"], "size_bytes": path.stat().st_size}
    frames = sum(1 for _ in iter_frames(video))
    old = json.loads(
        (directory / manifest["artifacts"]["coach_payload"]["filename"]).read_text()
    )
    current = reproduce_measurements(
        manifest, directory / manifest["artifacts"]["motion"]["filename"]
    )
    if current is None:
        raise AuditError("Source has no pitching athlete/payload.")
    payload = current.model_dump(mode="json")
    if frames != payload["delivery_evidence"]["source_frame_count"]:
        raise AuditError(
            f"Original decoded frame count differs from ML evidence: {directory.name}"
        )
    for field in (
        "analysis_id",
        "analysis_revision",
        "pitch_id",
        "events",
        "athlete",
        "context",
    ):
        if payload[field] != old[field]:
            raise AuditError(
                f"Replayed identity, context or event changed: {directory.name}.{field}"
            )
    if payload.get("visual_evidence") is not None:
        raise AuditError(
            "Replay must contain ML evidence only; visual evidence was present."
        )
    scalar_replay = compare_measurements(old, payload)
    return current, {
        "source_sha256": digest(video),
        "decoded_frames": frames,
        "source_manifest_sha256": digest(directory / "manifest.json"),
        "artifact_hashes_verified": checked,
        "source_analysis_id": manifest["analysis_id"],
        "source_analysis_revision": manifest["analysis_revision"],
        "original_video_identity_verified": True,
        "events_and_athlete_preserved": True,
        "scalar_replay": scalar_replay,
        "saved_calculation_hashes": manifest["pipeline"]["coach_payload"],
    }


def verify_report(payload, report, facts, live):
    from ai_coach.pitch_report.v1_1.coaching import Draft, check_draft
    from ai_coach.pitch_report.v1_1.schemas import PitchReport

    PitchReport.model_validate(report)
    checks = {
        "ml_only_payload": payload.get("visual_evidence") is None,
        "ml_only_report": report.get("visual_evidence") is None,
        "ml_only_facts": not any(k.startswith("visual:") for k in facts),
        "ml_only_coaching": report["coaching"]["evidence_mode"]
        == "ml_measurements_and_motion",
        "numerical_scores_withheld": report["overall_score"] is None
        and all(g["score"] is None for g in report["groups"])
        and all(m["score"] is None for m in report["measurements"]),
        "drill_score_withheld": report["drill_evaluation"]["score"] is None,
        "no_invented_corrective_drill": report["focus_area"]["drill"] is None,
        "report_analysis_identity_preserved": all(
            report[k] == payload[k] for k in ("analysis_id", "analysis_revision")
        ),
    }
    supplied = {m["metric_id"]: m for m in payload["measurements"]}
    returned = {m["metric_id"]: m for m in report["measurements"]}
    checks["report_scalar_values_preserved_or_withheld"] = (
        supplied.keys() == returned.keys()
        and all(
            m["value"] == supplied[key]["value"]
            or (m["value"] is None and m["status"] == "unavailable")
            for key, m in returned.items()
        )
    )
    evidence = payload["delivery_evidence"]
    if not evidence["clock"]["physical_time_available"]:
        checks["unknown_capture_clock_preserved"] = (
            all(e["capture_time_s"] is None for e in payload["events"].values())
            and all(
                m["value"] is None for m in payload["measurements"] if m["unit"] == "ms"
            )
            and all(p["duration_ms"] is None for p in evidence["phases"])
            and evidence["sequencing"]["status"] == "unavailable"
            and evidence["clock"]["median_capture_fps"] is None
        )
    coaching = report["coaching"]
    if coaching["status"] == "generated":
        draft = Draft.model_validate({k: coaching[k] for k in ("summary", "cards")})
        checks["coaching_passes_current_evidence_guards"] = not check_draft(
            draft, facts
        )
        checks["coaching_is_actual_live_generation"] = (
            live and report["meta"]["text_source"] == "llm"
        )
    else:
        checks["expected_coaching_mode"] = (
            not live and coaching["reason"] == "llm_not_configured"
        )
    return checks


def run(source_run, video_dir, output, *, live=False, env_file=None):
    from ai_coach.config import Settings
    from ai_coach.pitch_report.v1_1.coaching import facts_for
    from ai_coach.pitch_report.v1_1.rubric import evaluate_drill
    from ai_coach.pitch_report.v1_1.service import build_report

    source_run, video_dir, output = (
        Path(p).resolve() for p in (source_run, video_dir, output)
    )
    check_output(source_run, output)
    if not source_run.is_dir():
        raise AuditError("Source run directory does not exist.")
    directories = (
        [source_run]
        if (source_run / "manifest.json").is_file()
        else sorted(
            p
            for p in source_run.iterdir()
            if p.is_dir() and (p / "manifest.json").is_file()
        )
    )
    if not directories:
        raise AuditError("No saved clip manifests found in source run.")
    # Explicit offline override prevents an ambient GOOGLE_API_KEY causing provider requests.
    settings = Settings(_env_file=env_file if live else None)
    settings = settings.model_copy(
        update={
            "cache_enabled": False,
            "tracing": False,
            **({} if live else {"google_api_key": None}),
        }
    )
    if live and not settings.llm_enabled:
        raise AuditError(
            "Live coaching requires GOOGLE_API_KEY in the environment or --env-file."
        )
    prepared = [
        (directory.name, *prepare_clip(directory, video_dir))
        for directory in directories
    ]
    output.mkdir(parents=True, exist_ok=False)
    paths = [
        "baseball_batting/pitching_coach.py",
        "baseball_batting/pitching_geometry.py",
        "baseball_batting/pitching_sequence.py",
        "baseball_batting/motion_export.py",
        "AI-coach-agent/src/ai_coach/pitch_report/v1_1/coaching.py",
        "AI-coach-agent/src/ai_coach/pitch_report/v1_1/service.py",
        "AI-coach-agent/src/ai_coach/pitch_report/v1_1/contract.py",
        "AI-coach-agent/src/ai_coach/pitch_report/v1_1/evidence.py",
        "tools/validate_pitching_ml_coach.py",
    ]
    summary = {
        "created_at": datetime.now(UTC).isoformat(),
        "mode": "live_text_coach" if live else "offline_rules",
        "new_pose_inference": False,
        "production_writes": False,
        "physical_accuracy_validated": False,
        "current_source_sha256": {name: digest(ROOT / name) for name in paths},
        "clips": {},
        "limitations": [
            "Saved ML trajectories were recomputed, not rerun through the pose model.",
            "Reproducibility and software guards do not establish physical measurement accuracy.",
            "Automated coaching critique does not replace independent expert review.",
        ],
    }
    # Provider caches, logs and billing ledger stay private and outside the public evidence directory.
    with tempfile.TemporaryDirectory(prefix="pitching-ml-coach-") as private:
        settings = settings.model_copy(
            update={
                "cache_path": Path(private) / "responses.sqlite3",
                "ledger_path": Path(private) / "spend.sqlite3",
                "log_dir": Path(private) / "logs",
            }
        )
        for tag, p, verification in prepared:
            directory = output / tag
            directory.mkdir()
            payload = p.model_dump(mode="json")
            facts = facts_for(p, evaluate_drill(p))
            save(directory / "coach-payload.json", payload)
            save(directory / "coach-facts.json", facts)
            report = build_report(payload, settings=settings)
            save(directory / "report.json", report)
            checks = verify_report(payload, report, facts, live)
            verification.update(
                mode=summary["mode"],
                new_pose_inference=False,
                checks=checks,
                passed=all(checks.values()),
                coaching_status=report["coaching"]["status"],
                coaching_reason=report["coaching"]["reason"],
                coaching_model=report["meta"]["model"],
                prompt_version=report["meta"]["prompt_version"],
            )
            save(directory / "verification.json", verification)
            summary["clips"][tag] = {
                "passed": verification["passed"],
                "checks": checks,
                "coaching_status": verification["coaching_status"],
                "coaching_reason": verification["coaching_reason"],
            }
            print(json.dumps({"clip": tag, **summary["clips"][tag]}), flush=True)
        if settings.resolved_ledger_path.is_file():
            with sqlite3.connect(settings.resolved_ledger_path) as db:
                calls, cost = db.execute(
                    "SELECT COUNT(*), COALESCE(SUM(cost_usd), 0) FROM calls"
                ).fetchone()
            summary["provider_calls"] = calls
            summary["provider_cost_usd"] = cost
        else:
            summary.update(provider_calls=0, provider_cost_usd=0.0)
    summary["passed"] = all(c["passed"] for c in summary["clips"].values())
    if live and summary["provider_calls"] == 0:
        summary["passed"] = False
    save(output / "verification.json", summary)
    return summary


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source-run", type=Path, required=True)
    parser.add_argument("--video-dir", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--live", action="store_true")
    parser.add_argument("--env-file", type=Path)
    args = parser.parse_args()
    try:
        result = run(
            args.source_run,
            args.video_dir,
            args.output,
            live=args.live,
            env_file=args.env_file,
        )
    except AuditError as error:
        parser.exit(1, f"Validation failed: {error}\n")
    except (
        OSError,
        ValueError,
        TypeError,
        KeyError,
        ImportError,
        RuntimeError,
    ) as error:
        # Do not print provider/configuration exception contents, which may contain secrets.
        parser.exit(
            1,
            f"Validation failed ({type(error).__name__}); check source schema and local dependencies.\n",
        )
    print(
        json.dumps(
            {
                "passed": result["passed"],
                "mode": result["mode"],
                "provider_calls": result["provider_calls"],
                "output": str(args.output.resolve()),
            }
        )
    )
    return 0 if result["passed"] else 1


if __name__ == "__main__":
    raise SystemExit(main())