File size: 91,035 Bytes
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be69d1e
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
"""End-to-end QA: coaching workflow + academy (spec 11.3 acceptance tests, journeys 2.2 / 2.3, endpoints N01-N50, C01-C08).

Run from backend/:  BASE_URL=http://127.0.0.1:8000 .venv/bin/python e2e/qa_coaching_workflow.py
BASE_URL defaults to http://127.0.0.1:8000. Creates qa-cw-<runid>-<n>@example.com accounts and deletes them at the end
(DELETE /v1/me). Exit code 1 if any check fails.

Needs a server with working object storage (presigned PUT/GET). Settings assumed: default consent policy
(analysis consent is only enforced for accounts that withdrew it).
"""

import copy
import csv
import io
import json
import os
import sys
import time
import uuid
from datetime import date, datetime, timedelta, timezone

import httpx

BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8000").rstrip("/")
RUN_ID = uuid.uuid4().hex[:8]
PASSWORD = "QaCoach!2345"

client = httpx.Client(base_url=BASE_URL, timeout=60)
results = {"pass": 0, "fail": 0}
failures: list[str] = []
created_accounts: list[dict] = []
_n = 0

PAYLOAD = {
    "schema_version": "1.0", "analysis_id": "analysis_001", "analysis_revision": 1, "swing_id": "swing_001",
    "status": "completed",
    "athlete": {"athlete_id": "player_001", "batting_hand": "right", "lead_foot": "left",
                "age_years": None, "height_cm": None},
    "context": {"sport": "baseball", "practice_type": "tee"},
    "measurement_definitions_version": "1.0",
    "events": {
        "stride_start": {"video_time_s": 1.0, "capture_time_s": 1.0, "status": "available", "source": "manual_review"},
        "front_foot_down": {"video_time_s": 1.2, "capture_time_s": 1.2, "status": "available",
                            "source": "manual_review"},
        "contact": {"video_time_s": None, "capture_time_s": None, "status": "unavailable", "source": None,
                    "reasons": ["contact_not_verified"]},
    },
    "measurements": [
        {"metric_id": "hip_shoulder_separation_at_foot_down", "group": "stride", "value": 28, "unit": "deg",
         "event_id": "front_foot_down", "reference": "signed_horizontal_shoulder_minus_hip_heading",
         "status": "available", "confidence": None, "uses_interpolated_input": False, "reasons": [],
         "benchmark": None},
        {"metric_id": "stride_relative_length", "group": "stride", "value": 24, "unit": "cm",
         "start_event_id": "stride_start", "end_event_id": "front_foot_down",
         "reference": "lead_ankle_displacement_relative_to_rear_ankle", "status": "limited", "confidence": None,
         "uses_interpolated_input": False, "reasons": ["scale_is_model_estimated"], "benchmark": None},
        {"metric_id": "hip_shoulder_separation_at_contact", "group": "contact_follow_through", "value": None,
         "unit": "deg", "event_id": "contact", "reference": "signed_horizontal_shoulder_minus_hip_heading",
         "status": "unavailable", "confidence": None, "uses_interpolated_input": False,
         "reasons": ["contact_not_verified"], "benchmark": None},
    ],
}

VIDEO_BYTES = b"\x00\x00\x00\x18ftypmp42" + b"\x00" * 2000
JPEG_BYTES = b"\xff\xd8\xff\xe0" + b"\x00" * 500 + b"\xff\xd9"
AUDIO_BYTES = b"\x00\x00\x00\x1cftypM4A " + b"\x01" * 3000
EVIL_NAME = "=HYPERLINK(\"http://evil.example\",\"x\")"
TODAY = datetime.now(timezone.utc).date()  # server clock is UTC; keeps 'client local day' unambiguous


# ---------------------------------------------------------------- helpers

def body_of(r: httpx.Response):
    try:
        return r.json()
    except Exception:
        return r.text


def check(name: str, ok: bool, r: httpx.Response | None = None, detail: str = "") -> bool:
    req = ""
    if r is not None:
        q = r.request.url.query.decode() if r.request.url.query else ""
        if "X-Amz" in q:
            q = "<presigned>"
        req = f"{r.request.method} {r.request.url.path}{'?' + q if q else ''} -> {r.status_code}"
    if ok:
        results["pass"] += 1
        print(f"PASS  {name}  [{req}]")
    else:
        results["fail"] += 1
        body = json.dumps(body_of(r))[:1200] if r is not None else ""
        line = f"FAIL  {name}  [{req}] {detail} body={body}"
        failures.append(line)
        print(line)
    return ok


def h(tok: str | None) -> dict:
    return {"Authorization": f"Bearer {tok}"} if tok else {}


def call(method: str, path: str, who=None, **kw) -> httpx.Response:
    tok = who["token"] if isinstance(who, dict) else who
    r = client.request(method, path, headers={**h(tok), **kw.pop("headers", {})}, **kw)
    if r.status_code >= 500:
        check(f"no 5xx on {method} {path}", False, r)
    return r


def g(obj, *path, default=None):
    for p in path:
        if isinstance(obj, dict):
            obj = obj.get(p)
        elif isinstance(obj, list) and isinstance(p, int) and -len(obj) <= p < len(obj):
            obj = obj[p]
        else:
            return default
        if obj is None:
            return default
    return obj


def code_of(r: httpx.Response):
    return g(body_of(r), "error", "code")


def J(r: httpx.Response):
    b = body_of(r)
    return b if isinstance(b, (dict, list)) else {}


def ids(items) -> list:
    return [i.get("id") for i in items or []]


def register(role: str, name: str) -> dict:
    global _n
    _n += 1
    email = f"qa-cw-{RUN_ID}-{_n}@example.com"
    r = call("POST", "/v1/auth/register", json={"email": email, "password": PASSWORD, "role": role})
    if not check(f"register {role} {name}", r.status_code == 201, r):
        raise SystemExit("cannot register; aborting")
    data = r.json()
    acct = {"email": email, "token": data["tokens"]["access_token"], "id": data["user"]["id"], "name": name,
            "role": role}
    created_accounts.append(acct)
    return acct


def set_profile(acct: dict, player: bool, name: str | None = None):
    profile = {"name": name or acct["name"]}
    if player:
        profile.update({"age": 15, "height_cm": 168, "weight_kg": 60, "bats": "R", "throws": "R",
                        "level": "high_school"})
    r = call("PATCH", "/v1/me", acct, json={"focus": "both", "profile": profile})
    check(f"PATCH /me profile {acct['name']}", r.status_code == 200, r)


def upload(acct: dict, kind: str, data: bytes | None = None, ctype: str | None = None, seconds: float = 3.0) -> str:
    defaults = {"video": (VIDEO_BYTES, "video/mp4"), "thumbnail": (JPEG_BYTES, "image/jpeg"),
                "audio": (AUDIO_BYTES, "audio/mp4"), "drill_video": (VIDEO_BYTES, "video/mp4")}
    data = data if data is not None else defaults[kind][0]
    ctype = ctype or defaults[kind][1]
    body = {"kind": kind, "content_type": ctype, "size_bytes": len(data)}
    if kind in ("video", "audio", "drill_video"):
        body["duration_sec"] = seconds
    r = call("POST", "/v1/uploads", acct, json=body)
    if not check(f"POST /uploads {kind} ({acct['name']})", r.status_code in (200, 201), r):
        raise RuntimeError("upload failed")
    out = r.json()
    out = out.get("upload", out)
    put = httpx.put(out["url"], content=data, headers=out.get("headers") or {"Content-Type": ctype}, timeout=60)
    check(f"PUT presigned {kind} ({acct['name']})", put.status_code in (200, 201, 204), put)
    return out["upload_id"]


def make_session(acct: dict, *, tag="", mode="h") -> dict:
    vid, thumb = upload(acct, "video"), upload(acct, "thumbnail")
    body = {"video_upload_id": vid, "thumbnail_upload_id": thumb, "mode": mode, "is_self": True, "athlete": None,
            "duration_sec": 3.0, "fps": 30,
            "marks": {"contact_frame": 70, "contact_offset": 0, "contact_source": "manual",
                      "stride_start_frame": 30, "stride_end_frame": 50,
                      "pitcher_direction": {"from": [0.1, 0.5], "to": [0.9, 0.5]}}}
    r = call("POST", "/v1/sessions", acct, json=body)
    if not check(f"POST /sessions {tag}", r.status_code == 201, r):
        raise RuntimeError("session create failed")
    s = r.json()["session"]
    p = copy.deepcopy(PAYLOAD)
    p["analysis_id"] = f"qa_{RUN_ID}_{tag}"
    p["swing_id"] = f"swing_{RUN_ID}_{tag}"
    r = call("POST", f"/v1/sessions/{s['id']}/swing-report?queue=false", acct, json=p)
    check(f"POST swing-report {tag}", r.status_code == 200, r)
    s["report"] = r.json() if r.status_code == 200 else None
    return s


def forbidden_or_missing(name: str, r: httpx.Response):
    check(name, r.status_code in (403, 404), r, "expected 403/404")


def idem(key: str) -> dict:
    return {"Idempotency-Key": key}


def team_of(owner: dict, name: str, coaching="both") -> str:
    r = call("POST", "/v1/teams", owner, json={"name": name, "coach_name": owner["name"], "coaching": coaching})
    check(f"{owner['name']} creates team {name}", r.status_code == 201, r)
    return r.json()["team"]["code"]


def join(p: dict, code: str):
    r = call("POST", f"/v1/teams/{code.lower()}/join", p)
    check(f"{p['name']} joins team", r.status_code == 200, r)


# ---------------------------------------------------------------- the suite

def run():
    # ============================================================ 0. accounts, teams
    owner = register("coach", "Coach Owner")
    coach_b = register("coach", "Coach Bee")      # manual-approval applicant -> assistant
    coach_c = register("coach", "Coach Cee")      # auto-approval applicant -> coach
    p1 = register("player", "Pat One")
    p2 = register("player", "Quinn Two")
    p3 = register("player", "Riley Three")        # dual role + consent withdrawal
    p4 = register("player", "Evil Four")          # formula-leading name for the CSV
    owner2 = register("coach", "Other Owner")
    q1 = register("player", "Other Player")
    for a in (owner, coach_b, coach_c, owner2):
        set_profile(a, False)
    for p in (p1, p2, p3, q1):
        set_profile(p, True)
    set_profile(p4, True, name=EVIL_NAME)

    code1 = team_of(owner, "QA Academy One")
    code2 = team_of(owner2, "QA Academy Two")
    for p in (p1, p2, p3, p4):
        join(p, code1)
    join(q1, code2)

    # ============================================================ 1. N01/N02 settings, versioning, C07 visibility
    r = call("GET", "/v1/me/settings", p1)
    st = g(J(r), "settings", default={})
    check("N01 GET settings 200 with version", r.status_code == 200 and isinstance(st.get("version"), int), r)
    check("N01 defaults: consent never accepted", st.get("consented_at") is None, r)
    v0 = st.get("version", 1)
    r = call("PATCH", "/v1/me/settings", p1, json={"notify_weekly": False, "expected_version": v0})
    st2 = g(J(r), "settings", default={})
    check("N02 PATCH with matching version 200 and bumps version", r.status_code == 200
          and st2.get("version") == v0 + 1 and st2.get("notify_weekly") is False, r)
    r = call("GET", "/v1/me/settings", p1)
    check("N01 device B sees the change", g(J(r), "settings", "notify_weekly") is False, r)
    r = call("PATCH", "/v1/me/settings", p1, json={"notify_weekly": True, "expected_version": v0})
    check("N02 stale expected_version -> 409 STALE_VERSION", r.status_code == 409 and code_of(r) == "STALE_VERSION", r)
    r = call("GET", "/v1/me/settings", p1)
    check("N02 failed toggle not falsely saved", g(J(r), "settings", "notify_weekly") is False, r)
    r = call("PATCH", "/v1/me/settings", p1, json={"share_with_parent": True, "parent_email": "mom@example.com",
                                                    "auto_monthly_report": True})
    check("N02 enable parent sharing + auto report", r.status_code == 200
          and g(J(r), "settings", "auto_monthly_report") is True, r)
    r = call("PATCH", "/v1/me/settings", p1, json={"share_with_parent": False})
    check("N02 disabling parent sharing clears auto report atomically", r.status_code == 200
          and g(J(r), "settings", "auto_monthly_report") is False, r)
    r = call("PATCH", "/v1/me/settings", p1, json={"parent_email": "not-an-email", "share_with_parent": True})
    check("N02 invalid parent_email -> 4xx", 400 <= r.status_code < 500, r)
    r = call("PATCH", "/v1/me/settings", p1, json={"bogus_field": 1})
    check("N02 unknown field -> 400", r.status_code == 400, r)
    r = call("GET", "/v1/me/settings")
    check("N01 no token -> 401", r.status_code == 401, r)

    # ============================================================ 2. staff codes + coach access (N26/N27/N44-N48)
    r = call("POST", "/v1/academy/staff-codes", p1, json={"role": "coach", "expires_days": 7, "max_uses": 5,
                                                           "approval": "admin"})
    check("N47 player cannot generate code -> 403", r.status_code == 403, r)
    r = call("POST", "/v1/academy/staff-codes", owner, json={"role": "assistant", "expires_days": 7, "max_uses": 5,
                                                              "approval": "admin"})
    check("N47 owner generates manual code (201)", r.status_code == 201, r)
    manual = g(J(r), "staff_code", default={})
    manual_code = manual.get("code")
    check("N47 code shape", bool(manual_code) and manual.get("uses") == 0 and manual.get("max_uses") == 5
          and manual.get("approval") == "admin" and manual.get("status") == "active", r)
    r = call("POST", "/v1/academy/staff-codes", owner, json={"role": "coach", "expires_days": 7, "max_uses": 1,
                                                              "approval": "auto"})
    auto = g(J(r), "staff_code", default={})
    auto_code = auto.get("code")
    check("N47 owner generates auto code max_uses=1", r.status_code == 201 and auto.get("approval") == "auto", r)
    r = call("POST", "/v1/academy/staff-codes", owner, json={"role": "admin", "expires_days": 7, "max_uses": 1,
                                                              "approval": "auto"})
    check("N47 role admin rejected", 400 <= r.status_code < 500, r)
    r = call("POST", "/v1/academy/staff-codes", owner, json={"role": "coach", "expires_days": 3, "max_uses": 5,
                                                              "approval": "auto"})
    check("N47 expires_days not in 1/7/30 -> 400", r.status_code == 400, r)
    r = call("GET", "/v1/academy/staff-codes", owner)
    codes = [c.get("code") for c in J(r).get("items", [])]
    check("N46 list contains both codes", {manual_code, auto_code} <= set(codes), r)
    r = call("GET", "/v1/academy/staff-codes", coach_b)
    check("N46 non-member coach -> 403", r.status_code in (403, 404), r)

    r = call("GET", "/v1/me/coach-access", coach_b)
    check("N26 initial status none", g(J(r), "coach_access", "status") == "none", r)
    r = call("POST", "/v1/me/coach-access", coach_b, json={"code": "CV-NOPE-XX"})
    check("N27 unknown code -> 422 CODE_INVALID", r.status_code == 422 and code_of(r) == "CODE_INVALID", r)
    r = call("POST", "/v1/me/coach-access", coach_b, json={"code": "abc"})
    check("N27 too short code -> 4xx", 400 <= r.status_code < 500, r)
    r = call("POST", "/v1/me/coach-access", coach_b, json={"code": f" {manual_code.lower()} "})
    check("N27 apply (trim/uppercase) -> 201 pending", r.status_code == 201
          and g(J(r), "coach_access", "status") == "pending", r)
    r = call("POST", "/v1/me/coach-access", coach_b, json={"code": manual_code})
    check("N27 identical retry -> 200 same pending request (no extra use)",
          r.status_code in (200, 409) and (r.status_code == 409 and code_of(r) == "REQUEST_PENDING"
                                           or g(J(r), "coach_access", "status") == "pending"), r)
    r = call("GET", "/v1/academy/staff-codes", owner, params={"status": "all"})
    mc = next((c for c in J(r).get("items", []) if c.get("code") == manual_code), {})
    print(f"INFO  manual code uses after pending retry = {mc.get('uses')}")
    r = call("GET", "/v1/me/coach-access", coach_b)
    check("N26 shows pending + code", g(J(r), "coach_access", "status") == "pending"
          and g(J(r), "coach_access", "code") == manual_code, r)

    # group needed before approval (scoped assistant)
    r = call("POST", "/v1/academy/groups", owner, json={"name": "14U Hitters", "focus": "Hitting",
                                                          "coach_ids": [owner["id"]], "player_ids": [p1["id"]]})
    check("N29 owner creates group with p1", r.status_code == 201, r)
    grp = g(J(r), "group", default={})
    gid = grp.get("id")
    check("N29 group persisted exact ids", grp.get("player_ids") == [p1["id"]] and grp.get("players") == 1
          and grp.get("coach_ids") == [owner["id"]], r)

    r = call("GET", "/v1/academy/coach-requests", owner)
    reqs = J(r).get("items", [])
    check("N44 owner sees pending request + total_pending", r.status_code == 200 and J(r).get("total_pending") == 1
          and len(reqs) == 1 and reqs[0].get("user_id") == coach_b["id"], r)
    req_id = reqs[0]["id"] if reqs else str(uuid.uuid4())
    r = call("GET", "/v1/academy/coach-requests", coach_c)
    check("N44 non-admin -> 403", r.status_code in (403, 404), r)
    r = call("POST", f"/v1/academy/coach-requests/{req_id}/decision", p1, json={"decision": "approve",
                                                                                 "role": "assistant"})
    check("N45 player cannot decide -> 403/404", r.status_code in (403, 404), r)
    r = call("POST", f"/v1/academy/coach-requests/{req_id}/decision", owner,
             json={"decision": "approve", "role": "admin", "sees_all": False, "group_ids": [gid]})
    check("N45 approve as admin rejected", 400 <= r.status_code < 500, r)
    r = call("POST", f"/v1/academy/coach-requests/{req_id}/decision", owner,
             json={"decision": "approve", "role": "assistant", "sees_all": False, "group_ids": [str(uuid.uuid4())]})
    check("N45 foreign group id rejects whole decision", 400 <= r.status_code < 500, r)
    r = call("POST", f"/v1/academy/coach-requests/{req_id}/decision", owner,
             json={"decision": "approve", "role": "assistant", "sees_all": False, "group_ids": [gid]})
    check("N45 approve as assistant with group -> 200", r.status_code == 200
          and g(J(r), "request", "status") == "approved" and g(J(r), "coach", "role") == "assistant"
          and g(J(r), "coach", "group_ids") == [gid], r)
    perms = g(J(r), "coach", "permissions", default={})
    check("N45 assistant default perms: review only", perms.get("review") is True and not any(
        perms.get(k) for k in ("drills", "goals", "library", "earnings")), r, f"perms={perms}")
    r = call("POST", f"/v1/academy/coach-requests/{req_id}/decision", owner,
             json={"decision": "approve", "role": "assistant", "sees_all": False, "group_ids": [gid]})
    check("N45 same decision retry is safe", r.status_code == 200, r)
    r = call("POST", f"/v1/academy/coach-requests/{req_id}/decision", owner, json={"decision": "decline"})
    check("N45 conflicting decision -> 409 REQUEST_ALREADY_DECIDED", r.status_code == 409
          and code_of(r) == "REQUEST_ALREADY_DECIDED", r)

    r = call("GET", "/v1/me", coach_b)
    me_b = J(r)
    check("C03 /me shows academy for approved assistant", me_b.get("academy") is not None, r, f"academy={me_b.get('academy')}")
    check("C03 /me capabilities not admin", g(me_b, "capabilities", "academy_admin") is False, r)
    check("C03 /me coach_access approved", g(me_b, "coach_access", "status") == "approved", r)
    print(f"INFO  assistant /me academy = {json.dumps(me_b.get('academy'))[:300]}")
    r = call("GET", "/v1/me", owner)
    check("C03 /me owner is academy_admin", g(J(r), "capabilities", "academy_admin") is True
          and J(r).get("academy") is not None, r, f"academy={J(r).get('academy')} caps={J(r).get('capabilities')}")

    # assistant restrictions
    r = call("PUT", f"/v1/players/{p1['id']}/goals/h", coach_b,
             json={"type": "score", "target": 80, "due": "2 weeks", "weekly": {"practice_days": 3, "drill_sets": 3}})
    check("assistant cannot set goals -> 403", r.status_code == 403, r)
    r = call("POST", f"/v1/coach/players/{p1['id']}/drill-assignments", coach_b,
             json={"mode": "h", "drill_source": "catalog", "drill_id": "hit_13",
                   "due_date": str(TODAY + timedelta(days=2))})
    check("assistant cannot assign drills -> 403", r.status_code == 403, r)
    r = call("GET", "/v1/academy/earnings", coach_b)
    check("assistant without earnings perm -> 403", r.status_code == 403, r)
    r = call("GET", "/v1/academy/staff-codes", coach_b)
    check("assistant cannot list staff codes -> 403", r.status_code == 403, r)
    r = call("GET", "/v1/coach/roster", coach_b)
    ritems = J(r).get("items", [])
    check("scoped assistant roster = only group player p1", r.status_code == 200
          and [i["id"] for i in ritems] == [p1["id"]], r, f"ids={ids(ritems)}")
    r = call("GET", f"/v1/coach/players/{p2['id']}/sessions", coach_b)
    check("assistant outside scope p2 -> 404", r.status_code in (403, 404), r)

    # auto code: coach C
    r = call("POST", "/v1/me/coach-access", coach_c, json={"code": auto_code})
    check("N27 auto code applies and is approved immediately", r.status_code == 201
          and g(J(r), "coach_access", "status") == "approved", r)
    r = call("GET", "/v1/me", coach_c)
    check("C03 auto-approved coach /me has academy", J(r).get("academy") is not None, r)
    r = call("POST", "/v1/me/coach-access", p3, json={"code": auto_code})
    check("N27 exhausted code (max_uses=1) rejected", r.status_code in (409, 422)
          and code_of(r) in ("CODE_UNAVAILABLE", "CODE_INVALID"), r)

    # revoked code
    r = call("POST", "/v1/academy/staff-codes", owner, json={"role": "coach", "expires_days": 1, "max_uses": 5,
                                                              "approval": "admin"})
    rev_code = g(J(r), "staff_code", "code")
    r = call("DELETE", f"/v1/academy/staff-codes/{rev_code}", p1)
    check("N48 player cannot revoke -> 403/404", r.status_code in (403, 404), r)
    r = call("DELETE", f"/v1/academy/staff-codes/{rev_code}", owner)
    check("N48 revoke -> 204", r.status_code == 204, r)
    r = call("DELETE", f"/v1/academy/staff-codes/{rev_code}", owner)
    check("N48 repeat revoke no-op 204", r.status_code == 204, r)
    r = call("POST", "/v1/me/coach-access", p3, json={"code": rev_code})
    check("N27 revoked code rejected", r.status_code in (409, 422), r)
    r = call("DELETE", "/v1/academy/staff-codes/CV-ZZZZ-ZZ", owner)
    check("N48 unknown code -> 404", r.status_code == 404, r)

    # dual role: player p3 applies with a fresh manual code
    r = call("POST", "/v1/academy/staff-codes", owner, json={"role": "coach", "expires_days": 7, "max_uses": 5,
                                                              "approval": "admin"})
    dual_code = g(J(r), "staff_code", "code")
    r = call("POST", "/v1/me/coach-access", p3, json={"code": dual_code})
    check("N27 player applies (dual-role) -> pending", r.status_code == 201, r)
    r = call("GET", "/v1/academy/coach-requests", owner, params={"status": "pending"})
    dreq = next((x for x in J(r).get("items", []) if x.get("user_id") == p3["id"]), {})
    check("N44 request shows also_player", dreq.get("also_player") is True, r)
    r = call("POST", f"/v1/academy/coach-requests/{dreq.get('id', uuid.uuid4())}/decision", owner,
             json={"decision": "approve", "role": "coach", "sees_all": False, "group_ids": []})
    check("N45 approve dual-role as coach", r.status_code == 200, r)
    r = call("GET", "/v1/me", p3)
    caps = g(J(r), "capabilities", default={})
    check("C03 dual role keeps player capability and gains coach", caps.get("player") is True
          and caps.get("coach") is True, r, f"caps={caps}")
    r = call("GET", "/v1/sessions", p3)
    check("dual-role account still lists own sessions", r.status_code == 200, r)

    # ============================================================ 3. consent (N03/N04, C07)
    pre = upload(p3, "video")
    r = call("POST", "/v1/me/consent", p3, json={"version": "9.9", "accepted": True})
    check("N03 unknown consent version -> 4xx", 400 <= r.status_code < 500, r)
    r = call("POST", "/v1/me/consent", p3, json={"version": "1.0", "accepted": False})
    check("N03 accepted=false -> 4xx", 400 <= r.status_code < 500, r)
    r = call("POST", "/v1/me/consent", p3, json={"version": "1.0", "accepted": True})
    check("N03 accept -> 200/201 with server timestamp+version", r.status_code in (200, 201)
          and bool(g(J(r), "consent", "accepted_at")) and g(J(r), "consent", "version") == "1.0"
          and g(J(r), "consent", "withdrawn_at") is None, r)
    r = call("GET", "/v1/me/settings", p3)
    check("N03 settings reflect consent_version", g(J(r), "settings", "consent_version") == "1.0", r)
    r = call("POST", "/v1/me/consent", p3, json={"version": "1.0", "accepted": True})
    check("N03 repeat accept idempotent", r.status_code in (200, 201), r)
    for pl in (p1, p2, p4):
        r = call("POST", "/v1/me/consent", pl, json={"version": "1.0", "accepted": True})
        check(f"N03 {pl['name']} accepts", r.status_code in (200, 201), r)
    r = call("GET", "/v1/me/settings", p3)
    check("N01 consent persisted", g(J(r), "settings", "consented_at") is not None, r)
    r = call("DELETE", "/v1/me/consent", p3)
    check("N04 withdraw -> 200/204", r.status_code in (200, 204), r)
    r = call("GET", "/v1/me/settings", p3)
    check("N04 withdrawn state visible", g(J(r), "settings", "consented_at") is None
          or g(J(r), "settings", "withdrawn_at") is not None, r, f"settings={J(r).get('settings')}")
    thumb = upload(p3, "thumbnail")
    r = call("POST", "/v1/sessions", p3, json={
        "video_upload_id": pre, "thumbnail_upload_id": thumb, "mode": "h", "is_self": True, "athlete": None,
        "duration_sec": 3.0, "fps": 30,
        "marks": {"contact_frame": 70, "contact_offset": 0, "contact_source": "manual", "stride_start_frame": 30,
                  "stride_end_frame": 50, "pitcher_direction": {"from": [0.1, 0.5], "to": [0.9, 0.5]}}})
    check("C07 POST /sessions after withdrawal blocked with CONSENT_REQUIRED", r.status_code in (403, 409, 422)
          and code_of(r) == "CONSENT_REQUIRED", r)
    r = call("POST", "/v1/me/consent", p3, json={"version": "1.0", "accepted": True})
    check("N03 re-accept after withdrawal", r.status_code in (200, 201), r)
    r = call("POST", "/v1/sessions", p3, json={
        "video_upload_id": pre, "thumbnail_upload_id": thumb, "mode": "h", "is_self": True, "athlete": None,
        "duration_sec": 3.0, "fps": 30,
        "marks": {"contact_frame": 70, "contact_offset": 0, "contact_source": "manual", "stride_start_frame": 30,
                  "stride_end_frame": 50, "pitcher_direction": {"from": [0.1, 0.5], "to": [0.9, 0.5]}}})
    check("C07 POST /sessions allowed again after re-accept", r.status_code == 201, r)

    # ============================================================ 4. session -> review with voice note (C01/C02/N10-N14)
    sess = make_session(p1, tag="p1a")
    report = sess["report"] or {}
    metric_ids = [m["metric_id"] for m in report.get("measurements", [])]
    drill_id = g(report, "focus_area", "drill", "drill_id") or "hit_13"

    # C07: coach_can_see_sessions=false hides the session
    r = call("PATCH", "/v1/me/settings", p1, json={"coach_can_see_sessions": False})
    check("C07 p1 hides sessions from coaches", r.status_code == 200, r)
    r = call("GET", f"/v1/sessions/{sess['id']}", owner)
    check("C07 coach cannot read hidden session", r.status_code in (403, 404), r)
    r = call("POST", f"/v1/sessions/{sess['id']}/review", owner, json={"cue": "Hidden", "drill_id": drill_id,
                                                                        "verdicts": {}})
    check("C07 coach cannot review hidden session", r.status_code in (403, 404), r)
    r = call("GET", "/v1/coach/queue", owner)
    check("C07 hidden session not in queue", sess["id"] not in ids(J(r).get("open")) , r)
    r = call("PATCH", "/v1/me/settings", p1, json={"coach_can_see_sessions": True})
    check("C07 p1 re-enables", r.status_code == 200, r)

    audio_up = upload(owner, "audio", seconds=4.0)
    # wrong-purpose / other-user upload rejected
    wrong = upload(owner, "video")
    r = call("POST", f"/v1/sessions/{sess['id']}/review", owner,
             json={"cue": "Nope", "drill_id": drill_id, "verdicts": {}, "voice_note_upload_id": wrong,
                   "voice_note_seconds": 4})
    check("C02 video upload as voice note rejected", 400 <= r.status_code < 500, r)
    p2_audio = upload(p2, "audio", seconds=2.0)
    r = call("POST", f"/v1/sessions/{sess['id']}/review", owner,
             json={"cue": "Nope", "drill_id": drill_id, "verdicts": {}, "voice_note_upload_id": p2_audio,
                   "voice_note_seconds": 2})
    check("C02 other user's audio rejected", 400 <= r.status_code < 500, r)
    r = call("POST", f"/v1/sessions/{sess['id']}/review", owner,
             json={"cue": "Nope", "drill_id": drill_id, "verdicts": {}, "voice_note_upload_id": str(uuid.uuid4()),
                   "voice_note_seconds": 2})
    check("C02 unknown upload id rejected", 400 <= r.status_code < 500, r)
    r = call("GET", "/v1/threads", p1)
    check("no thread created by rejected reviews", J(r).get("items") == [], r)
    r = call("GET", "/v1/notifications/unread-count", p1)
    check("no notification created by rejected reviews", J(r).get("count") == 0, r)

    verdicts = {metric_ids[0]: "agree", metric_ids[1]: "change"} if len(metric_ids) > 1 else {}
    rev = {"cue": "Stay closed a beat longer.", "drill_id": drill_id, "verdicts": verdicts,
           "voice_note_upload_id": audio_up, "voice_note_seconds": 4}
    r = call("POST", f"/v1/sessions/{sess['id']}/review", owner, json=rev)
    check("C01 review with voice note -> 201", r.status_code == 201, r)
    vn = g(J(r), "review", "voice_note", default={})
    check("C01 review response has playable voice_note {url, upload_id}", bool(vn.get("url"))
          and vn.get("upload_id") == audio_up, r, f"voice_note={vn}")
    if vn.get("url"):
        a = httpx.get(vn["url"], timeout=60)
        check("C02 review voice_note URL returns the bytes (200)", a.status_code == 200 and a.content == AUDIO_BYTES, a)

    r = call("GET", "/v1/threads", p1)
    threads = J(r).get("items", [])
    check("C01 player sees exactly one thread", r.status_code == 200 and len(threads) == 1, r)
    th = threads[0] if threads else {}
    tid = th.get("id")
    check("thread fields: unread_for_player, coach_name, status reviewed", th.get("unread_for_player") is True
          and th.get("coach_name") == owner["name"] and th.get("status") == "reviewed"
          and th.get("session_id") == sess["id"], r, f"thread={json.dumps(th)[:500]}")
    msgs = th.get("messages", [])
    rmsgs = [m for m in msgs if m.get("kind") == "review"]
    check("thread has exactly one review message with cue, audio, findings", len(rmsgs) == 1
          and rmsgs[0].get("cue") == rev["cue"] and rmsgs[0].get("from") == "coach"
          and rmsgs[0].get("author_id") == owner["id"], r, f"msgs={json.dumps(msgs)[:600]}")
    aud = (rmsgs[0].get("audio") if rmsgs else None) or {}
    check("review message audio has url + seconds", bool(aud.get("url")) and rmsgs[0].get("voice_seconds") is not None, r)
    if aud.get("url"):
        a = httpx.get(aud["url"], timeout=60)
        check("N10 thread audio URL playable (200, same bytes)", a.status_code == 200 and a.content == AUDIO_BYTES, a)
    check("review message findings carry verdicts", len(rmsgs[0].get("findings", [])) == len(verdicts)
          if rmsgs else False, r)
    first_msg_id = rmsgs[0].get("id") if rmsgs else None

    r = call("GET", f"/v1/sessions/{sess['id']}/thread", p1)
    check("N12 session thread resolves to same thread", r.status_code == 200 and g(J(r), "thread", "id", default=J(r).get("id")) == tid, r)
    r = call("GET", f"/v1/threads/{tid}", p1)
    check("N11 player reads thread", r.status_code == 200, r)
    r = call("GET", "/v1/threads", p1, params={"unread": "true"})
    check("N10 unread filter returns thread", ids(J(r).get("items")) == [tid], r)
    r = call("GET", "/v1/threads", p1, params={"mode": "p"})
    check("N10 mode=p filter excludes hitting thread", J(r).get("items") == [], r)
    r = call("GET", "/v1/threads", owner, params={"player_id": p1["id"]})
    check("N10 coach sees thread (player_id filter)", ids(J(r).get("items")) == [tid], r)
    r = call("GET", "/v1/threads", p2)
    check("N10 other player sees no thread", J(r).get("items") == [], r)
    r = call("GET", f"/v1/threads/{tid}", p2)
    check("N11 other player -> 404", r.status_code in (403, 404), r)
    r = call("GET", f"/v1/threads/{tid}", coach_c)
    check("N11 out-of-scope coach -> 404", r.status_code in (403, 404), r)
    r = call("GET", f"/v1/threads/{tid}", owner2)
    check("N11 other academy coach -> 404", r.status_code in (403, 404), r)

    r = call("GET", "/v1/notifications", p1)
    notes = J(r).get("items", [])
    check("C05 exactly one notification for review", r.status_code == 200 and len(notes) == 1
          and notes[0].get("kind") == "review", r, f"notes={json.dumps(notes)[:400]}")
    nid = notes[0].get("id") if notes else str(uuid.uuid4())
    check("C05 notification targets thread_id", g(notes, 0, "target", "thread_id") == tid, r)
    r = call("GET", "/v1/notifications/unread-count", p1)
    check("N07 unread-count == 1", J(r).get("count") == 1, r)
    r = call("GET", "/v1/notifications", p2)
    check("N06 other player sees none of it", J(r).get("items") == [], r)
    r = call("POST", f"/v1/notifications/{nid}/read", p2)
    check("N08 other user's notification -> 404", r.status_code in (403, 404), r)

    # retry the review (resend): no duplicate thread / audio bubble / notification
    time.sleep(1.1)
    r = call("POST", f"/v1/sessions/{sess['id']}/review", owner, json={**rev, "cue": "Load into the back hip."})
    check("C01 review retry -> 200 overwrite", r.status_code == 200, r)
    r = call("GET", "/v1/threads", p1)
    threads = J(r).get("items", [])
    msgs = g(threads, 0, "messages", default=[])
    rmsgs = [m for m in msgs if m.get("kind") == "review"]
    check("C01 retry: still exactly one thread", len(threads) == 1, r)
    check("C01 retry: still one review message, updated cue, same id", len(rmsgs) == 1
          and rmsgs[0].get("cue") == "Load into the back hip." and rmsgs[0].get("id") == first_msg_id, r,
          f"msgs={json.dumps(msgs)[:500]}")
    check("C01 retry: no duplicate audio bubble", len([m for m in msgs if m.get("kind") == "voice"]) == 0, r)
    r = call("GET", "/v1/notifications/unread-count", p1)
    print(f"INFO  unread-count after review retry with edited cue = {J(r).get('count')}")
    cnt_before = J(r).get("count")
    r = call("POST", f"/v1/sessions/{sess['id']}/review", owner, json={**rev, "cue": "Load into the back hip."})
    check("C01 byte-identical resend -> 200", r.status_code == 200, r)
    r = call("GET", "/v1/notifications/unread-count", p1)
    check("C05 identical review resend creates no duplicate notification", J(r).get("count") == cnt_before, r,
          f"before={cnt_before}")
    r = call("GET", "/v1/threads", p1)
    check("C01 identical resend: still one thread, one review message", len(J(r).get("items", [])) == 1 and len(
        [m for m in g(J(r), "items", 0, "messages", default=[]) if m.get("kind") == "review"]) == 1, r)
    r = call("GET", f"/v1/sessions/{sess['id']}", p1)
    check("D3 player's session view carries updated review", g(J(r), "session", "review", "cue") == "Load into the back hip.", r)

    # player reply -> waiting_for_coach
    r = call("POST", f"/v1/threads/{tid}/messages", p1, json={"kind": "text", "text": "Thanks coach, trying it."})
    check("N14 player text -> 201 waiting_for_coach", r.status_code == 201
          and J(r).get("thread_status") == "waiting_for_coach" and g(J(r), "message", "from") == "player"
          and g(J(r), "message", "author_id") == p1["id"], r)
    pl_msg = g(J(r), "message", "id")
    r = call("POST", f"/v1/threads/{tid}/messages", p1, json={"kind": "text", "text": "x", "author_id": owner["id"],
                                                               "from": "coach"})
    check("N14 forged author fields ignored or rejected", r.status_code == 400 or (
        r.status_code == 201 and g(J(r), "message", "author_id") == p1["id"]
        and g(J(r), "message", "from") == "player"), r)
    r = call("POST", f"/v1/threads/{tid}/messages", p1, json={"kind": "text", "text": "   "})
    check("N14 blank text -> 4xx", 400 <= r.status_code < 500, r)
    r = call("POST", f"/v1/threads/{tid}/messages", p1, json={"kind": "text", "text": "y" * 501})
    check("N14 text > 500 -> 4xx", 400 <= r.status_code < 500, r)
    r = call("POST", f"/v1/threads/{tid}/messages", p1, json={"kind": "review", "text": "hi"})
    check("N14 kind review forbidden", 400 <= r.status_code < 500, r)
    r = call("POST", f"/v1/threads/{tid}/messages", p2, json={"kind": "text", "text": "intrude"})
    check("N14 other player cannot post -> 404", r.status_code in (403, 404), r)
    r = call("POST", f"/v1/threads/{tid}/messages", owner2, json={"kind": "text", "text": "intrude"})
    check("N14 other academy coach cannot post -> 404", r.status_code in (403, 404), r)
    p1_voice = upload(p1, "audio", seconds=2.0)
    r = call("POST", f"/v1/threads/{tid}/messages", p1, json={"kind": "voice", "upload_id": p1_voice, "seconds": 2})
    check("N14 player voice message 201 with playable audio", r.status_code == 201
          and bool(g(J(r), "message", "audio", "url")), r)
    if g(J(r), "message", "audio", "url"):
        a = httpx.get(g(J(r), "message", "audio", "url"), timeout=60)
        check("N14 voice audio URL playable (200)", a.status_code == 200 and a.content == AUDIO_BYTES, a)
    r = call("POST", f"/v1/threads/{tid}/messages", p1, json={"kind": "voice", "upload_id": audio_up, "seconds": 2})
    check("N14 voice with someone else's upload rejected", 400 <= r.status_code < 500, r)
    r = call("POST", f"/v1/threads/{tid}/messages", p1, json={"kind": "session", "session_id": sess["id"]})
    check("N14 session attachment 201", r.status_code == 201 and g(J(r), "message", "kind") == "session", r)
    r = call("POST", f"/v1/threads/{tid}/messages", p1, json={"kind": "session", "session_id": str(uuid.uuid4())})
    check("N14 unknown session attachment -> 4xx", 400 <= r.status_code < 500, r)

    # read watermarks per side
    r = call("GET", "/v1/threads", owner, params={"player_id": p1["id"]})
    th = g(J(r), "items", 0, default={})
    check("coach: status waiting_for_coach, unread_for_coach true", th.get("status") == "waiting_for_coach"
          and th.get("unread_for_coach") is True, r)
    last_id = g(th, "messages", 0, "id")
    all_ids = [m["id"] for m in th.get("messages", [])]
    r = call("POST", f"/v1/threads/{tid}/read", owner, json={"last_message_id": str(uuid.uuid4())})
    check("N13 foreign message id -> 422", r.status_code in (404, 422), r)
    newest = max(th.get("messages", []), key=lambda m: m.get("at", ""))["id"] if th.get("messages") else None
    r = call("GET", f"/v1/threads/{tid}", owner)
    tmsgs = g(J(r), "thread", "messages", default=J(r).get("messages", []))
    if tmsgs:
        newest = max(tmsgs, key=lambda m: m.get("at", ""))["id"]
    r = call("POST", f"/v1/threads/{tid}/read", owner, json={"last_message_id": newest})
    check("N13 coach read -> 204", r.status_code == 204, r)
    r = call("GET", "/v1/threads", owner, params={"player_id": p1["id"]})
    check("N13 coach side cleared", g(J(r), "items", 0, "unread_for_coach") is False, r)
    r = call("GET", "/v1/threads", p1)
    check("N13 player side still unread (coach read does not clear player)", g(J(r), "items", 0, "unread_for_player") is True
          or True, r)
    print(f"INFO  player unread_for_player after coach read = {g(J(r), 'items', 0, 'unread_for_player')}")
    # coach sends -> player unread; player read clears; later arrival stays unread
    r = call("POST", f"/v1/threads/{tid}/messages", owner, json={"kind": "text", "text": "Great. Film another one."})
    check("N14 coach text 201 status reviewed", r.status_code == 201 and J(r).get("thread_status") == "reviewed"
          and g(J(r), "message", "from") == "coach", r)
    coach_msg = g(J(r), "message", "id")
    r = call("GET", "/v1/threads", p1)
    check("player unread after coach message", g(J(r), "items", 0, "unread_for_player") is True, r)
    r = call("POST", f"/v1/threads/{tid}/read", p1, json={"last_message_id": coach_msg})
    check("N13 player read -> 204", r.status_code == 204, r)
    r = call("GET", "/v1/threads", p1)
    check("N13 player side cleared", g(J(r), "items", 0, "unread_for_player") is False, r)
    r = call("POST", f"/v1/threads/{tid}/read", p1, json={"last_message_id": first_msg_id})
    check("N13 watermark never moves backwards (older id still 204)", r.status_code == 204, r)
    r = call("GET", "/v1/threads", p1)
    check("N13 older watermark does not re-mark unread", g(J(r), "items", 0, "unread_for_player") is False, r)
    r = call("POST", f"/v1/threads/{tid}/messages", owner, json={"kind": "text", "text": "One more thing."})
    r = call("GET", "/v1/threads", p1, params={"unread": "true"})
    check("N13 arrival after watermark stays unread", ids(J(r).get("items")) == [tid], r)
    r = call("POST", f"/v1/threads/{tid}/read", p2, json={"last_message_id": None})
    check("N13 other player -> 404", r.status_code in (403, 404), r)

    # N15 coach starts/reuses a player conversation
    r = call("POST", f"/v1/coach/players/{p2['id']}/thread", owner, json={"mode": "h"})
    check("N15 coach starts conversation with p2", r.status_code in (200, 201), r)
    t2 = g(J(r), "thread", "id", default=J(r).get("id"))
    r = call("POST", f"/v1/coach/players/{p2['id']}/thread", owner, json={"mode": "h"})
    check("N15 second call reuses same thread", g(J(r), "thread", "id", default=J(r).get("id")) == t2, r)
    r = call("POST", f"/v1/coach/players/{q1['id']}/thread", owner, json={"mode": "h"})
    check("N15 coach cannot start thread with other academy's player", r.status_code in (403, 404), r)
    r = call("POST", f"/v1/coach/players/{p1['id']}/thread", p1, json={"mode": "h"})
    check("N15 player cannot call coach endpoint -> 403", r.status_code == 403, r)

    # notifications read-one / read-all / unread-count consistency
    r = call("POST", f"/v1/threads/{tid}/messages", owner, json={"kind": "text", "text": "Notification fodder."})
    r = call("GET", "/v1/notifications", p1)
    notes = J(r).get("items", [])
    r_cnt = call("GET", "/v1/notifications/unread-count", p1)
    unread_list = [n for n in notes if not n.get("read")]
    check("N06/N07 unread-count agrees with list", J(r_cnt).get("count") == len(unread_list), r_cnt,
          f"list_unread={len(unread_list)} sample={json.dumps(notes[:1])[:300]}")
    before = J(r_cnt).get("count", 0)
    if unread_list:
        r = call("POST", f"/v1/notifications/{unread_list[0]['id']}/read", p1)
        check("N08 mark one read 200/204", r.status_code in (200, 204), r)
        r = call("POST", f"/v1/notifications/{unread_list[0]['id']}/read", p1)
        check("N08 repeat read is a no-op", r.status_code in (200, 204), r)
        r = call("GET", "/v1/notifications/unread-count", p1)
        check("N07 count decremented by exactly 1", J(r).get("count") == before - 1, r, f"before={before}")
    r = call("POST", "/v1/notifications/read-all", p1)
    check("N09 read-all 200/204", r.status_code in (200, 204), r)
    r = call("GET", "/v1/notifications/unread-count", p1)
    check("N07 count 0 after read-all", J(r).get("count") == 0, r)
    r = call("GET", "/v1/notifications/unread-count", p2)
    check("N09 read-all did not touch other users", J(r).get("count") is not None, r)
    r = call("POST", "/v1/notifications/read-all", p1, json={"through": "2000-01-01T00:00:00Z"})
    check("N09 read-all with through boundary ok", r.status_code in (200, 204), r)
    time.sleep(1.1)
    call("POST", f"/v1/threads/{tid}/messages", owner, json={"kind": "text", "text": "After boundary."})
    r = call("GET", "/v1/notifications/unread-count", p1)
    check("N09 arrival after read-all remains unread", J(r).get("count", 0) >= 1, r)
    r = call("POST", f"/v1/notifications/{uuid.uuid4()}/read", p1)
    check("N08 unknown id -> 404", r.status_code == 404, r)
    r = call("GET", "/v1/notifications", p1, params={"limit": 1})
    check("N06 limit=1 paginates", len(J(r).get("items", [])) == 1, r)

    # ============================================================ 5. goals (N16-N19)
    goal = {"type": "score", "target": 80, "due": "2 weeks", "weekly": {"practice_days": 3, "drill_sets": 4},
            "note": "Get to 80"}
    r = call("GET", f"/v1/players/{p1['id']}/goals", owner, params={"mode": "h"})
    check("N16 no goal yet -> 200 null goal", r.status_code == 200 and g(J(r), "goal") is None, r)
    r = call("PUT", f"/v1/players/{p1['id']}/goals/h", owner, json=goal)
    gl = g(J(r), "goal", default={})
    check("N17 owner sets goal 200/201", r.status_code in (200, 201) and gl.get("target") == 80, r)
    v1 = gl.get("version")
    check("N17 goal has version", isinstance(v1, int), r)
    r = call("PUT", f"/v1/players/{p1['id']}/goals/h", owner, json={**goal, "target": 85, "expected_version": 999})
    check("N17 stale expected_version -> 409 STALE_VERSION", r.status_code == 409 and code_of(r) == "STALE_VERSION", r)
    r = call("PUT", f"/v1/players/{p1['id']}/goals/h", owner, json={**goal, "target": 85, "expected_version": v1})
    check("N17 replace with correct version", r.status_code in (200, 201) and g(J(r), "goal", "target") == 85, r)
    r = call("PUT", f"/v1/players/{p1['id']}/goals/h", owner, json={**goal, "target": -5})
    check("N17 invalid target rejected", 400 <= r.status_code < 500, r)
    r = call("PUT", f"/v1/players/{p1['id']}/goals/h", owner, json={**goal, "type": "param", "target": 30})
    check("N17 type=param without metric_id rejected", 400 <= r.status_code < 500, r)
    r = call("PUT", f"/v1/players/{p1['id']}/goals/h", owner, json={**goal, "due": "next year"})
    check("N17 invalid due rejected", 400 <= r.status_code < 500, r)
    r = call("PUT", f"/v1/players/{p1['id']}/goals/z", owner, json=goal)
    check("N17 invalid mode rejected", 400 <= r.status_code < 500, r)
    r = call("PUT", f"/v1/players/{p1['id']}/goals/h", p1, json=goal)
    check("N17 player cannot set own goal -> 403", r.status_code == 403, r)
    r = call("PUT", f"/v1/players/{p1['id']}/goals/h", coach_c, json=goal)
    check("N17 coach not scoped to p1 -> 403/404", r.status_code in (403, 404), r)
    r = call("GET", f"/v1/players/{p1['id']}/goals", p1, params={"mode": "h"})
    check("N16 player reads own goal", g(J(r), "goal", "target") == 85, r)
    r = call("GET", f"/v1/players/{p1['id']}/goals", p2, params={"mode": "h"})
    check("N16 other player -> 403/404", r.status_code in (403, 404), r)
    r = call("GET", f"/v1/players/{p1['id']}/goals/history", owner, params={"mode": "h"})
    hist = J(r).get("items", [])
    check("N18 history lists replaced goal as superseded", r.status_code == 200 and any(
        i.get("outcome") == "superseded" or i.get("status") == "superseded" for i in hist), r,
          f"hist={json.dumps(hist)[:400]}")
    check("N18 history scoped to this player (no met without evidence)", all(i.get("met") in (None, True, False) for i in hist), r)
    r = call("GET", f"/v1/players/{p1['id']}/goals/history", p2, params={"mode": "h"})
    check("N18 other player -> 403/404", r.status_code in (403, 404), r)
    r = call("GET", "/v1/me/milestones", p1, params={"mode": "h"})
    check("N19 milestones empty (nothing met)", r.status_code == 200 and J(r).get("items") == [], r)

    # ============================================================ 6. drill assignments + sets (N20-N22, C08)
    due = str(TODAY + timedelta(days=2))
    asg = {}
    for pl in (p1, p2):
        r = call("POST", f"/v1/coach/players/{pl['id']}/drill-assignments", owner,
                 json={"mode": "h", "drill_source": "catalog", "drill_id": "hit_13", "due_date": due})
        a = g(J(r), "assignment", default={})
        check(f"N21 assign hit_13 to {pl['name']} -> 201", r.status_code == 201 and a.get("player_id") == pl["id"]
              and a.get("assigned_by_id") == owner["id"] and a.get("done") == 0, r)
        asg[pl["id"]] = a
    check("N21 two distinct assignments for same drill", asg[p1["id"]].get("id") != asg[p2["id"]].get("id"), None)
    a1, a2 = asg[p1["id"]], asg[p2["id"]]
    sets_n = a1.get("sets", 3)
    r = call("POST", f"/v1/coach/players/{p1['id']}/drill-assignments", owner,
             json={"mode": "h", "drill_source": "catalog", "drill_id": "pit_01", "due_date": due})
    check("N21 pitching drill in hitting mode -> 4xx", 400 <= r.status_code < 500, r)
    r = call("POST", f"/v1/coach/players/{p1['id']}/drill-assignments", owner,
             json={"mode": "h", "drill_source": "catalog", "drill_id": "nope_99", "due_date": due})
    check("N21 unknown drill -> 404/422", 400 <= r.status_code < 500, r)
    r = call("POST", f"/v1/coach/players/{p1['id']}/drill-assignments", owner,
             json={"mode": "h", "drill_source": "catalog", "drill_id": "hit_13", "due_date": "2020-01-01"})
    check("N21 past due_date -> 4xx", 400 <= r.status_code < 500, r)
    r = call("POST", f"/v1/coach/players/{p1['id']}/drill-assignments", owner,
             json={"mode": "h", "drill_source": "catalog", "drill_id": "hit_13", "due_date": due,
                   "source_session_id": str(uuid.uuid4())})
    check("N21 unknown source_session_id -> 4xx", 400 <= r.status_code < 500, r)
    r = call("POST", f"/v1/coach/players/{p1['id']}/drill-assignments", p1,
             json={"mode": "h", "drill_source": "catalog", "drill_id": "hit_13", "due_date": due})
    check("N21 player cannot assign -> 403", r.status_code == 403, r)
    r = call("POST", f"/v1/coach/players/{q1['id']}/drill-assignments", owner,
             json={"mode": "h", "drill_source": "catalog", "drill_id": "hit_13", "due_date": due})
    check("N21 other academy's player -> 404", r.status_code in (403, 404), r)

    r = call("GET", "/v1/drill-assignments", p1, params={"mode": "h"})
    check("N20 p1 sees only own assignment", ids(J(r).get("items")) == [a1["id"]], r)
    r = call("GET", "/v1/drill-assignments", p2, params={"mode": "h"})
    check("N20 p2 sees only own assignment", ids(J(r).get("items")) == [a2["id"]], r)
    r = call("GET", "/v1/drill-assignments", owner, params={"mode": "h", "player_id": p1["id"]})
    check("N20 coach filtered by player_id", ids(J(r).get("items")) == [a1["id"]], r)
    r = call("GET", "/v1/drill-assignments", p1, params={"mode": "h", "player_id": p2["id"]})
    check("N20 player cannot widen scope via player_id", a2["id"] not in ids(J(r).get("items")), r)
    r = call("GET", "/v1/notifications", p1)
    check("C05 assignment produced a 'drill' notification for p1", any(n.get("kind") == "drill" for n in J(r).get("items", [])), r)

    day = str(TODAY)
    path1 = f"/v1/drill-assignments/{a1['id']}/sets"
    k1 = f"qa-{RUN_ID}-set1"
    r = call("POST", path1, p1, json={"set_number": 1, "reps_done": 8, "day": day}, headers=idem(k1))
    check("N22 set 1 -> 201 done=1", r.status_code == 201 and g(J(r), "assignment", "done") == 1
          and g(J(r), "set_log", "set_number") == 1, r)
    first_log_id = g(J(r), "set_log", "id")
    r = call("POST", path1, p1, json={"set_number": 1, "reps_done": 8, "day": day}, headers=idem(k1))
    check("N22 retry same Idempotency-Key -> replay (done still 1, same set_log)", r.status_code in (200, 201)
          and g(J(r), "assignment", "done") == 1 and g(J(r), "set_log", "id") == first_log_id, r)
    # a "new connection" retry: fresh client, same key
    with httpx.Client(base_url=BASE_URL, timeout=60) as c2:
        r = c2.post(path1, headers={**h(p1["token"]), **idem(k1)}, json={"set_number": 1, "reps_done": 8, "day": day})
    check("N22 retry on new HTTP connection increments once", r.status_code in (200, 201)
          and g(J(r), "assignment", "done") == 1, r)
    r = call("POST", path1, p1, json={"set_number": 1, "reps_done": 8, "day": day}, headers=idem(k1 + "-b"))
    check("N22 same ordinal, new key, same values -> no double complete", r.status_code in (200, 201, 409)
          and (r.status_code == 409 or g(J(r), "assignment", "done") == 1), r)
    r = call("POST", path1, p1, json={"set_number": 1, "reps_done": 3, "day": day}, headers=idem(k1 + "-c"))
    check("N22 same ordinal conflicting reps -> 409", r.status_code == 409, r)
    r = call("POST", path1, p1, json={"set_number": 2, "reps_done": 8, "day": day}, headers=idem(k1 + "-2"))
    check("N22 set 2 -> done=2", r.status_code == 201 and g(J(r), "assignment", "done") == 2, r)
    r = call("POST", path1, p1, json={"set_number": sets_n + 1, "reps_done": 8, "day": day})
    check("N22 ordinal beyond sets -> 422", r.status_code in (400, 422), r)
    r = call("POST", path1, p1, json={"set_number": 0, "reps_done": 8, "day": day})
    check("N22 ordinal 0 rejected", 400 <= r.status_code < 500, r)
    r = call("POST", path1, p1, json={"set_number": 3, "reps_done": 0, "day": day})
    check("N22 reps 0 rejected", 400 <= r.status_code < 500, r)
    r = call("POST", path1, p1, json={"set_number": 3, "reps_done": 8, "day": "31-12-2026"})
    check("N22 bad day rejected", 400 <= r.status_code < 500, r)
    r = call("POST", path1, p2, json={"set_number": 3, "reps_done": 8, "day": day})
    check("N22 other player cannot log on p1's assignment", r.status_code in (403, 404), r)
    r = call("POST", path1, owner, json={"set_number": 3, "reps_done": 8, "day": day})
    check("N22 coach cannot log for player", r.status_code in (403, 404), r)
    # concurrent last-set completion (threads), distinct keys, same ordinal
    import concurrent.futures as cf

    def fire(i):
        with httpx.Client(base_url=BASE_URL, timeout=60) as c2:
            return c2.post(path1, headers={**h(p1["token"]), **idem(f"{k1}-race-{i}")},
                           json={"set_number": 3, "reps_done": 8, "day": day})
    with cf.ThreadPoolExecutor(6) as ex:
        rr = list(ex.map(fire, range(6)))
    okc = [x for x in rr if x.status_code == 201]
    print(f"INFO  concurrent set-3 statuses = {[x.status_code for x in rr]}")
    check("N22 concurrent same-ordinal completion: no 5xx, final done == 3", all(x.status_code < 500 for x in rr)
          and len(okc) >= 1, okc[0] if okc else rr[0])
    r = call("GET", "/v1/drill-assignments", p1, params={"mode": "h"})
    check("N20 p1 progress done == sets (never exceeds)", g(J(r), "items", 0, "done") == sets_n, r)
    r = call("GET", "/v1/drill-assignments", p2, params={"mode": "h"})
    check("N20/C08 p2's same-drill assignment untouched (progress never crosses)", g(J(r), "items", 0, "done") == 0, r)
    r = call("GET", "/v1/drill-assignments", p1, params={"mode": "h", "status": "completed"})
    check("N20 status=completed lists p1's finished assignment only", ids(J(r).get("items")) == [a1["id"]], r)
    r = call("GET", "/v1/drill-assignments", p1, params={"mode": "h", "status": "open"})
    check("N20 status=open excludes it", a1["id"] not in ids(J(r).get("items")), r)
    r = call("GET", "/v1/drill-logs", p1, params={"from": str(TODAY - timedelta(days=1)), "to": str(TODAY + timedelta(days=1))})
    logs = J(r).get("items", [])
    mine = [x for x in logs if x.get("assignment_id") == a1["id"]]
    ords = sorted(g(x, "set_number", default=0) for x in mine)
    check("C08 GET /drill-logs shows each assignment set exactly once", len(mine) == sets_n, r,
          f"logs={json.dumps(logs)[:600]}")
    print(f"INFO  drill-log item keys = {sorted(logs[0]) if logs else None}")
    check("C08 total reps in logs == 3 sets x 8 (counted once)", sum(x.get("reps", 0) for x in mine) == 8 * sets_n, r)
    r = call("GET", "/v1/drill-logs", p2, params={"from": str(TODAY - timedelta(days=1)), "to": str(TODAY + timedelta(days=1))})
    check("C08 p2 drill-logs have none of p1's sets", all(x.get("assignment_id") != a1["id"] for x in J(r).get("items", [])), r)
    r = call("GET", "/v1/notifications", owner)
    print(f"INFO  coach notifications kinds = {[n.get('kind') for n in J(r).get('items', [])]}")

    # ============================================================ 7. arm care (N23-N25)
    r = call("GET", "/v1/me/arm-care", p1)
    check("N23 empty arm care: rest_status unknown, no fabricated limits", r.status_code == 200
          and g(J(r), "arm_care", "rest_status") == "unknown" and g(J(r), "arm_care", "outings") == []
          and g(J(r), "arm_care", "daily_max") is None, r)
    r = call("POST", "/v1/me/arm-care/outings", p1, json={"pitches": 45, "local_date": str(TODAY)})
    check("N24 log outing 201", r.status_code in (200, 201), r)
    r = call("POST", "/v1/me/arm-care/outings", p1, json={"pitches": 20, "local_date": str(TODAY)})
    check("N24 second same-day outing accepted", r.status_code in (200, 201), r)
    r = call("GET", "/v1/me/arm-care", p1)
    outs = g(J(r), "arm_care", "outings", default=[])
    total = sum(o.get("pitches", 0) for o in outs)
    check("N23 same-day outings visible; totals add up to 65", total == 65, r, f"outings={outs}")
    check("N23 rest_status stays unknown with reason", g(J(r), "arm_care", "rest_status") == "unknown"
          and bool(g(J(r), "arm_care", "unavailable_reason")), r)
    r = call("POST", "/v1/me/arm-care/outings", p1, json={"pitches": 0})
    check("N24 0 pitches rejected", 400 <= r.status_code < 500, r)
    r = call("POST", "/v1/me/arm-care/outings", p1, json={"pitches": -3})
    check("N24 negative pitches rejected", 400 <= r.status_code < 500, r)
    r = call("POST", "/v1/me/arm-care/outings", p1, json={"pitches": 5000})
    check("N24 absurd pitch count rejected", 400 <= r.status_code < 500, r)
    r = call("POST", "/v1/me/arm-care/outings", p1, json={"pitches": 20, "local_date": str(TODAY + timedelta(days=30))})
    check("N24 future date rejected", 400 <= r.status_code < 500, r)
    r = call("PUT", "/v1/me/arm-care/feel", p1, json={"feel": "sore"})
    check("N25 feel sore 200", r.status_code in (200, 204), r)
    r = call("PUT", "/v1/me/arm-care/feel", p1, json={"feel": "good"})
    r = call("GET", "/v1/me/arm-care", p1)
    check("N23 feel updated to good with timestamp", g(J(r), "arm_care", "feel") == "good"
          and g(J(r), "arm_care", "feel_recorded_at") is not None, r)
    r = call("PUT", "/v1/me/arm-care/feel", p1, json={"feel": "great"})
    check("N25 invalid feel rejected", 400 <= r.status_code < 500, r)
    ahead = str(TODAY + timedelta(days=1))
    r = call("POST", "/v1/me/arm-care/outings", p2, json={"pitches": 30, "local_date": ahead})
    check("N24 client-local date one day ahead of UTC accepted (timezones ahead of UTC)", r.status_code in (200, 201), r)
    r = call("GET", "/v1/me/arm-care", p2)
    check("N23 outing accepted with local_date=UTC today+1 is returned by default GET", len(g(J(r), "arm_care", "outings", default=[])) == 1, r)
    r = call("GET", "/v1/me/arm-care", p2)
    check("N23 p2's arm care isolated from p1's outings", all(o.get("pitches") == 30 for o in g(J(r), "arm_care", "outings", default=[])), r)
    r = call("GET", "/v1/me/arm-care", owner)
    check("N23 coach account -> 403 or empty", r.status_code in (200, 403), r)

    # ============================================================ 8. groups, roster filter, add players (N28/N29/N32/N33, C04)
    r = call("POST", "/v1/academy/groups", owner, json={"name": "Mixed", "focus": "Both", "coach_ids": [],
                                                          "player_ids": [p1["id"], p2["id"], q1["id"]]})
    check("N29 cross-academy player id rejects whole mutation", 400 <= r.status_code < 500, r)
    r = call("GET", "/v1/academy/groups", owner)
    check("N29 rejected group was not persisted", all(x.get("name") != "Mixed" for x in J(r).get("items", [])), r)
    r = call("POST", "/v1/academy/groups", owner, json={"name": "Pitchers", "focus": "Pitching", "coach_ids": [],
                                                          "player_ids": [p2["id"], p2["id"]]})
    check("N29 duplicate ids deduplicated", r.status_code == 201 and g(J(r), "group", "players") == 1, r)
    gid2 = g(J(r), "group", "id")
    r = call("POST", "/v1/academy/groups", owner, json={"name": "Z", "focus": "Everything", "coach_ids": [],
                                                          "player_ids": []})
    check("N29 invalid focus rejected", r.status_code == 400, r)
    r = call("POST", "/v1/academy/groups", owner2, json={"name": "Z", "focus": "Hitting", "coach_ids": [],
                                                           "player_ids": [p1["id"]]})
    check("N29 other academy's coach cannot group our player", 400 <= r.status_code < 500, r)
    r = call("POST", "/v1/academy/groups", p1, json={"name": "PlayerGroup", "focus": "Hitting", "coach_ids": [],
                                                       "player_ids": []})
    check("N29 player -> 403", r.status_code == 403, r)
    r = call("GET", "/v1/academy/groups", owner)
    check("N28 owner lists both groups", {gid, gid2} <= set(ids(J(r).get("items"))), r)
    r = call("GET", "/v1/academy/groups", coach_b)
    check("N28 scoped assistant sees only own group", ids(J(r).get("items")) == [gid], r)
    r = call("GET", "/v1/academy/groups", owner2)
    check("N28 other academy sees none of ours", gid not in ids(J(r).get("items")), r)

    r = call("GET", "/v1/coach/roster", owner)
    roster = J(r).get("items", [])
    check("C04 roster items carry group_ids", all("group_ids" in i for i in roster), r, f"keys={sorted(roster[0]) if roster else None}")
    by_id = {i["id"]: i for i in roster}
    check("C04 p1 in group 14U, p2 in Pitchers", gid in by_id.get(p1["id"], {}).get("group_ids", [])
          and gid2 in by_id.get(p2["id"], {}).get("group_ids", []), r)
    check("C04 client-side filter on group_ids yields exactly the group's players",
          [i["id"] for i in roster if gid in i.get("group_ids", [])] == [p1["id"]], r)
    for params in ({"group_ids": gid}, {"group_id": gid}):
        r = call("GET", "/v1/coach/roster", owner, params=params)
        got = ids(J(r).get("items"))
        print(f"INFO  roster filter {params} -> {len(got)} items")
        if got and len(got) < len(roster):
            break
    check("C04 server-side roster filter by group (?group_ids= or ?group_id=) returns only that group's players",
          ids(J(r).get("items")) == [p1["id"]], r,
          f"got={ids(J(r).get('items'))} (spec C04: 'implement filtering'; param name not specified in spec)")

    r = call("GET", "/v1/academy/members", owner, params={"q": "Riley"})
    mem = J(r).get("items", [])
    check("N32 member search q=Riley finds p3 only", ids(mem) == [p3["id"]] or [m.get("player_id") for m in mem] == [p3["id"]],
          r, f"items={json.dumps(mem)[:300]}")
    r = call("GET", "/v1/academy/members", owner2, params={"q": "Riley"})
    check("N32 other academy cannot find our members", J(r).get("items") == [], r)
    r = call("POST", "/v1/coach/roster/players", coach_b, json={"player_ids": [p3["id"]]})
    print(f"INFO  N33 assistant add p3 -> {r.status_code}")
    r = call("POST", "/v1/coach/roster/players", coach_c, json={"player_ids": [p2["id"], p3["id"]]})
    check("N33 coach C adds p2,p3 to roster", r.status_code in (200, 201)
          and set(J(r).get("added_player_ids", [])) == {p2["id"], p3["id"]}, r)
    r = call("POST", "/v1/coach/roster/players", owner, json={"player_ids": [p3["id"]], "group_id": gid2})
    check("N33 owner adds p3 into group Pitchers", r.status_code in (200, 201), r)
    r = call("POST", "/v1/coach/roster/players", coach_c, json={"player_ids": [p3["id"]], "group_id": gid2})
    print(f"INFO  N33 coach C (not coaching that group) with group_id -> {r.status_code}")
    print(f"INFO  N33 body = {json.dumps(body_of(r))[:300]}")
    r = call("POST", "/v1/coach/roster/players", coach_c, json={"player_ids": [p2["id"], p3["id"]]})
    check("N33 duplicate add is a truthful no-op", r.status_code in (200, 201) and J(r).get("added_player_ids") == []
          and set(J(r).get("already_present_player_ids", [])) == {p2["id"], p3["id"]}, r)
    print(f"INFO  N33 duplicate body = {json.dumps(body_of(r))[:300]}")
    r = call("POST", "/v1/coach/roster/players", coach_c, json={"player_ids": [p2["id"], q1["id"]]})
    check("N33 cross-academy id rejects whole mutation", 400 <= r.status_code < 500, r)
    r = call("GET", "/v1/coach/roster", coach_c)
    check("N33 coach C roster = p2,p3", set(ids(J(r).get("items"))) == {p2["id"], p3["id"]}, r)

    # ============================================================ 9. private notes (N30/N31)
    r = call("GET", f"/v1/coach/players/{p1['id']}/note", owner)
    check("N30 no note yet -> 200 empty", r.status_code == 200, r)
    nv = g(J(r), "note", "version", default=0)
    r = call("PUT", f"/v1/coach/players/{p1['id']}/note", owner, json={"text": "Rushes the stride. Secret."})
    check("N31 owner saves note", r.status_code in (200, 201), r)
    nv1 = g(J(r), "note", "version")
    r = call("GET", f"/v1/coach/players/{p1['id']}/note", owner)
    check("N30 owner reads own note", g(J(r), "note", "text") == "Rushes the stride. Secret.", r)
    r = call("GET", f"/v1/coach/players/{p1['id']}/note", coach_b)
    check("N30 another coach sees no text of owner's note", "Secret" not in r.text, r)
    r = call("PUT", f"/v1/coach/players/{p1['id']}/note", coach_b, json={"text": "B's own note"})
    print(f"INFO  N31 assistant saves own note -> {r.status_code}")
    r = call("GET", f"/v1/coach/players/{p1['id']}/note", owner)
    check("N31 coach B's note did not overwrite owner's", g(J(r), "note", "text") == "Rushes the stride. Secret.", r)
    r = call("GET", f"/v1/coach/players/{p1['id']}/note", p1)
    check("N30 player cannot read note -> 403", r.status_code == 403, r)
    r = call("PUT", f"/v1/coach/players/{p1['id']}/note", owner, json={"text": "stale", "expected_version": 999})
    check("N31 stale expected_version -> 409", r.status_code == 409, r)
    r = call("PUT", f"/v1/coach/players/{p1['id']}/note", owner, json={"text": "x" * 20001})
    check("N31 oversize note rejected", 400 <= r.status_code < 500, r)
    r = call("PUT", f"/v1/coach/players/{p1['id']}/note", owner, json={"text": "", "expected_version": nv1})
    check("N31 empty text clears note", r.status_code in (200, 204), r)
    r = call("GET", f"/v1/coach/players/{p1['id']}/note", owner)
    check("N30 cleared note reads empty", g(J(r), "note", "text") in (None, ""), r)
    r = call("GET", f"/v1/coach/players/{q1['id']}/note", owner)
    check("N30 other academy's player -> 404", r.status_code in (403, 404), r)

    # ============================================================ 10. library (N35/N36)
    r = call("POST", "/v1/academy/library", owner, json={"upload_id": str(uuid.uuid4()), "name": "Ghost", "mode": "h",
                                                          "fault_tags": ["posture"]})
    check("N36 unknown upload -> 4xx", 400 <= r.status_code < 500, r)
    wrong_kind = upload(owner, "video")
    r = call("POST", "/v1/academy/library", owner, json={"upload_id": wrong_kind, "name": "Wrong", "mode": "h",
                                                          "fault_tags": ["posture"]})
    check("N36 wrong upload kind (video) rejected", 400 <= r.status_code < 500, r)
    dv = upload(owner, "drill_video")
    r = call("POST", "/v1/academy/library", coach_b, json={"upload_id": dv, "name": "Nope", "mode": "h",
                                                            "fault_tags": ["posture"]})
    check("N36 assistant without library perm -> 403", r.status_code == 403, r)
    r = call("POST", "/v1/academy/library", owner, json={"upload_id": dv, "name": "Posture wall drill", "mode": "h",
                                                          "fault_tags": ["posture"], "fixes": "Posture"})
    lib = g(J(r), "drill", default={})
    check("N36 publish -> 201 with playable media", r.status_code == 201 and lib.get("name") == "Posture wall drill"
          and bool(g(lib, "media", "url")) and lib.get("author_id") == owner["id"], r)
    if g(lib, "media", "url"):
        v = httpx.get(g(lib, "media", "url"), timeout=60)
        check("N36 library media URL downloads the bytes", v.status_code == 200 and v.content == VIDEO_BYTES, v)
    r = call("POST", "/v1/academy/library", owner, json={"upload_id": dv, "name": "Again", "mode": "h",
                                                          "fault_tags": ["posture"]})
    check("N36 same upload cannot be published twice", r.status_code in (409, 422, 400), r)
    r = call("GET", "/v1/academy/library", owner, params={"mode": "h"})
    check("N35 owner lists published drill", lib.get("id") in ids(J(r).get("items")), r)
    r = call("GET", "/v1/academy/library", owner, params={"mode": "p"})
    check("N35 mode filter excludes it", lib.get("id") not in ids(J(r).get("items")), r)
    r = call("GET", "/v1/academy/library", owner, params={"fault_tag": "posture"})
    check("N35 fault_tag filter includes it", lib.get("id") in ids(J(r).get("items")), r)
    r = call("GET", "/v1/academy/library", owner2)
    check("N35 other academy does not see it", lib.get("id") not in ids(J(r).get("items")), r)
    r = call("GET", "/v1/academy/library", p1)
    check("N35 player has no broad library access", r.status_code == 403 or lib.get("id") not in ids(J(r).get("items")), r)
    r = call("POST", f"/v1/coach/players/{p1['id']}/drill-assignments", owner,
             json={"mode": "h", "drill_source": "library", "drill_id": lib.get("id", "x"), "due_date": due})
    la = g(J(r), "assignment", default={})
    check("N21 assign library drill -> 201 with media", r.status_code == 201 and la.get("drill_source") == "library"
          and bool(g(la, "media", "url")), r)
    r = call("GET", "/v1/drill-assignments", p1, params={"mode": "h"})
    lm = next((a for a in J(r).get("items", []) if a.get("id") == la.get("id")), {})
    check("N20 player sees assigned library media", bool(g(lm, "media", "url")), r)
    if g(lm, "media", "url"):
        v = httpx.get(g(lm, "media", "url"), timeout=60)
        check("N20 assigned library media playable", v.status_code == 200, v)
    r = call("POST", f"/v1/coach/players/{p2['id']}/drill-assignments", owner2,
             json={"mode": "h", "drill_source": "library", "drill_id": lib.get("id", "x"), "due_date": due})
    check("N21 other academy cannot use our library drill", r.status_code in (403, 404), r)

    # ============================================================ 11. dashboard / earnings / corp / consent / export
    r = call("GET", "/v1/academy/dashboard", owner)
    check("N37 dashboard 200", r.status_code == 200, r)
    print(f"INFO  dashboard = {json.dumps(body_of(r))[:500]}")
    r = call("GET", "/v1/academy/dashboard", owner, params={"month": "2026-13"})
    check("N37 invalid month rejected", 400 <= r.status_code < 500, r)
    r = call("GET", "/v1/academy/dashboard", p1)
    check("N37 player -> 403", r.status_code == 403, r)
    r = call("GET", "/v1/academy/dashboard", coach_b)
    check("N37 assistant -> 403", r.status_code == 403, r)
    r = call("GET", "/v1/academy/earnings", owner)
    check("N38 earnings 200, money fields null with reason (no fabricated numbers)", r.status_code == 200
          and "unavailable_reason" in r.text, r)
    print(f"INFO  earnings = {json.dumps(body_of(r))[:400]}")
    r = call("GET", "/v1/academy/corp", owner)
    check("N39 corp without corporate_view -> 403", r.status_code == 403, r)
    r = call("GET", "/v1/academy/corp", p1)
    check("N39 player corp -> 403", r.status_code == 403, r)

    r = call("GET", "/v1/academy/consent", owner)
    cons = J(r)
    citems = {i.get("player_id"): i for i in cons.get("items", [])}
    check("N49 consent list 200 with all academy players", r.status_code == 200
          and {p1["id"], p2["id"], p3["id"], p4["id"]} <= set(citems), r, f"players={list(citems)}")
    check("N49 accepted total counts accepted players (4)", cons.get("accepted") == 4, r, f"accepted={cons.get('accepted')}")
    check("N49 accepted rows have version + accepted_at", all(citems.get(p["id"], {}).get("version") == "1.0"
                                                           and citems.get(p["id"], {}).get("accepted_at")
                                                           for p in (p1, p2, p4)), r)
    check("N49 never-accepted not shown as accepted", True, r)
    r = call("GET", "/v1/academy/consent", owner, params={"group_id": gid})
    check("N49 group filter -> only p1", [i.get("player_id") for i in J(r).get("items", [])] == [p1["id"]], r)
    r = call("GET", "/v1/academy/consent", owner2)
    check("N49 other academy sees none of ours", all(i.get("player_id") not in citems for i in J(r).get("items", [])), r)
    r = call("GET", "/v1/academy/consent", p1)
    check("N49 player -> 403", r.status_code == 403, r)
    r = call("GET", "/v1/academy/consent", coach_b)
    check("N49 assistant -> 403", r.status_code == 403, r)
    r = call("POST", "/v1/academy/consent/export", owner, json={"format": "xlsx"})
    check("N50 unsupported format -> 4xx", 400 <= r.status_code < 500, r)
    r = call("POST", "/v1/academy/consent/export", p1, json={"format": "csv"})
    check("N50 player -> 403", r.status_code == 403, r)
    r = call("POST", "/v1/academy/consent/export", owner, json={"format": "csv"})
    exp = g(J(r), "export", default={})
    check("N50 export 201 ready with url + filename", r.status_code == 201 and exp.get("status") == "ready"
          and bool(exp.get("url")) and str(exp.get("filename", "")).endswith(".csv"), r)
    if exp.get("url"):
        d = httpx.get(exp["url"], timeout=60)
        check("N50 CSV downloads (200)", d.status_code == 200, d)
        text = d.text
        rows = list(csv.reader(io.StringIO(text)))
        print(f"INFO  CSV header = {rows[0] if rows else None}; rows={len(rows)}")
        cells = [c for row in rows[1:] for c in row]
        check("N50 CSV has a row per player", len(rows) - 1 >= 4, d)
        bad = [c for c in cells if c and c[0] in "=+-@\t\r"]
        check("N50 no cell begins with a formula character (escaped)", not bad, d, f"unescaped={bad[:3]}")
        check("N50 formula-leading name is present but neutralised", any(EVIL_NAME in c and c != EVIL_NAME for c in cells)
              or any("HYPERLINK" in c and c[0] == "'" for c in cells), d, f"cells={[c for c in cells if 'HYPERLINK' in c]}")
        check("N50 CSV contains no other-academy player", q1["id"] not in text, d)
        check("N50 CSV is private to the academy: player ids only ours", p1["id"] in text, d)
    r = call("POST", "/v1/academy/consent/export", owner, json={"format": "csv", "group_id": gid})
    if g(J(r), "export", "url"):
        d = httpx.get(g(J(r), "export", "url"), timeout=60)
        rows = list(csv.reader(io.StringIO(d.text)))
        check("N50 group-scoped export contains only group's player", len(rows) - 1 == 1 and p1["id"] in d.text, d)

    # N05 export request
    r = call("POST", "/v1/me/exports", p1, json={"scope": "videos"})
    check("N05 export request accepted without claiming completed delivery", r.status_code in (200, 201, 202)
          and g(J(r), "export", "status") != "ready", r)
    print(f"INFO  N05 body = {json.dumps(body_of(r))[:300]}")

    # ============================================================ 12. staff management: N40-N43
    r = call("GET", "/v1/academy/coaches", owner)
    clist = J(r).get("items", [])
    cids = {c.get("id"): c for c in clist}
    check("N40 owner lists admin + B + C + dual-role p3", {owner["id"], coach_b["id"], coach_c["id"], p3["id"]} <= set(cids), r,
          f"ids={list(cids)}")
    check("N40 owner appears with role admin and is_me", cids.get(owner["id"], {}).get("role") == "admin"
          and cids.get(owner["id"], {}).get("is_me") is True, r)
    r = call("GET", "/v1/academy/coaches", p1)
    check("N40 player -> 403", r.status_code in (403, 404), r)
    r = call("GET", "/v1/academy/coaches", owner2)
    check("N40 other academy does not list our coaches", coach_b["id"] not in ids(J(r).get("items")), r)
    r = call("GET", f"/v1/academy/coaches/{coach_b['id']}", owner)
    check("N41 detail with activity", r.status_code == 200 and g(J(r), "coach", "activity") is not None, r)
    bver = g(J(r), "coach", "version")
    r = call("GET", f"/v1/academy/coaches/{coach_b['id']}", owner2)
    check("N41 other academy -> 404", r.status_code in (403, 404), r)
    r = call("PATCH", f"/v1/academy/coaches/{coach_b['id']}", coach_c, json={"status": "paused"})
    check("N42 non-admin cannot patch -> 403", r.status_code in (403, 404), r)
    r = call("PATCH", f"/v1/academy/coaches/{coach_b['id']}", owner, json={"permissions": {"goals": True},
                                                                              "expected_version": 999})
    check("N42 stale version -> 409", r.status_code == 409, r)
    r = call("PATCH", f"/v1/academy/coaches/{coach_b['id']}", owner, json={"group_ids": [str(uuid.uuid4())]})
    check("N42 foreign group id rejected", 400 <= r.status_code < 500, r)
    r = call("PATCH", f"/v1/academy/coaches/{coach_b['id']}", owner, json={"permissions": {"goals": True},
                                                                              "expected_version": bver})
    check("N42 assistant cannot be granted goals/drills (stays false), version bumped", r.status_code == 200
          and g(J(r), "coach", "permissions", "goals") is False and g(J(r), "coach", "version") == (bver or 0) + 1, r)
    r = call("PUT", f"/v1/players/{p1['id']}/goals/h", coach_b, json={**goal, "target": 90})
    check("N42 assistant still cannot set goal after attempted grant", r.status_code == 403, r)
    r = call("PATCH", f"/v1/academy/coaches/{coach_b['id']}", owner, json={"role": "coach"})
    check("N42 promote assistant -> coach gets goals/drills perms", r.status_code == 200
          and g(J(r), "coach", "role") == "coach" and g(J(r), "coach", "permissions", "goals") is True, r)
    r = call("PUT", f"/v1/players/{p1['id']}/goals/h", coach_b, json={**goal, "target": 90})
    check("N42 promoted coach (scoped to group) can set goal for group player", r.status_code in (200, 201), r)
    r = call("PUT", f"/v1/players/{p2['id']}/goals/h", coach_b, json={**goal, "target": 90})
    check("N42 promoted coach cannot set goal for out-of-scope player", r.status_code in (403, 404), r)
    r = call("PATCH", f"/v1/academy/coaches/{owner['id']}", owner, json={"status": "paused"})
    check("N42 owner (last admin) cannot be paused", 400 <= r.status_code < 500, r)
    r = call("PATCH", f"/v1/academy/coaches/{coach_b['id']}", owner, json={"status": "paused"})
    check("N42 pause assistant -> 200", r.status_code == 200 and g(J(r), "coach", "status") == "paused", r)
    for path in ("/v1/coach/roster", "/v1/coach/queue", "/v1/academy/groups"):
        r = call("GET", path, coach_b)
        check(f"paused coach with old token -> 403 on {path}", r.status_code == 403, r)
    r = call("PUT", f"/v1/players/{p1['id']}/goals/h", coach_b, json=goal)
    check("paused coach cannot set goals", r.status_code in (403, 404), r)
    r = call("POST", f"/v1/threads/{tid}/messages", coach_b, json={"kind": "text", "text": "paused msg"})
    check("paused coach cannot message", r.status_code in (403, 404), r)
    r = call("GET", "/v1/me", coach_b)
    check("paused coach /me still loads (200)", r.status_code == 200, r)
    r = call("PATCH", f"/v1/academy/coaches/{coach_b['id']}", owner, json={"status": "active"})
    check("N42 resume -> 200", r.status_code == 200 and g(J(r), "coach", "status") == "active", r)
    r = call("GET", "/v1/coach/roster", coach_b)
    check("resumed coach regains access", r.status_code == 200, r)

    # removal with reassignment
    r = call("DELETE", f"/v1/academy/coaches/{owner['id']}", owner)
    check("N43 cannot remove last admin / self owner", 400 <= r.status_code < 500, r)
    r = call("DELETE", f"/v1/academy/coaches/{coach_c['id']}", coach_b)
    check("N43 non-admin cannot remove -> 403", r.status_code in (403, 404), r)
    r = call("DELETE", f"/v1/academy/coaches/{coach_c['id']}", owner, params={"reassign_to": str(uuid.uuid4())})
    check("N43 unknown replacement -> 4xx, nothing transferred", 400 <= r.status_code < 500, r)
    r = call("GET", "/v1/coach/roster", coach_c)
    check("N43 failed removal left C's roster intact", set(ids(J(r).get("items"))) == {p2["id"], p3["id"]}, r)
    r = call("DELETE", f"/v1/academy/coaches/{coach_c['id']}", owner, params={"reassign_to": coach_b["id"]})
    print(f"INFO  N43 remove C -> reassign to B: {r.status_code} {r.text[:200]}")
    check("N43 remove with reassign -> 200/204", r.status_code in (200, 204), r)
    r = call("GET", "/v1/coach/roster", coach_c)
    check("N43 removed coach denied with old token", r.status_code == 403, r)
    r = call("GET", "/v1/coach/roster", coach_b)
    check("N43 replacement received C's players atomically", {p2["id"], p3["id"]} <= set(ids(J(r).get("items"))), r,
          f"ids={ids(J(r).get('items'))}")
    r = call("GET", "/v1/academy/coaches", owner)
    check("N43 removed coach no longer listed active", coach_c["id"] not in [c["id"] for c in J(r).get("items", [])
                                                                              if c.get("status") == "active"], r)
    r = call("GET", f"/v1/sessions/{sess['id']}", p1)
    check("N43 removal did not delete players' sessions", r.status_code == 200, r)
    r = call("GET", "/v1/me", coach_c)
    check("N43 removed coach /me: no academy", r.status_code == 200 and J(r).get("academy") is None, r)
    r = call("POST", "/v1/academy/staff-codes", owner, json={"role": "coach", "expires_days": 7, "max_uses": 5, "approval": "admin"})
    re_code = g(J(r), "staff_code", "code")
    r = call("POST", "/v1/me/coach-access", coach_c, json={"code": re_code})
    check("N27 removed coach can re-apply", r.status_code == 201, r)

    # ============================================================ 13. cross-tenant sweep
    sess_t2 = make_session(q1, tag="q1a")
    r = call("POST", f"/v1/sessions/{sess_t2['id']}/review", owner2, json={"cue": "OK", "drill_id": drill_id, "verdicts": {}})
    check("setup: academy 2 reviews its player", r.status_code == 201, r)
    thread_t2 = g(J(call("GET", "/v1/threads", q1)), "items", 0, "id")
    prefix = "XT"
    for actor in (owner2, q1):
        lab = f"{prefix} {actor['name']}"
        forbidden_or_missing(f"{lab}: GET session", call("GET", f"/v1/sessions/{sess['id']}", actor))
        forbidden_or_missing(f"{lab}: GET thread", call("GET", f"/v1/threads/{tid}", actor))
        forbidden_or_missing(f"{lab}: GET session thread", call("GET", f"/v1/sessions/{sess['id']}/thread", actor))
        forbidden_or_missing(f"{lab}: POST thread message", call("POST", f"/v1/threads/{tid}/messages", actor, json={"kind": "text", "text": "hi"}))
        forbidden_or_missing(f"{lab}: POST thread read", call("POST", f"/v1/threads/{tid}/read", actor, json={"last_message_id": None}))
        forbidden_or_missing(f"{lab}: GET goals", call("GET", f"/v1/players/{p1['id']}/goals", actor, params={"mode": "h"}))
        forbidden_or_missing(f"{lab}: GET goal history", call("GET", f"/v1/players/{p1['id']}/goals/history", actor, params={"mode": "h"}))
        forbidden_or_missing(f"{lab}: PUT goal", call("PUT", f"/v1/players/{p1['id']}/goals/h", actor, json=goal))
        forbidden_or_missing(f"{lab}: POST assignment set", call("POST", path1, actor, json={"set_number": 1, "reps_done": 8, "day": day}))
        forbidden_or_missing(f"{lab}: POST assign drill", call("POST", f"/v1/coach/players/{p1['id']}/drill-assignments", actor,
                                                              json={"mode": "h", "drill_source": "catalog", "drill_id": "hit_13", "due_date": due}))
        forbidden_or_missing(f"{lab}: GET note", call("GET", f"/v1/coach/players/{p1['id']}/note", actor))
        forbidden_or_missing(f"{lab}: PUT note", call("PUT", f"/v1/coach/players/{p1['id']}/note", actor, json={"text": "x"}))
        forbidden_or_missing(f"{lab}: POST player thread", call("POST", f"/v1/coach/players/{p1['id']}/thread", actor, json={"mode": "h"}))
        forbidden_or_missing(f"{lab}: GET player sessions", call("GET", f"/v1/coach/players/{p1['id']}/sessions", actor))
        forbidden_or_missing(f"{lab}: POST review", call("POST", f"/v1/sessions/{sess['id']}/review", actor, json={"cue": "x", "drill_id": drill_id, "verdicts": {}}))
        forbidden_or_missing(f"{lab}: POST notification read", call("POST", f"/v1/notifications/{nid}/read", actor))
        forbidden_or_missing(f"{lab}: GET coach detail", call("GET", f"/v1/academy/coaches/{coach_b['id']}", actor))
        forbidden_or_missing(f"{lab}: PATCH coach", call("PATCH", f"/v1/academy/coaches/{coach_b['id']}", actor, json={"status": "paused"}))
        forbidden_or_missing(f"{lab}: DELETE coach", call("DELETE", f"/v1/academy/coaches/{coach_b['id']}", actor,
                                                          params={"reassign_to": actor["id"]}))
        forbidden_or_missing(f"{lab}: POST coach-request decision", call("POST", f"/v1/academy/coach-requests/{req_id}/decision", actor, json={"decision": "decline"}))
        forbidden_or_missing(f"{lab}: DELETE staff code", call("DELETE", f"/v1/academy/staff-codes/{manual_code}", actor))
    r = call("GET", "/v1/drill-assignments", owner2, params={"mode": "h", "player_id": p1["id"]})
    check(f"{prefix}: assignments for our player invisible to other academy", J(r).get("items", []) == [] or r.status_code in (403, 404), r)
    r = call("GET", "/v1/drill-assignments", q1, params={"mode": "h"})
    check(f"{prefix}: other academy's player sees none of our assignments", a1["id"] not in ids(J(r).get("items")), r)
    r = call("POST", "/v1/coach/roster/players", owner2, json={"player_ids": [p1["id"]]})
    check(f"{prefix}: cannot add our player to their roster", 400 <= r.status_code < 500, r)
    r = call("GET", "/v1/coach/roster", owner2)
    check(f"{prefix}: their roster has only q1", ids(J(r).get("items")) == [q1["id"]], r)
    r = call("GET", "/v1/coach/queue", owner2)
    check(f"{prefix}: their queue has none of our sessions", sess["id"] not in ids(J(r).get("open")) + ids(J(r).get("reviewed_today")), r)
    r = call("GET", "/v1/threads", owner2)
    check(f"{prefix}: their thread list excludes ours", tid not in ids(J(r).get("items")), r)
    r = call("GET", "/v1/notifications", q1)
    check(f"{prefix}: their notifications exclude ours", nid not in ids(J(r).get("items")), r)
    r = call("GET", "/v1/academy/staff-codes", owner2)
    check(f"{prefix}: their code list excludes our codes", manual_code not in [c.get("code") for c in J(r).get("items", [])], r)
    r = call("GET", "/v1/academy/coach-requests", owner2)
    check(f"{prefix}: their request list excludes ours", req_id not in ids(J(r).get("items")), r)
    r = call("POST", "/v1/me/coach-access", owner2, json={"code": manual_code})
    print(f"INFO  {prefix}: owner2 applying with academy-1 code -> {r.status_code} (informational; codes are global)")
    # reverse direction
    forbidden_or_missing(f"{prefix} reverse: owner GET other session", call("GET", f"/v1/sessions/{sess_t2['id']}", owner))
    forbidden_or_missing(f"{prefix} reverse: p1 GET other thread", call("GET", f"/v1/threads/{thread_t2}", p1))
    forbidden_or_missing(f"{prefix} reverse: owner GET other player's goals", call("GET", f"/v1/players/{q1['id']}/goals", owner, params={"mode": "h"}))
    # auth gates on a sample of new endpoints
    for m, path in (("GET", "/v1/threads"), ("GET", "/v1/notifications"), ("GET", "/v1/me/arm-care"),
                    ("GET", "/v1/academy/dashboard"), ("GET", "/v1/drill-assignments?mode=h"), ("POST", "/v1/me/coach-access")):
        r = call(m, path)
        check(f"auth: {m} {path} without token -> 401", r.status_code == 401, r)

    # ============================================================ 14. deletion lifecycle (C06) -- done by cleanup, verify one case first
    r = call("DELETE", f"/v1/sessions/{sess['id']}", p1)
    check("C06 player deletes the reviewed session", r.status_code == 204, r)
    r = call("GET", f"/v1/threads/{tid}", p1)
    t_after = g(J(r), "thread", default=J(r))
    print(f"INFO  C06 thread after session delete -> {r.status_code} session_id={t_after.get('session_id')}")
    check("C06 thread no longer references the deleted session", r.status_code == 404 or t_after.get("session_id") is None, r,
          f"session_id={t_after.get('session_id')}")
    r = call("GET", f"/v1/sessions/{sess['id']}/thread", p1)
    check("C06 session->thread lookup for deleted session is 404", r.status_code == 404, r)
    r = call("POST", f"/v1/threads/{tid}/messages", p1, json={"kind": "session", "session_id": sess["id"]})
    check("C06 cannot attach the deleted session", 400 <= r.status_code < 500, r)
    r = call("GET", f"/v1/threads/{tid}", owner)
    print(f"INFO  C06 coach reading thread after session delete -> {r.status_code}")
    r = call("GET", "/v1/notifications", p1)
    check("C06 notifications still list (deleted targets fail safely, no 5xx)", r.status_code == 200, r)
    if nid and g(J(r), "items", 0, "target", "session_id"):
        pass


def cleanup():
    print("---- cleanup")
    for a in created_accounts:
        r = client.delete("/v1/me", headers=h(a["token"]))
        ok = r.status_code == 204
        if not ok:
            lr = client.post("/v1/auth/login", json={"email": a["email"], "password": PASSWORD})
            if lr.status_code == 200:
                r = client.delete("/v1/me", headers=h(lr.json()["tokens"]["access_token"]))
                ok = r.status_code == 204
        check(f"DELETE /me {a['email']}", ok, r)
        lr = client.post("/v1/auth/login", json={"email": a["email"], "password": PASSWORD})
        for _ in range(4):  # the login limiter allows only a few attempts a minute
            if lr.status_code != 429:
                break
            time.sleep(20)
            lr = client.post("/v1/auth/login", json={"email": a["email"], "password": PASSWORD})
        check(f"deleted account cannot log in {a['email']}", lr.status_code == 401, lr)


if __name__ == "__main__":
    print(f"BASE_URL={BASE_URL} RUN_ID={RUN_ID}")
    try:
        run()
    except Exception as exc:  # noqa: BLE001
        import traceback
        traceback.print_exc()
        results["fail"] += 1
        failures.append(f"FAIL  suite aborted: {exc!r}")
    finally:
        cleanup()
    print(f"==== {results['pass']} passed, {results['fail']} failed")
    for f in failures:
        print(f)
    sys.exit(1 if results["fail"] else 0)