File size: 63,492 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440

Cognivision Baseball Backend Specification
 · 
Single source of truth for the backend team: how the React Native app works today, what it stores, and every API needed to move it from a local-first prototype to a connected product. Written from the actual codebase; anything not defined in the app is marked Requires Clarification.
1. Application overview
Cognivision Baseball is a mobile app (React Native 0.88, iOS and Android) that lets a baseball player film one swing or one pitch, mark four reference points on the clip, and get a scored breakdown of their mechanics with one cue and one drill to work on. Coaches run a team: players join with a code, every analysis a player runs lands in the coach's review queue, and the coach's verdict, cue and drill replace the app's defaults on the player's screens.
Today the app has no backend. Everything lives in a single JSON document in AsyncStorage on the device (src/store): accounts with plaintext passwords, teams, sessions, drill logs and reviews. A coach and their players only "share" data when they use the same phone. The analysis engine (src/store/engine.ts) is a deterministic simulation: it produces plausible, improving numbers from the athlete's profile, the marked frames and practice history. There is no pose-estimation model yet. The backend's job is to replace the local store with real accounts, make teams multi-device, store video, and host the analysis pipeline.
Modules
 | 
Module | 
Code | 
Responsibility | 
Backend needed
 | 
Auth | 
screens/auth, AppContext.signUp/signIn/signOut/setRole | 
Email + password accounts, role (player or coach), persisted session | 
Yes
 | 
Onboarding | 
screens/onboarding | 
Focus (hitting / pitching / both), athlete profile, join team by code, coach team setup and invite | 
Yes
 | 
Capture and marking | 
GuideScreen, SubjectScreen, ContactFrameScreen, modules/contact-audio | 
Record or import a clip, say whose swing it is, mark contact, stride start, stride end and pitcher direction; contact is detected from the clip's audio on-device | 
Upload only
 | 
Analysis | 
store/engine.ts, AnalyzingScreen | 
Produce a session: score, phase scores, 10 metrics with bands, fix order, cue and drill | 
Yes, the real pipeline
 | 
Results | 
ResultScreen, RecapScreen, PhaseScreen | 
Score, deltas vs last rep, fix-first card, metric list, clip playback anchored to marked moments, per-phase detail | 
Read APIs
 | 
Practice | 
HomeScreen, DrillsScreen, DrillScreen, HistoryScreen | 
Drill of the day, logging sets, week streaks, score trend and ranges | 
Yes
 | 
Coach | 
screens/coach, ReviewScreen | 
Roster, per-player history, review queue, sending verdicts + cue + drill | 
Yes
 | 
Profile and plan | 
ProfileScreen, EditProfileScreen | 
Athlete data, units, team membership, private-video toggle, free / pro plan (3 analyses a week on free) | 
Yes, incl. payments
 | 
Local store | 
store/*, state/AppContext.tsx | 
Persistence, migrations, sample data for dev builds | 
Replaced by API client + cache
How the parts connect
One React context (AppContext) exposes the whole store to every screen: the signed-in account, the derived team, sessions, drill logs, roster and queue, plus the actions listed in section 5. Screens never talk to storage directly; they call context actions, which mutate the in-memory document and a debounced writer saves it. A backend client can be dropped in behind the same context API, which is why this document maps each action to an endpoint rather than each screen to a fetch call.
Only the highlighted box changes on the app side; every screen keeps calling the same store API. The worker writes results back to Postgres and the push service tells the phone to refresh.
2. Roles and the current data model
Two roles exist and are fixed at onboarding: player and coach. A coach can still film their own reps (the app tells them so), but the coach tabs expose roster, queue and team only. There is no admin, parent or organisation role; the parental-consent notice on the invite screen is copy only (see section 13).
These are the exact shapes persisted today (src/store/types.ts). Field names are kept verbatim so the backend can mirror them; types are TypeScript.
 | 
Entity | 
Fields | 
Notes
 | 
Account | 
id, email, password, role: 'player' | 'coach', focus: 'h' | 'p' | 'both', profile: Athlete, unit: 'imperial' | 'metric', plan: 'free' | 'pro', teamCode: string | null, privateVideos: boolean, createdAt | 
Password is stored in plaintext locally; the backend must hash. teamCode is how a player belongs to a team; a coach is linked to a team through Team.coachId instead.
 | 
Athlete | 
name, age: number | null, heightCm, weightKg, bats: 'L' | 'R' | 'S', throws: 'L' | 'R', level: 'Youth' | 'High school' | 'College' | 'Adult' | 
Embedded in the account as profile, and copied into every session as athlete (the person on camera, which may not be the owner). Validation: age 5 to 70, name at least 2 characters when required, height and weight required only when the subject is someone else.
 | 
Team | 
code (e.g. KDA-4821: up to 3 initials + 4 digits), name, coachId, coachName, coaching: 'h' | 'p' | 'both', createdAt | 
One team per coach. Creating a team again replaces the coach's previous team.
 | 
Session | 
id, ownerId, athlete, isSelf, mode: 'h' | 'p', createdAt, videoUri, thumbUri, durationSec, contactSec, contactFrame, contactOffset, strideStartFrame, strideEndFrame, strideStartSec, strideEndSec, pitcherDir: {from:[x,y], to:[x,y]} | null, score, phases: [name, score][], weak, metrics: Metric[], fixOrder: string[], review: Review | null | 
One analysed rep. Frames assume 30 fps (FPS = 30 in src/figures/motion.ts). contactOffset = frames the user moved contact away from the suggestion. pitcherDir points are fractions (0..1) of the displayed frame. weak is the lowest-scoring phase name.
 | 
Metric | 
key, name, value (formatted, e.g. 18°), raw, band: {min, max, lo, hi, v, grade}, target, why, drill, pose, phase, grade: 'g' | 'b' | 'o' | 
10 per session (8 simulated + 2 timing metrics measured from the marked frames). Grade: g (in range, score 85+), b (60 to 84), o (under 60).
 | 
Review | 
coachId, coachName, cue, drill, verdicts: Record<metricKey, 'agree' | 'change' | 'later'>, at | 
Attached to a session. A session has at most one review; sending again overwrites.
 | 
DrillLog | 
id, ownerId, mode, drill (name), day (YYYY-MM-DD local), sets (always 1), reps, at | 
One row per logged set.
 | 
Persisted (root) | 
version: 1, accounts[], teams[], sessions[], drills[], authUserId, seenContactTour | 
The whole device store. seenContactTour is a per-device UI flag.
Derived data the app computes client-side
team for the signed-in user: by coachId for coaches, by teamCode for players.
roster: player accounts whose teamCode equals the coach's team code.
queue: roster sessions with isSelf = true and no review, oldest first. Reviewed today = roster sessions reviewed since local midnight.
analysesThisWeek: the owner's sessions created in the last 7 days (rolling, includes "someone else's" reps); analysesLeft = 3 - analysesThisWeek on the free plan, unlimited on pro.
mySessions(mode): the owner's own (isSelf) sessions for a mode, newest first. Sessions filmed for someone else never appear in Home, History, Drills or the coach queue.
setsToday(drill): drill logs for that drill name with today's day.
Session title ("Swing 4", "Pitch 2"): ordinal among the same owner, mode and athlete name, oldest = 1.
The backend should own all of these so they are consistent across devices; section 7 gives each one an endpoint or a response field.
3. End-to-end user journeys
Every journey below is implemented and working on-device today. Where a step says backend, that is the call the backend will take over (section 7); the UI behaviour does not change.
3.1 Launch
The store loads from AsyncStorage (migrations run: sessions get stride and direction defaults, orphaned teams are dropped). A spinner shows until it is ready.
No signed-in user: Welcome (animated hero, Create account, Sign in; debug builds also show "Load sample data").
Signed-in player: straight to Player tabs. Signed-in coach: Coach tabs. Backend: restore the session from a stored token and fetch the account.
3.2 Player onboarding
Sign up: email (regex-validated) and password (8+ characters). Apple and Google buttons exist but create a placeholder local account (user<ts>@social.local). Duplicate email shows "An account with this email already exists." Backend: register, social sign-in.
Role: "I'm a player" or "I'm a coach". Saved on the account; the copy says it cannot be changed later.
Focus: hitting, pitching or both. Sets which mode Home opens on and which modes History and Drills can switch between.
About you: age (required), height and weight (optional here), bats, throws, level, with an imperial / metric toggle. Stored metric on the account.
Coach code: typing a 6+ character code looks the team up live and shows its name and coach; "Join" sets teamCode, "Skip for now" goes on. Either way the stack resets to Player tabs. Backend: team lookup and join.
3.3 Capture and marking (the core loop)
Home shows the last rep (score, delta vs the previous rep, fix-first), the free-plan counter (3 a week), today's drill and the Analyze button. On the free plan with 0 left, Analyze shows an alert that links to Profile.
Whose swing is this? "My swing" uses the player's own profile (a warning appears if height or weight are missing, with a link to Edit profile). "Someone else's" opens the athlete form and requires name, age, height and weight. The choice sets subject.
Film: tips, then Record (native camera, back lens, 12 s limit, not saved to Photos) or Choose a video (library). Clips over 60 s are refused with "Clip too long". Camera permission is requested on Android; a denied permission shows a Settings prompt. The chosen file becomes clip (local URI + duration). Backend: nothing yet; the upload happens after marking.
Mark contact (step 1 of 4). For hitting, the clip's audio is scanned on-device and the sharpest onset becomes the suggested frame, shown as "Detected contact" (the UI never says audio). Below 0.5 confidence or with no audio track it falls back to a fixed fraction of the clip (72%) labelled "Suggested". Pitching always uses the fixed fraction (74%). Controls: drag the video to jog, scrub a 9-frame filmstrip, hold 1-frame buttons, "Use the suggested frame". First visit shows a 6-step tutorial.
Foot lift (step 2) and Foot plant (step 3): no suggestion; the playhead starts at the clip start (then at the foot-lift mark) and the player scrubs forward. Order is enforced: lift < plant < contact, frames outside the allowed range are dimmed. Pitching labels: Leg lift and Foot strike.
Direction (step 4): two taps on the contact frame, beside the batter then toward the pitcher, make a draggable arrow. Confirm is disabled until both points exist and the arrow is at least 8% of the frame long. Pitching: pitcher then plate.
Confirm creates the session: a contact-frame thumbnail is extracted, addSession runs the engine, and the app replaces the marking screen with Analyzing (4 fake steps, 3.2 s), then Result. Backend: upload the clip and the marks, start analysis, poll or push the result.
3.4 Results and practice
Result: thumbnail tile (opens Recap), the three marked moments and the direction, score with delta pill and "First rep" badge, "Fix this first" card (metric, why, cue), Start drill, phase scores (each opens Phase), findings split into To improve / Going well, coach status (No coach yet / Pending / Reviewed), Share (native share sheet), Delete (confirmation alert).
Recap: real playback of the clip at 0.25x, 0.5x or 1x, a slider, and phase chips that jump to the marked moments. Sessions without a video show the demo figure.
Drill: the drill for the top fix (or the coach's drill), the cue, a rep counter up to 8 and "Log set n" up to 3 sets a day. Each set writes a DrillLog. 3 sets shows "Drill complete" and goes back.
Drills tab: today's drill with Due today / Done, drills for the other fixes, and a 7-day row of dots from the logs.
History tab: mode switch, 7D / 30D / All, a score trend chart, Best, Average and weekly Streak, and the session list with the top fix and Reviewed badges.
Profile tab: focus segment, Body & stats and Units (both open Edit profile), Team (join by code, or Leave with confirmation), Email, Plan (an alert toggles free / pro; billing is not connected), Keep my videos private switch, Sign out (confirmation, resets to Welcome).
3.5 Coach onboarding
Sign up, choose "I'm a coach" (bug fixed on 2026-10-22: the role used to be lost here).
Set up your team: team name, coach name (pre-filled from the profile), what you coach. Creates the team with a generated code and goes to Invite.
Invite: the code in large type, Copy (clipboard + toast), Share (native sheet with a join message), a notice about under-18 consent, and "Go to my roster", which resets to Coach tabs. Without a team the screen shows "No team yet" with a Create team button.
3.6 Coach review loop
A player on the team confirms a rep. It appears in the coach's Queue (oldest first, with the player's name, the top finding and relative time) and the Roster card shows the open count.
Roster: every player with their last score, delta, a flag (Not filmed yet, Not filmed in N days, Stuck when the last three scores have not improved) and a To review badge; filter All / Hitting / Pitching. Tapping a player opens Player (their trend, a recurring-issue notice when the same top fix repeats, and their session list).
Review: the clip, score, each AI finding with Agree / Change / Not now, an editable cue (pre-filled), a drill chip picked from the findings' drills. "Send to <first name>" stores the review; unanswered findings are sent without a verdict.
The player's Result, Drill and Home now show the coach's cue and drill and a Reviewed badge; the session leaves the queue and appears under Reviewed today. Backend: the review must sync to the player's device, ideally with a push notification.
Edge cases handled in the UI today
A session that was deleted while open shows "This session is gone" on Result, Recap, Phase and Review.
A player who left the team shows "Player not on your team" on the coach's Player screen.
Nothing flagged on a rep shows "Everything is in range" and the coach can still send a cue.
Frame extraction failures show a timestamp cell in the filmstrip instead of a spinner.
Reduce-motion settings disable the hero animation.
4. Screen-by-screen reference
26 screens: a native stack (RootNavigator) with two native tab bars inside it. Route names are the ones in src/navigation/types.ts. "Reads" and "Writes" name the store data each screen touches; section 10 maps them to endpoints.
 | 
Route | 
Screen | 
Shows | 
Actions and navigation | 
Reads | 
Writes
 | 
Welcome | 
WelcomeScreen | 
Animated hero, tagline | 
Create account (SignUp), Sign in (SignIn), dev-only Load sample data | 
none | 
sample store (dev)
 | 
SignUp | 
SignUpScreen | 
Email, password (show/hide), Apple and Google buttons | 
Continue (Role), Sign in link | 
accounts (duplicate check) | 
new Account, authUserId
 | 
SignIn | 
SignInScreen | 
Email, password, Forgot password (alert only) | 
Sign in resets to Player or Coach tabs; Create an account link | 
accounts | 
authUserId, mode, subject
 | 
Role | 
RoleScreen | 
Player / Coach choice | 
Continue (CoachSetup or ObFocus); back disabled | 
user | 
account.role
 | 
ObFocus | 
FocusScreen | 
Hitting / Pitching / Both choices with figures | 
Continue (ObProfile) | 
focus | 
account.focus, mode
 | 
ObProfile | 
ProfileSetupScreen | 
Athlete form (age, height, weight, bats, throws, level, units) | 
Continue (ObCoach); age required | 
profile, unit | 
account.profile, account.unit
 | 
ObCoach | 
CoachCodeScreen | 
Code field with live team lookup | 
Join <team> (sets teamCode), Skip for now; both reset to PlayerTabs | 
teams | 
account.teamCode
 | 
CoachSetup | 
CoachSetupScreen | 
Team name, coach name, coaching pick | 
Create team (CoachInvite) | 
profile | 
new Team (replaces coach's old one), account.profile.name, account.focus
 | 
CoachInvite | 
CoachInviteScreen | 
Team code, name, Copy, Share, consent notice | 
Go to my roster (reset to CoachTabs); no team: Create team (CoachSetup) | 
team | 
none
 | 
PlayerTabs / Home | 
HomeScreen | 
Greeting, last rep card, free counter, Today's drill, coach notice | 
Analyze (Subject, or limit alert), last rep (Result), drill (Drill), All drills (Drills tab), avatar (Profile tab) | 
mySessions, analysesLeft, user.plan, team, setsToday | 
none
 | 
PlayerTabs / History | 
HistoryScreen | 
Mode switch, 7D/30D/All, trend chart, Best/Average/Streak, session list | 
Session row (Result), Analyze (Subject) | 
mySessions, sessions | 
mode
 | 
PlayerTabs / Drills | 
DrillsScreen | 
Today's drill with Due/Done, other fixes, 7-day dots | 
Drill card and rows (Drill) | 
mySessions, drills, setsToday | 
mode
 | 
PlayerTabs / Profile | 
ProfileScreen | 
Name, plan badge, focus segment, Athlete, Team, Account, Sign out | 
Body & stats and Units (EditProfile), Join team, Leave team (alert), Plan (alert toggle), private videos switch, Sign out (alert, reset to Welcome) | 
user, team, profile, unit, focus | 
account.focus, teamCode, plan, privateVideos, authUserId
 | 
EditProfile (modal) | 
EditProfileScreen | 
Athlete form with name, privacy notice | 
Save (goBack), Cancel | 
profile, unit | 
account.profile, account.unit
 | 
Subject | 
SubjectScreen | 
My swing / Someone else's, athlete form for the latter, missing-body warning | 
Continue to filming (Guide), Add height and weight (EditProfile) | 
profile | 
subject (in-memory)
 | 
Guide | 
GuideScreen | 
Filming tips, Record, Choose a video | 
Record (camera) or Choose (library), then ContactFrame; alerts for permission, length, errors | 
mode | 
clip (in-memory)
 | 
ContactFrame | 
ContactFrameScreen | 
4-step marker: contact, foot lift, foot plant, direction; filmstrip, jog, steps, tutorial | 
Confirm per step, back between steps, X discards (popTo Guide), How it works (tour); final confirm replaces with Analyzing | 
clip, mode, subject, seenContactTour | 
Session (via addSession), seenContactTour
 | 
Analyzing | 
AnalyzingScreen | 
Progress bar, 4 steps, the top fix preview | 
Auto-replaces with Result after 3.2 s | 
session | 
none
 | 
Result | 
ResultScreen | 
Clip tile, moments, score and delta, Fix first, Start drill, phase scores, findings tabs, coach status, Share, Delete | 
Tile (Recap), phase row (Phase), drill rows (Drill), Share sheet, Delete (alert, goBack) | 
session, previous session, team, user, unit | 
deletes Session
 | 
Recap | 
RecapScreen | 
Video player, speed pick, slider, phase chips | 
Play / pause, scrub, chip jumps | 
session | 
none
 | 
Phase | 
PhaseScreen | 
Phase grade, figure tile, measurements in that phase, re-film notice | 
Tile (Recap) | 
session | 
none
 | 
Drill | 
DrillScreen | 
Figure tile, drill name, cue (coach's if reviewed), rep counter, sets today | 
One more rep, Log set n (writes a DrillLog; 3 sets goes back), tile (Recap) | 
session or latest, setsToday | 
DrillLog
 | 
CoachTabs / Roster | 
RosterScreen | 
Team name, queue count card, All/Hitting/Pitching, player rows with score, delta, flags | 
Invite players or Create team, queue card (Queue tab), player row (CoachPlayer) | 
team, roster, sessionsOf, queue | 
none
 | 
CoachTabs / Queue (titled Review) | 
QueueScreen | 
Open sessions oldest first, Reviewed today | 
Row (Review), reviewed row (Result) | 
queue, roster, sessions | 
none
 | 
CoachTabs / Team | 
TeamScreen | 
Coach name, code card with Copy and Share, players count, coaching, email, Sign out | 
Players (Roster tab), Create team if none (CoachSetup), Sign out (alert) | 
user, team, roster | 
authUserId
 | 
CoachPlayer | 
CoachPlayerScreen | 
Player header, Hitting/Pitching segment when focus is both, trend, recurring-issue notice, sessions with Reviewed / Not reviewed | 
Footer Review <session> (Review), rows (Review or Result) | 
roster, sessionsOf | 
mode
 | 
Review | 
ReviewScreen | 
Score, clip, AI findings with Agree/Change/Not now, cue field, drill chips | 
Send to <name> (writes Review, goBack), Watch the clip (Recap) | 
session, roster | 
Session.review
Not in the list: Boot is declared in the route types but never registered; the loading state is handled inside RootNavigator.
5. Feature-by-feature breakdown
Each feature lists the store actions it calls today (names from AppContext), the data it needs and produces, and what the user sees on success, failure and when data is missing.
5.1 Accounts and sessions
Why: identity for players and coaches; everything else hangs off the account.
Actions: signUp(email, password, role), signIn(email, password), signOut(), setRole(role).
Needs: email (regex), password (8+). Produces: Account with role, focus: 'both', empty profile, plan: 'free'.
Success: sign-up goes to Role; sign-in resets to the role's tabs. Failure: inline error under the form ("Wrong email or password.", duplicate email). Missing: Forgot password is an alert placeholder; social buttons create a local placeholder account.
Backend: registration, login, token refresh, logout, password reset email, Apple and Google token exchange.
5.2 Athlete profile and units
Why: age, height, weight and level set the metric targets and the engine's starting point (athleteSkill).
Actions: updateProfile(patch), setUnit(unit), setFocus(focus).
Needs: Athlete fields; metric stored, unit only affects display. Produces: updated account.profile, unit, focus.
Missing data: Home and Subject warn when height or weight are null; targets still compute (size factor = 0).
Backend: PATCH on the account. Privacy rule from the UI copy: coaches see scores and targets, not body data.
5.3 Teams
Why: connects players to one coach so reps flow into a review queue.
Actions: createTeam(name, coachName, coaching), findTeam(code), joinTeam(code), leaveTeam().
Needs: team name (2+), coach name (2+); join needs an exact code (case-insensitive, trimmed). Produces: Team with generated code AAA-1234 (initials padded with X, 4 random digits, unique).
Success: join shows the team and coach on the Coach-code screen, then Profile lists Team and Coach. Failure: "We couldn't find a team with that code." Missing: a coach without a team sees Create team prompts on Invite, Roster and Team.
Backend: create (one per coach, replacing the old), lookup by code, join, leave, roster listing. Code generation moves server-side.
5.4 Capture
Why: get one side-on rep as a local video file.
Actions: setSubject(subject), setClip({uri, durationSec}).
Needs: camera or library permission. Produces: a local file:// URI; the app never copies it.
Failure: alerts for denied camera, library errors, clips over 60 s. Missing: no subject chosen defaults to self.
Backend: a video upload target (signed URL) and the stored object key. Nothing in the capture flow needs the network until confirm.
5.5 Marking (contact, stride, direction)
Why: anchors every measurement; contact timing, stride time and plant-to-contact are measured directly from these frames.
Needs: the clip; for hitting the audio envelope from modules/contact-audio (2 ms windows, 1.5 kHz high-pass). Produces: contactFrame, contactOffset, strideStartFrame, strideEndFrame, pitcherDir, a JPEG thumbnail at contact.
Rules: lift < plant < contact; direction length >= 8% of the frame; contact suggestion confidence >= 0.5 to be shown as Detected.
Failure: no audio or low confidence falls back to the fixed-fraction guess with a caption; thumbnail failures leave thumbUri null and the figure tile is shown instead.
Backend: receives the marks with the upload. Detection stays on-device unless the backend wants to re-run it (section 13).
5.6 Analysis engine
Why: turns a rep into a score, phase scores, 10 metrics, a fix order, a cue and a drill.
Action: addSession(args) runs analyze(ctx) synchronously.
Needs: athlete, mode, owner's history for that athlete and mode (newest first), drill logs since the last session, the marks, duration, video and thumb URIs.
How it computes today (to be replaced, but the output contract stays): per metric, first rep starts outside the target band on its typical side (startBias), scaled by age and level; later reps pull 18% toward target, or 45% if the matching drill was logged since the last rep; plus noise and a penalty on contact-phase metrics proportional to contactOffset. The two timing metrics per mode are real measurements. Band score: 100 inside [lo, hi], falling 55 points per band-width outside, floor 20. Phase score = mean of its metrics (85 if none). Session score = mean of phases. fixOrder = metrics not in range, worst first (or the single worst if all are in range). Cue = coach's cue if reviewed, else the catalog cue for the top fix; drill likewise.
Backend: the real pipeline (pose estimation + the metric catalog in section 7.5). Must return the same Session shape so no screen changes.
5.7 Results, recap and phases
Actions: getSession(id), deleteSession(id), native Share.
Needs: the session and the previous session of the same owner, mode and athlete for the delta. Produces: nothing except delete.
Missing: no previous session shows a First rep badge; thumbUri null shows the figure; videoUri null plays the demo figure in Recap.
Backend: session read (with signed video and thumbnail URLs), list, delete. Share stays client-side.
5.8 Drills and practice
Actions: logSet(session, drill, reps), setsToday(drill).
Rules: 8 reps per set, 3 sets a day; the drill name is the key (no drill ids). Week view = any log on each of the last 7 local days. Streak = consecutive weeks with at least one session.
Backend: drill log create and list; the week and streak can stay client-side if the API returns logs for the last N days.
5.9 Coach review
Actions: roster, sessionsOf(playerId), queue, sendReview(sessionId, {cue, drill, verdicts}).
Needs: the coach's team, player accounts and their self sessions. Produces: Session.review with the coach's id and name and a timestamp.
Rules: only isSelf sessions are reviewable; one review per session (resend overwrites); verdict keys are metric keys.
Backend: roster with last session summaries, per-player sessions, queue, review create. The player must receive the review on their own device (push or poll).
5.10 Plan and limits
Actions: setPlan(plan), analysesLeft.
Rules: free = 3 analyses per rolling 7 days counted on the owner (including reps for someone else); pro = unlimited. Home blocks Analyze at 0 with an alert.
Today: an alert toggles the plan with the text "Billing is not connected yet". Backend: entitlement check on session create, a billing provider (section 13).
5.11 Privacy toggle
Action: setPrivateVideos(bool). Stored on the account; nothing reads it yet. Backend: should gate who can fetch the video URL (section 13 asks what non-private means).
5.12 Sample data and reset
loadSample() (debug builds only) builds a coach, a team (KDA-4821), three players and weeks of sessions and drill logs through the engine, and signs in as the player. resetAll() clears the store. Neither needs a backend; a seed script for staging would be useful.
6. Implementation status
The UI is complete for every feature; what is missing is persistence beyond one device, real analysis, and the services the copy already promises. Exists (client) means it works on-device and the backend only has to store or serve the same data. Partial means the UI is there but the behaviour is a placeholder. The Status column is a dropdown; update it as endpoints land.
 | 
Feature | 
Status | 
What exists today | 
What the backend must add
 | 
Email sign-up and sign-in | 
Partial | 
Local accounts, plaintext passwords, duplicate-email check | 
Hashed credentials, tokens, refresh, logout
 | 
Apple / Google sign-in | 
Needs backend | 
Buttons that create a placeholder local account | 
Token exchange with Apple and Google, account linking
 | 
Forgot password | 
Needs backend | 
Alert placeholder | 
Reset email + token flow
 | 
Role, focus, profile, units | 
Partial | 
Persisted locally | 
Account PATCH, validation
 | 
Team create / code / invite | 
Partial | 
Local team, generated code, share sheet | 
Server-generated unique codes, lookup, invite links (optional)
 | 
Join / leave team | 
Partial | 
Works on the same device only | 
Cross-device membership
 | 
Record / import clip | 
Exists (client) | 
Native camera and library, limits, permissions | 
Upload target only
 | 
Contact detection and marking | 
Exists (client) | 
On-device audio detection, 4-step marking, tutorial | 
Store the marks
 | 
Video storage and playback | 
Needs backend | 
Plays the local file; coach can only watch on the same device | 
Object storage, signed URLs, thumbnail storage
 | 
Analysis (scores, metrics, fix, cue, drill) | 
Needs backend | 
Deterministic simulation with practice effect | 
Real pipeline; async job + status; same output contract
 | 
Result, Recap, Phase | 
Partial | 
Fully working from local sessions | 
Session read with media URLs
 | 
History (trend, ranges, streak) | 
Partial | 
Computed from local sessions | 
Session list with range filter
 | 
Drill of the day, logging sets | 
Partial | 
Local drill logs, 8 reps x 3 sets rule | 
Drill log create / list
 | 
Coach roster, player page, flags | 
Partial | 
Computed from local accounts and sessions | 
Roster endpoint with last-session summaries
 | 
Review queue and sending reviews | 
Needs backend | 
Works only when coach and player share a device | 
Queue, review create, delivery to the player (push)
 | 
Free plan limit (3 a week) | 
Needs backend | 
Counted locally; alert at 0 | 
Server-side entitlement on session create
 | 
Pro plan and billing | 
Needs backend | 
Alert toggles the plan; copy says billing is not connected | 
Store subscriptions (App Store / Play) or a web checkout
 | 
Private videos switch | 
Needs backend | 
Stored, unused | 
Access rule on video URLs
 | 
Share score / share code | 
Exists (client) | 
Native share sheet with text | 
Nothing (deep links optional)
 | 
Notifications ("we'll notify you", "handled by email") | 
Needs backend | 
Copy only | 
Push for analysis done and review received; consent email
7. API specification
30 endpoints across 7 modules make the app fully functional; 23 are needed for the first connected release (section 12 has the priorities). Everything is REST over HTTPS with JSON bodies. Endpoint paths are suggestions; the request and response shapes are what the app needs.
7.1 Conventions
Base path /v1. Ids are UUIDs. Timestamps are ISO 8601 UTC strings; the app converts to local time. Body measurements are metric (heightCm, weightKg); the app handles unit display.
Auth: Authorization: Bearer <accessToken>. Access tokens short-lived (15 to 60 min), refresh tokens rotated on use. Every endpoint except the auth module requires a token.
Roles: player and coach from the account. Coach endpoints return 403 FORBIDDEN for players and vice versa.
Errors always use one shape, and the message is safe to show in the UI (the app shows API messages inline under forms):
Common codes: 400 VALIDATION (with fields: {email: "..."}), 401 UNAUTHENTICATED, 403 FORBIDDEN, 404 NOT_FOUND, 409 CONFLICT, 402 PLAN_LIMIT, 413 TOO_LARGE, 422 UNPROCESSABLE, 429 RATE_LIMITED, 500 INTERNAL.
Lists return { "items": [...], "nextCursor": "..." | null } with ?limit= (default 50, max 200) and ?cursor=.
All writes are idempotent where the app may retry: POST /sessions and POST /drill-logs accept an Idempotency-Key header.
7.2 Auth module
 | 
# | 
Endpoint | 
Purpose | 
Auth | 
Triggered by
 | 
A1 | 
POST /v1/auth/register | 
Create an account | 
none | 
SignUp, Continue
 | 
A2 | 
POST /v1/auth/login | 
Sign in | 
none | 
SignIn, Sign in
 | 
A3 | 
POST /v1/auth/social | 
Sign in or up with Apple or Google | 
none | 
SignUp, Apple / Google buttons
 | 
A4 | 
POST /v1/auth/refresh | 
Rotate tokens | 
refresh token | 
App launch, on 401
 | 
A5 | 
POST /v1/auth/logout | 
Revoke the refresh token | 
bearer | 
Profile and Team, Sign out
 | 
A6 | 
POST /v1/auth/password/forgot | 
Send a reset email | 
none | 
SignIn, Forgot password
 | 
A7 | 
POST /v1/auth/password/reset | 
Set a new password from the emailed token | 
none | 
Reset link (web page or deep link; see section 13)
A1 register
Validation: email RFC-style, lower-cased and trimmed; password 8 to 128 characters; role in player | coach (the app sends player and may change it once on the Role screen, see B2). Errors: 409 EMAIL_TAKEN, 400 VALIDATION. Logic: hash the password (argon2id or bcrypt 12), create the account with the defaults above, issue tokens.
A2 login: { "email", "password" } returns the same body as A1 with 200. Wrong credentials return 401 INVALID_CREDENTIALS with message "Wrong email or password." (the app shows it verbatim). Rate-limit by email and IP.
A3 social: { "provider": "apple" | "google", "idToken": "...", "role": "player" }. Verify the token with the provider, find or create the account by the provider subject (and verified email when present), return the A1 body plus "isNew": true | false so the app can route new users to Role. Apple may hide the email; store the relay address.
A4 refresh: { "refreshToken" } returns tokens; a reused or revoked token returns 401 TOKEN_REVOKED and the app signs out.
A6 / A7: A6 always returns 202 to avoid account enumeration. A7 takes { "token", "password" }, returns 204, 400 TOKEN_INVALID when expired (suggest 1 hour).
7.3 Account module
 | 
# | 
Endpoint | 
Purpose | 
Auth | 
Triggered by
 | 
B1 | 
GET /v1/me | 
Current account, team and entitlement in one call | 
bearer | 
App launch, after sign-in, pull-to-refresh
 | 
B2 | 
PATCH /v1/me | 
Update role (onboarding only), focus, profile, unit, privateVideos | 
bearer | 
Role, Focus, About you, Edit profile, Profile (focus segment, privacy switch)
 | 
B3 | 
POST /v1/devices | 
Register a push token | 
bearer | 
App launch when permission granted
 | 
B4 | 
DELETE /v1/devices/{token} | 
Remove a push token | 
bearer | 
Sign out
B1 response:
team is null when the user has none. entitlement replaces the client's analysesLeft computation; usedThisWeek counts the owner's sessions created in the last 7 days, including reps for someone else, matching today's behaviour.
B2 request is a partial object; every field optional:
Validation (mirrors src/data/athlete.ts): age integer 5 to 70 or null; heightCm 90 to 230 or null; weightKg 20 to 200 or null; bats in L R S; throws in L R; level in Youth | High school | College | Adult; focus in h p both; unit in imperial metric. role may only change while the account has no team and no sessions, otherwise 409 ROLE_LOCKED. Returns the updated user.
7.4 Teams module
 | 
# | 
Endpoint | 
Purpose | 
Auth | 
Triggered by
 | 
C1 | 
POST /v1/teams | 
Create the coach's team (replaces an existing one) | 
coach | 
CoachSetup, Create team
 | 
C2 | 
GET /v1/teams/lookup?code=KDA-4821 | 
Public summary of a team by code | 
bearer | 
Coach-code screen (live as the user types), Profile Join team
 | 
C3 | 
POST /v1/teams/{code}/join | 
Join as a player | 
player | 
Coach-code Join, Profile Join team
 | 
C4 | 
DELETE /v1/me/team | 
Leave the team | 
player | 
Profile, Leave team
C1 request { "name": "Karachi Diamond Academy", "coachName": "Imran Baig", "coaching": "both" }; name and coachName 2 to 60 characters; coaching in h p both. Logic: generate a unique code (today: up to 3 initials padded with X, a dash, 4 digits, e.g. KDA-4821; keep this format, the app validates 6+ characters), set profile.name and focus on the coach's account as the app does, and if the coach already has a team, replace it and keep the members (Requires Clarification: today the old team is dropped and players keep a dead code). Returns 201 { "team": {...} }.
C2 returns { "team": { "code", "name", "coachName", "coaching" } } or 404 TEAM_NOT_FOUND with message "We couldn't find a team with that code." Lookup is case-insensitive and trimmed. Rate-limit (codes are guessable).
C3 sets teamCode on the player, returns 200 { "team" }. Joining another team moves the player. C4 returns 204 and must make the coach's roster and queue drop the player's sessions.
8. Database schema and relationships
Eight tables cover everything the app stores; three more (auth_tokens, devices, subscriptions) support the backend-only features. Relational (Postgres) is the natural fit: the data is small per user, strongly related, and the coach views are joins. JSON columns hold the parts the app treats as opaque blobs (metrics, phases, verdicts, pitcher_dir).
 | 
Table | 
Columns (type, constraints) | 
Relationships and indexes
 | 
accounts | 
id uuid pk, email citext unique, password_hash text null (null for social-only), role text check in (player, coach), focus text default 'both', name text, age int null, height_cm numeric null, weight_kg numeric null, bats char(1), throws char(1), level text, unit text default 'imperial', plan text default 'free', private_videos bool default true, team_id uuid null fk teams, created_at, updated_at | 
team_id for players only (coaches link via teams.coach_id). Index (team_id).
 | 
auth_identities | 
id, account_id fk, provider text (apple, google), subject text, email text null | 
Unique (provider, subject).
 | 
auth_tokens | 
id, account_id fk, refresh_hash text, expires_at, revoked_at null, replaced_by null | 
Refresh-token rotation; index (account_id).
 | 
password_resets | 
id, account_id fk, token_hash, expires_at, used_at null | 
 | 
teams | 
id uuid pk, code text unique, name text, coach_id uuid fk accounts unique, coach_name text, coaching text check in (h, p, both), created_at | 
One team per coach (coach_id unique). Index (code).
 | 
sessions | 
id uuid pk, owner_id fk accounts, is_self bool, athlete jsonb (Athlete snapshot), mode char(1), status text (queued, processing, done, failed), failure jsonb null, video_key text, thumb_key text null, duration_sec numeric, fps int default 30, contact_frame int, contact_offset int, contact_source text, stride_start_frame int, stride_end_frame int, pitcher_dir jsonb null, score int null, phases jsonb null, weak text null, metrics jsonb null, fix_order text[] null, created_at, analyzed_at null, deleted_at null | 
Index (owner_id, mode, created_at desc) for history and the delta; (owner_id, is_self); partial index on status for the job queue. Soft delete so the coach queue and push payloads can resolve a deleted id.
 | 
reviews | 
session_id uuid pk fk sessions, coach_id fk accounts, coach_name text, cue text, drill text, verdicts jsonb, created_at, updated_at | 
One review per session (pk on session_id). The coach queue is sessions where is_self and status = done and no review and owner in team.
 | 
drill_logs | 
id uuid pk, owner_id fk, session_id fk null, mode char(1), drill text, reps int, day date, created_at | 
Index (owner_id, day) and (owner_id, mode, created_at) for the practice-effect lookup.
 | 
devices | 
id, account_id fk, platform text, push_token text unique, created_at, last_seen_at | 
 | 
subscriptions | 
id, account_id fk, platform, product_id, original_transaction_id unique, status, expires_at, raw jsonb | 
Drives accounts.plan.
 | 
metric_catalog (optional) | 
mode, key, name, phase, unit, min, max, lo, hi, decimals, why_low, why_high, why_good, drill, pose, cue, sort | 
Pk (mode, key). Source of truth for D6 and the analysis job.
A coach reaches a player's sessions through teams.coach_id to accounts.team_id to sessions.owner_id; the review hangs off the session, not the player, so the queue is a simple anti-join.
Data flow
Reads on launch: GET /me joins accounts, teams and a count over sessions for the entitlement.
A new rep writes one sessions row (status queued) and two objects in storage; the job updates the same row to done.
Player screens read sessions by owner; coach screens read sessions joined to accounts by team. Nothing is copied between players and coaches, so a review is a single row the player's next fetch picks up.
The athlete snapshot on a session is intentional: a player can change their profile later and old reps keep the numbers they were scored against.
Migration from the device store
Existing users have local data in AsyncStorage (cognivision.db.v1). If it should survive, a one-time POST /v1/import that accepts the Persisted document (minus passwords) could create sessions with video_key = null (the clip never left the phone). Requires Clarification: whether pre-backend local data matters; the app can simply reset.
9. Integration and system workflows
The app is request-driven with one background job (analysis) and two push events. The two drawings below cover the paths with branches; the rest are plain request and response.
9.1 Auth and session restore
On launch the app reads tokens from the keychain (new; today it reads authUserId from AsyncStorage). No tokens: Welcome.
It calls B1 with the access token. 401: call A4 with the refresh token, retry once; a TOKEN_REVOKED signs the user out to Welcome.
B1's user.role picks the tab set; team and entitlement seed Home, Profile, Roster and Team so no second round trip is needed before the first screen.
Sign out calls A5 and B4, clears the keychain and the local cache, and resets to Welcome. Today's copy promises "Your sessions stay on this device"; with a backend they stay on the account instead (copy change for the app team).
9.2 Upload and analysis pipeline
The marking screen already has everything the pipeline needs at the moment the user confirms the direction step. The drawing shows the happy path, the plan-limit refusal and a failed job. Timing: the app shows four fake steps for 3.2 s today; with a backend it polls D3 every 2 s and the push ends the wait early.
The plan check happens before anything is stored, so a refused rep leaves no session and no counter change. A failed job keeps the session row (status failed) so the app can offer re-filming without losing the marks.
9.3 Coach review loop
A review is one row, but it changes four player screens and two coach screens. The player device learns about it through the review.received push or on the next D3 / D4 fetch; nothing is pushed into the player's local store.
The loop closes when the player films again: the new rep's engine run reads the drill logs since the last session, so a logged drill moves the next score.
9.4 Data synchronisation model
Server is the source of truth; the app keeps a small read cache keyed by endpoint and refreshes on screen focus and on pull-to-refresh (to be added to Home, History, Roster and Queue).
Writes are online-only. The only write that can happen offline today is logging a drill set; queue E1 locally with an Idempotency-Key and flush when back online. Session creation requires the upload, so it stays online.
Media URLs are signed and expire; the app re-fetches D3 when a video or thumbnail fails to load.
Conflicts are rare because each record has one writer: the owner for sessions and logs, the coach for reviews, the server for analysis results.
9.5 Third-party services
 | 
Need | 
Service | 
Where it is used
 | 
Object storage with signed URLs | 
S3, GCS or R2 | 
D1, D3 media, D5 cleanup
 | 
Job queue and worker | 
SQS + a container, or a Postgres-backed queue | 
Analysis after D2
 | 
Push | 
APNs and FCM | 
B3, analysis.done, review.received
 | 
Social sign-in | 
Sign in with Apple, Google Identity | 
A3
 | 
Email | 
Any transactional provider | 
A6 reset mail, Q6 consent mail
 | 
Payments | 
App Store Server API, Google Play Developer API | 
G2, G3
 | 
Pose estimation (later) | 
A hosted model or a GPU worker | 
Replaces the ported engine in the worker
10. Frontend-to-API mapping
Every user action that touches data, and the endpoint it calls. Actions not listed (scrubbing, tutorial, share sheet, unit toggles inside a form) are client-only.
 | 
Screen | 
Action | 
Endpoint(s) | 
Notes
 | 
App launch | 
Restore session | 
A4, B1 | 
B1 also seeds team and entitlement; B3 once push permission is granted
 | 
Welcome | 
Load sample data | 
none | 
Dev builds only
 | 
SignUp | 
Continue | 
A1 | 
Then Role
 | 
SignUp | 
Apple / Google | 
A3 | 
isNew decides Role vs tabs
 | 
SignIn | 
Sign in | 
A2, B1 | 
Reset to tabs by role
 | 
SignIn | 
Forgot password | 
A6 | 
Replaces today's alert
 | 
Role | 
Continue | 
B2 {role} | 
Only allowed before any team or session
 | 
Focus | 
Continue | 
B2 {focus} | 
 | 
About you | 
Continue | 
B2 {profile, unit} | 
 | 
Coach code | 
typing (debounced) | 
C2 | 
Shows team name and coach
 | 
Coach code | 
Join <team> | 
C3 | 
Skip for now calls nothing
 | 
CoachSetup | 
Create team | 
C1 | 
Also updates the coach's name and focus
 | 
CoachInvite | 
Copy / Share | 
none | 
Code from B1 or C1
 | 
Home | 
load | 
D4 ?mode=&self=true&limit=1, G1, E2 (today) | 
Last rep, counter, sets today
 | 
Home | 
Analyze | 
G1 (or cached) | 
Blocks at 0 left
 | 
Subject | 
Continue to filming | 
none | 
Subject kept in memory until D2
 | 
Guide | 
Record / Choose | 
none | 
Local file only
 | 
ContactFrame | 
final confirm | 
D1 (video), D1 (thumbnail), storage PUT x2, D2 | 
Then Analyzing
 | 
Analyzing | 
poll | 
D3 every 2 s until status != queued/processing, or push analysis.done | 
Replace with Result on done; show re-film prompt on failed
 | 
Result | 
load | 
D3 | 
Includes previous, media, review, ordinal
 | 
Result | 
Delete session | 
D5 | 
 | 
Recap | 
play | 
D3 media.videoUrl | 
Re-fetch D3 on URL expiry
 | 
Phase | 
load | 
D3 (cached) | 
 | 
Drill | 
load | 
D3 or D4 latest, E2 (today) | 
 | 
Drill | 
Log set n | 
E1 | 
3 sets closes the screen
 | 
Drills tab | 
load | 
D4 ?self=true&limit=1, E2 (7 days) | 
 | 
History tab | 
load, range change | 
D4 ?mode=&self=true&since= | 
Trend, best, average, streak computed client-side
 | 
Profile | 
Focus segment | 
B2 {focus} | 
 | 
Profile | 
Join team | 
C2 then C3 | 
 | 
Profile | 
Leave team | 
C4 | 
 | 
Profile | 
Plan | 
G2 (after store purchase) | 
Today an alert toggle
 | 
Profile | 
Keep my videos private | 
B2 {privateVideos} | 
 | 
Profile / Team | 
Sign out | 
A5, B4 | 
Then clear local cache
 | 
EditProfile | 
Save | 
B2 {profile, unit} | 
 | 
Roster | 
load, filter | 
F1 | 
Flags computed from last and recent
 | 
Roster | 
Invite / Create team | 
none / C1 | 
 | 
Queue | 
load | 
F3 | 
 | 
CoachPlayer | 
load, mode switch | 
F2 ?mode= | 
Recurring-issue notice from fixOrder[0] counts
 | 
Review | 
load | 
D3 | 
Coach access to a player's self session
 | 
Review | 
Send to <name> | 
F4 | 
Push review.received to the player
 | 
Team | 
load | 
B1, F1 (count) | 
11. Backend development checklist
Four milestones, in dependency order. A milestone is done when every acceptance line under it passes against the app with the local store swapped for the API client.
Milestone 1: Accounts and teams (critical)
A1, A2, A4, A5 with hashed passwords, rotating refresh tokens, rate limits on A2 and A6
B1 returning user, team, entitlement in one call
B2 with the validation rules in 7.3 and the ROLE_LOCKED rule
C1 to C4, server-generated unique codes in the AAA-1234 format
Error envelope from 7.1 everywhere; messages safe to show
Acceptance: a coach on one phone and a player on another can create a team, join by code, and the player appears in F1 within one refresh. Sign-up with a taken email shows the duplicate message inline. The coach sign-up path never loses the role.
Milestone 2: Sessions, media and the analysis job (critical)
D1 signed uploads (video and thumbnail), size and type limits, object cleanup for abandoned uploads
D2 with mark validation, the athlete snapshot, idempotency, and the weekly entitlement check
Job queue with queued / processing / done / failed; D3 exposes status and failure
Analysis worker producing the exact Session contract (section 2 and D3). Until the pose model exists, port src/store/engine.ts to the worker so the output is identical and the app is testable end to end
D3 with signed media URLs, previous, ordinal, access rules; D4 with filters and cursors; D5 with media deletion
E1, E2 drill logs
Acceptance: confirming a rep on the device creates a session that reaches done within 30 s, Result renders from D3 with no client-side fallbacks, Recap plays the uploaded clip, History shows the rep with the correct ordinal and delta, and a 4th rep in a week on free returns 402 PLAN_LIMIT with the app's alert.
Milestone 3: Coach loop and notifications (high)
F1 with last, recent, pendingCount, no body data
F2, F3 (oldest first, reviewed today), F4 with the verdict and drill validation
B3, B4 device tokens; APNs and FCM senders; analysis.done and review.received payloads
Acceptance: a review sent from the coach's phone shows on the player's Result, Drill and Home within one refresh or via push; the session leaves the queue and appears under Reviewed today.
Milestone 4: Growth and compliance (medium / low)
A3 social sign-in (Apple required for App Store if any third-party login ships), A6 and A7 reset flow
G1, G2, G3 billing; plan derived from subscriptions
D6 metric catalog served from metric_catalog
Privacy rule for privateVideos once defined (section 13); parental-consent email once defined
Account deletion endpoint (store policy requirement, not in the UI yet)
Cross-cutting requirements
Security: TLS only, bcrypt or argon2id, JWT with short expiry, refresh rotation with reuse detection, signed storage URLs (never public buckets), coach access limited to own team and isSelf sessions, no body data in coach responses, rate limits on auth and code lookup, audit log on reviews.
Validation: reject unknown fields, enforce the ranges in 7.3 and 7.5, return field-level errors.
Observability: request ids in every response, job metrics (queue depth, time to done, failure rate by code).
Testing: contract tests against the JSON examples in section 7; a seed script equivalent to src/store/sample.ts (coach, team KDA-4821, three players, weeks of sessions) for staging; an end-to-end run of journeys 3.2, 3.3 and 3.6 on two devices before each milestone closes.
12. API inventory
30 endpoints, plus 2 optional ones at the end. 18 are Critical (milestones 1 and 2), 6 High (milestone 3), 6 Medium or Low. The Priority column is a dropdown so the team can re-plan in place.
 | 
# | 
Method | 
Path | 
Module | 
Priority | 
Milestone
 | 
A1 | 
POST | 
/v1/auth/register | 
Auth | 
Critical | 
1
 | 
A2 | 
POST | 
/v1/auth/login | 
Auth | 
Critical | 
1
 | 
A3 | 
POST | 
/v1/auth/social | 
Auth | 
Medium | 
4
 | 
A4 | 
POST | 
/v1/auth/refresh | 
Auth | 
Critical | 
1
 | 
A5 | 
POST | 
/v1/auth/logout | 
Auth | 
Critical | 
1
 | 
A6 | 
POST | 
/v1/auth/password/forgot | 
Auth | 
Medium | 
4
 | 
A7 | 
POST | 
/v1/auth/password/reset | 
Auth | 
Medium | 
4
 | 
B1 | 
GET | 
/v1/me | 
Account | 
Critical | 
1
 | 
B2 | 
PATCH | 
/v1/me | 
Account | 
Critical | 
1
 | 
B3 | 
POST | 
/v1/devices | 
Account | 
High | 
3
 | 
B4 | 
DELETE | 
/v1/devices/{token} | 
Account | 
High | 
3
 | 
C1 | 
POST | 
/v1/teams | 
Teams | 
Critical | 
1
 | 
C2 | 
GET | 
/v1/teams/lookup | 
Teams | 
Critical | 
1
 | 
C3 | 
POST | 
/v1/teams/{code}/join | 
Teams | 
Critical | 
1
 | 
C4 | 
DELETE | 
/v1/me/team | 
Teams | 
Critical | 
1
 | 
D1 | 
POST | 
/v1/uploads | 
Sessions | 
Critical | 
2
 | 
D2 | 
POST | 
/v1/sessions | 
Sessions | 
Critical | 
2
 | 
D3 | 
GET | 
/v1/sessions/{id} | 
Sessions | 
Critical | 
2
 | 
D4 | 
GET | 
/v1/sessions | 
Sessions | 
Critical | 
2
 | 
D5 | 
DELETE | 
/v1/sessions/{id} | 
Sessions | 
Critical | 
2
 | 
D6 | 
GET | 
/v1/catalog/metrics | 
Sessions | 
Low | 
4
 | 
E1 | 
POST | 
/v1/drill-logs | 
Drills | 
Critical | 
2
 | 
E2 | 
GET | 
/v1/drill-logs | 
Drills | 
Critical | 
2
 | 
F1 | 
GET | 
/v1/coach/roster | 
Coach | 
High | 
3
 | 
F2 | 
GET | 
/v1/coach/players/{playerId}/sessions | 
Coach | 
High | 
3
 | 
F3 | 
GET | 
/v1/coach/queue | 
Coach | 
High | 
3
 | 
F4 | 
POST | 
/v1/sessions/{id}/review | 
Coach | 
High | 
3
 | 
G1 | 
GET | 
/v1/me/entitlement | 
Billing | 
Medium | 
4
 | 
G2 | 
POST | 
/v1/billing/receipts | 
Billing | 
Medium | 
4
 | 
G3 | 
POST | 
/v1/billing/webhooks/{provider} | 
Billing | 
Medium | 
4
 | 
opt | 
POST | 
/v1/import | 
Migration | 
Low | 
if needed
 | 
opt | 
DELETE | 
/v1/me | 
Account | 
Low | 
before store release
The analysis worker is not an endpoint but is on the critical path of milestone 2; see section 9.2.
13. Requires clarification
Nothing below is defined in the app. Each item has a recommendation so work can start; the product owner should confirm or change it.
 | 
# | 
Question | 
Where it shows | 
Recommendation
 | 
Q1 | 
What does Pro cost, and is it App Store / Play billing or web checkout? | 
Profile, Plan alert ("Billing is not connected yet") | 
Store subscriptions (required by Apple for in-app digital goods); one monthly product pro_monthly; G2 and G3 as specified.
 | 
Q2 | 
Does a failed analysis count toward the 3-a-week free limit? | 
Analyzing failure, Home counter | 
No; count only done sessions.
 | 
Q3 | 
Is the weekly limit a rolling 7 days (today) or a calendar week? | 
Home counter | 
Keep rolling 7 days; the app already shows "this week" loosely.
 | 
Q4 | 
Should reps filmed for someone else count toward the owner's limit? | 
Subject, Home | 
Today they do; keep it, since the cost is the same analysis.
 | 
Q5 | 
What does "Keep my videos private" turn off when it is off? | 
Profile switch (stored, unused) | 
Off = team-mates on the same team may view the clip; on = only the owner and coach. If no sharing feature is planned, remove the switch.
 | 
Q6 | 
Parental consent for under-18s: real flow or copy? | 
CoachInvite notice ("We handle that by email") | 
Collect a parent email at onboarding when age < 18, send a consent email, and hide the coach's access to that player until consent is recorded. Needs a consents table and two endpoints.
 | 
Q7 | 
When a coach creates a second team, what happens to members of the first? | 
CoachSetup (today: old team dropped, players keep a dead code) | 
Treat C1 on an existing team as an update (rename / recoach), never a replacement.
 | 
Q8 | 
Can a player belong to more than one team or have several coaches? | 
Profile Team section (single) | 
Single team; joining another moves the player (as specified in C3).
 | 
Q9 | 
Password reset delivery: web page or app deep link? | 
SignIn, Forgot password | 
Web page hosted by the backend with the token in the URL; the app does not need a route.
 | 
Q10 | 
Should the analysis re-detect contact server-side or trust the user's marks? | 
ContactFrame (on-device audio detection, presented as AI) | 
Trust the marks; store contactSource so the pipeline can weight them. Re-detection can come with the pose model.
 | 
Q11 | 
Where will the real pose model run, and what latency is acceptable? | 
Analyzing ("About 20 seconds") | 
Server-side worker; target under 30 s per clip; push on completion.
 | 
Q12 | 
Video retention and size limits | 
Guide (60 s cap), Result Delete | 
Keep clips while the session exists; cap uploads at 250 MB; lifecycle rule to delete objects of soft-deleted sessions after 30 days.
 | 
Q13 | 
Does local data from the pre-backend builds need to migrate? | 
Everything persisted today | 
No; reset on first signed-in launch. Keep /v1/import out unless asked.
 | 
Q14 | 
Account deletion and data export | 
Not in the UI | 
Required by both app stores for accounts: add DELETE /v1/me and a Profile row before release.
 | 
Q15 | 
Coach-side notifications (player joined, new rep) | 
Queue, Roster | 
Add rep.ready for the coach when a team rep reaches done; low priority.
7.5 Sessions and analysis module
 | 
# | 
Endpoint | 
Purpose | 
Auth | 
Triggered by
 | 
D1 | 
POST /v1/uploads | 
Get a signed URL to upload the clip (and the thumbnail) | 
bearer | 
ContactFrame, final confirm
 | 
D2 | 
POST /v1/sessions | 
Create a session from an upload and the marks; starts analysis | 
bearer, entitlement | 
ContactFrame, final confirm
 | 
D3 | 
GET /v1/sessions/{id} | 
Full session including analysis status, media URLs, review and the previous rep's score | 
owner, their coach | 
Analyzing (poll), Result, Recap, Phase, Drill, Review
 | 
D4 | 
GET /v1/sessions | 
The owner's sessions, filterable | 
bearer | 
Home, History, Drills, delta on Result
 | 
D5 | 
DELETE /v1/sessions/{id} | 
Delete a session and its media | 
owner | 
Result, Delete session
 | 
D6 | 
GET /v1/catalog/metrics?mode=h | 
Metric catalog: names, phases, bands, why texts, cues and drills | 
bearer | 
Optional; the app ships the catalog
D1 request { "kind": "video" | "thumbnail", "contentType": "video/mp4", "bytes": 18422331, "durationSec": 3.87 }. Returns 201 { "uploadId": "u9...", "url": "https://...signed PUT...", "headers": { "Content-Type": "video/mp4" }, "expiresAt": "..." }. Limits: video up to 60 s and 250 MB (413 TOO_LARGE); accepted types video/mp4, video/quicktime (iOS records .mov), thumbnails image/jpeg. The app PUTs the file to url directly; the backend verifies the object exists when D2 references the id.
D2 request, exactly what the app has at confirm time:
athlete is null for the owner's own rep (the server copies the account profile into the session) or a full Athlete object for someone else's (name required, age, heightCm, weightKg required, matching the Subject screen). contactSource is detected (on-device audio pick), suggested (fixed fraction) or manual (user moved it); the app can derive this from contactOffset and the badge state. Validation: strideStartFrame < strideEndFrame < contactFrame, all within 0..round(durationSec*fps)-1; pitcherDir points in 0..1 and at least 0.08 apart; mode in h p. Entitlement: on the free plan, 402 PLAN_LIMIT with message "The free plan includes 3 analyses a week." when usedThisWeek >= 3. Response 202:
Logic: persist the session with status = queued, enqueue the analysis job (section 9.2), and when it finishes set status = done and fill score, phases, weak, metrics, fixOrder. A failed job sets status = failed with failure: { "code": "NO_PERSON" | "BAD_ANGLE" | "INTERNAL", "message" }; the app's copy already promises "we ask you to re-film instead of guessing". The session must not count toward the weekly limit if it fails (Requires Clarification).
D3 response is the Session shape from section 2 plus media and context:
previous is the owner's prior session with the same mode and athlete name (for the delta pill); ordinal gives the "Swing 4" title. Metric grade and band.grade are the same value (kept for compatibility). Signed media URLs should live at least 1 hour; the app re-fetches on expiry. Access: the owner, and the coach of the owner's team when isSelf is true; a coach may not fetch someone-else's-swing sessions. privateVideos = true must not block the coach (the UI says "Only you and your coaches").
D4 query: mode=h|p, self=true|false, athleteName=, since=<ISO>, limit, cursor. Items are session summaries: id, mode, isSelf, athlete.name, createdAt, status, score, weak, fixOrder[0], topFix: {key, name, drill}, review: {coachName, at} | null, thumbUrl. Home needs the latest per mode; History needs 7, 30 or all days; Drills needs the latest self session per mode.
D5 returns 204, deletes the objects, and removes the session from the coach's queue. A reviewed session may still be deleted by its owner (today it can).
D6 returns the 10 specs per mode as in src/store/engine.ts (key, name, phase, unit, min, max, lo, hi, decimals, whyLow, whyHigh, whyGood, drill, pose, cue). Serving it lets the backend tune bands without an app release.
7.6 Drills module
 | 
# | 
Endpoint | 
Purpose | 
Auth | 
Triggered by
 | 
E1 | 
POST /v1/drill-logs | 
Log one set | 
bearer | 
Drill, Log set n
 | 
E2 | 
GET /v1/drill-logs?from=2026-10-16&to=2026-10-22 | 
Logs in a local-date range | 
bearer | 
Drills (7-day row), Drill (sets today), Home (sets today)
E1 request { "sessionId": "s7...", "mode": "h", "drill": "Back-pocket load", "reps": 8, "day": "2026-10-22", "at": "2026-10-22T17:05:00Z" }; reps 1 to 8; day is the device's local date so "sets today" matches what the player sees. Returns 201 { "log": { "id", ...same fields..., "sets": 1 } }. A fourth set on the same day and drill is accepted but the app never sends it (TARGET_SETS = 3). E2 returns { "items": [log...] }.
The analysis pipeline reads drill logs since the player's last session for the practice effect (section 5.6); keep that query cheap (index on ownerId, mode, at).
7.7 Coach module
 | 
# | 
Endpoint | 
Purpose | 
Auth | 
Triggered by
 | 
F1 | 
GET /v1/coach/roster | 
Players on the coach's team with last-session summaries | 
coach | 
Roster, Team (count)
 | 
F2 | 
GET /v1/coach/players/{playerId}/sessions?mode=h | 
A player's self sessions, newest first | 
coach | 
CoachPlayer
 | 
F3 | 
GET /v1/coach/queue | 
Unreviewed self sessions on the team, oldest first, plus reviewed today | 
coach | 
Queue, Roster card
 | 
F4 | 
POST /v1/sessions/{id}/review | 
Send the review | 
coach of the owner's team | 
Review, Send to <name>
F1 item:
recent holds the last three scores per mode so the app can keep computing its Stuck flag (last three not improving) client-side; joinedAt and email are shown when the name is empty. Do not include body data (height, weight, age) in coach responses.
F3 response { "open": [session summary...], "reviewedToday": [session summary...] }, summaries as in D4 plus ownerName. Oldest first for open.
F4 request { "cue": "Point your back pocket at the catcher as you load.", "drill": "Back-pocket load", "verdicts": { "pelvis": "agree", "stridetime": "change" } }. cue 1 to 200 characters (the app falls back to the catalog cue when empty), drill must be one of the session's finding drills, verdict values in agree | change | later, keys must be metric keys on that session. Returns 201 { "review": { "coachId", "coachName", "cue", "drill", "verdicts", "at" } }; sending again overwrites (200). Side effects: the session leaves the queue, and the player gets a push (section 7.8). 403 if the coach is not the owner's team coach or the session is not isSelf.
7.8 Entitlement, billing and notifications
 | 
# | 
Endpoint | 
Purpose | 
Auth | 
Triggered by
 | 
G1 | 
GET /v1/me/entitlement | 
Plan and weekly usage | 
bearer | 
Home counter, before Analyze
 | 
G2 | 
POST /v1/billing/receipts | 
Validate an App Store or Play purchase and set the plan | 
bearer | 
Profile, Upgrade to Pro (Requires Clarification)
 | 
G3 | 
POST /v1/billing/webhooks/{provider} | 
Renewal, cancellation, refund events | 
provider signature | 
Store servers
G1 is the entitlement object from B1 on its own, for cheap refresh. G2 request { "platform": "ios" | "android", "receipt": "..." | "purchaseToken": "...", "productId": "pro_monthly" }; returns the new entitlement. Today the app toggles the plan with no payment, so the exact product and provider are open (section 13).
Push notifications have no endpoint of their own beyond B3 / B4. Two events are implied by the UI copy: analysis finished ("We'll notify you if you leave" on Analyzing; payload { type: "analysis.done", sessionId } opens Result) and review received (payload { type: "review.received", sessionId } opens Result). A third, player joined for the coach, is a reasonable addition but not promised anywhere.