File size: 44,326 Bytes
92f480e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Verifier for t19 (CGDive's "Rigging isn't Scary" Level 1, parts 1-4, GUI only).

The deliverable is the .blend the agent saved. For every .blend under /root
(preferring /root/rig/rig.blend) the verifier runs Blender headless with
inspect_blend.py to dump the facts the tutorial leaves behind, grades the dump
against a progress-shaped rubric, and keeps the best-scoring file.

GRANULAR, PROGRESS-SHAPED (same philosophy as t17/t18 — Sid: "I just want to
see how far the agent goes"): each check is a pytest test with a
`[verifier] ✓/✗` line; sub-items earn a proportional share; the weights follow
the videos' order so the score reads as "how far into the four parts did it
get". A session fixture scores everything once and writes the weighted
fraction to reward.txt — Harbor reads that.

Bones are located by NAME first (lenient: any separator, any case, Blender's
.L/.R / _L / Left conventions) and by GEOMETRY second (centre-line bones =
spine/neck/head, side bones below the hip = legs, side bones at shoulder
height = arms), so an agent that follows the video but names things slightly
differently is still graded on what it built.

Weights (sum 1.00):
  Part 1  0.35   saved, armature at origin, spine/neck/head chain, leg chain,
                 arm chain, names, symmetrize, parenting, automatic weights
  Part 2  0.25   IK target at the ankle, IK constraint (target, chain 2),
                 pole target + leg at rest, foot parented to the target +
                 Copy Location (head/tail 1), pole parented to target, mirrored
  Part 3  0.25   hat on the head with weights, weight-paint settings, root
                 bone, deform flags off, bone shapes, bone colours, bone
                 collection hidden
  Part 4  0.15   keyframes on the walk frames, contact poses, full cycle,
                 root moving linearly

No-op floor: 0.0 (no .blend under /root/rig on the untouched image; the
untouched start files score only the "saved" half-credit if graded).
"""
from __future__ import annotations

import glob
import json
import math
import os
import re
import subprocess
from pathlib import Path

try:
    import pytest
except ImportError:  # allow importing on hosts without pytest
    class _NoPytest:
        @staticmethod
        def fixture(*a, **k):
            return lambda f: f
    pytest = _NoPytest()  # type: ignore

REWARD_PATH = os.environ.get("REWARD_PATH", "/logs/verifier/reward.txt")
BLENDER = os.environ.get("BLENDER_BIN", "/opt/blender/blender")
INSPECT = os.environ.get("INSPECT_PY", str(Path(__file__).with_name("inspect_blend.py")))
GRADE_DIR = Path(os.environ.get("T19_GRADE_DIR", "/tmp/t19-grade"))
SEARCH_ROOTS = [p for p in os.environ.get("T19_ROOTS", "/root").split(":") if p]
PREFERRED = os.environ.get("T19_PREFERRED", "/root/rig/rig.blend")
START_DIR = os.environ.get("T19_START_DIR", "/root/Downloads/RiS_StartFiles_v2")
IMAGE_STAMP = os.environ.get("T19_IMAGE_STAMP", "/usr/local/bin/start-blender-task")

WEIGHTS = {
    # part 1 (0.35)
    "p1_saved": 0.02, "p1_armature": 0.03, "p1_spine": 0.05, "p1_leg": 0.05, "p1_arm": 0.05,
    "p1_names": 0.03, "p1_symmetrize": 0.04, "p1_parenting": 0.03, "p1_auto_weights": 0.05,
    # part 2 (0.25)
    "p2_ik_target": 0.04, "p2_ik_constraint": 0.06, "p2_pole": 0.05, "p2_foot_fix": 0.04,
    "p2_pole_parent": 0.02, "p2_symmetric": 0.04,
    # part 3 (0.25)
    "p3_hat": 0.04, "p3_weight_paint": 0.02, "p3_root": 0.05, "p3_deform": 0.04,
    "p3_bone_shapes": 0.04, "p3_bone_colors": 0.03, "p3_bone_collections": 0.03,
    # part 4 (0.15)
    "p4_keyframes": 0.04, "p4_contact_poses": 0.04, "p4_cycle": 0.03, "p4_root_motion": 0.04,
}
assert abs(sum(WEIGHTS.values()) - 1.0) < 1e-9, sum(WEIGHTS.values())

WALK_FRAMES = [1, 4, 7, 10, 13, 16, 19, 22, 25]
CHARACTER_HEIGHT = 1.82   # lpMaleG in Beginner_01.blend


# ---------------------------------------------------------------------------
# discovery + dump
# ---------------------------------------------------------------------------

def find_blends() -> list[str]:
    found = []
    try:
        stamp = os.path.getmtime(IMAGE_STAMP)
    except OSError:
        stamp = 0
    for root in SEARCH_ROOTS:
        for depth in ("*.blend", "*/*.blend", "*/*/*.blend", "*/*/*/*.blend"):
            for f in glob.glob(os.path.join(root, depth)):
                if "/.config/" in f or "/.local/" in f or "/.cache/" in f:
                    continue
                if f.endswith(".blend1") or os.path.basename(f) == "quit.blend":
                    continue
                # the shipped start files count only if the agent saved over them
                if f.startswith(START_DIR) and os.path.getmtime(f) <= stamp + 5:
                    continue
                found.append(f)
    found = sorted(set(found), key=lambda f: (f != PREFERRED, -os.path.getmtime(f)))
    return found


def dump(blend: str) -> dict | None:
    GRADE_DIR.mkdir(parents=True, exist_ok=True)
    out = GRADE_DIR / (Path(blend).stem + ".json")
    cmd = [BLENDER, "-b", blend, "-Y", "--python", INSPECT, "--", str(out)]
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, timeout=420,
                           env={**os.environ, "HOME": "/tmp/t19-verifier-home"})
    except subprocess.TimeoutExpired:
        print(f"[verifier] inspect timed out on {blend}")
        return None
    (GRADE_DIR / (Path(blend).stem + ".blender.log")).write_text(r.stdout[-20000:] + "\n---stderr---\n" + r.stderr[-20000:])
    if not out.exists():
        print(f"[verifier] inspect produced no dump for {blend} (rc={r.returncode})")
        return None
    return json.loads(out.read_text())


# ---------------------------------------------------------------------------
# bone identification
# ---------------------------------------------------------------------------

_SIDE_SUFFIX = re.compile(r"^(.*?)[._\- ]([LlRr])$")
_SIDE_PREFIX = re.compile(r"^([LlRr])[._\- ](.*)$")
_SIDE_WORD = re.compile(r"^(.*?)[._\- ]?(left|right)$", re.I)
_SIDE_WORD_PRE = re.compile(r"^(left|right)[._\- ]?(.*)$", re.I)


def split_side(name: str) -> tuple[str, str | None]:
    """('upper_arm', 'L') for 'upper_arm.L', 'L_upper_arm', 'UpperArmLeft'..."""
    for rx, side_group, stem_group in ((_SIDE_SUFFIX, 2, 1), (_SIDE_PREFIX, 1, 2), (_SIDE_WORD, 2, 1), (_SIDE_WORD_PRE, 1, 2)):
        m = rx.match(name)
        if m:
            s = m.group(side_group).lower()
            return m.group(stem_group), ("L" if s.startswith("l") else "R")
    return name, None


def norm(s: str) -> str:
    return re.sub(r"[^a-z0-9]", "", s.lower())


def role_of(stem: str) -> str | None:
    n = norm(stem)
    if not n:
        return None
    if "pole" in n or "knee" in n:
        return "ikpole"
    if "ik" in n or "target" in n or "ctrl" in n or "control" in n:
        return "iktarget"
    if n in ("root", "master", "cog", "main") or n.startswith("root"):
        return "root"
    if "spine" in n or n in ("torso", "body", "chest", "hip", "hips", "pelvis", "back"):
        return "spine"
    if "neck" in n:
        return "neck"
    if n.startswith("head") or n == "skull":
        return "head"
    if "shoulder" in n or "clavicle" in n or "collar" in n:
        return "shoulder"
    if "forearm" in n or ("lower" in n and "arm" in n) or "lowarm" in n or "loarm" in n:
        return "lowerarm"
    if ("upper" in n and "arm" in n) or "uparm" in n or "bicep" in n or n == "arm" or n.startswith("arm"):
        return "upperarm"
    if "hand" in n or "wrist" in n:
        return "hand"
    if "finger" in n or "thumb" in n or "th" == n:
        return "finger"
    if "thigh" in n or ("upper" in n and "leg" in n) or "upleg" in n or n == "leg" or n.startswith("leg"):
        return "thigh"
    if "shin" in n or "calf" in n or ("lower" in n and "leg" in n) or "lowleg" in n:
        return "shin"
    if "foot" in n or "ankle" in n:
        return "foot"
    if "toe" in n:
        return "toe"
    return None


def _armature(d: dict) -> dict | None:
    arms = d.get("armatures") or []
    if not arms:
        return None
    return max(arms, key=lambda a: len(a.get("bones") or []))


def identify(d: dict) -> dict:
    """roles -> bone dicts. Side roles are keyed 'thigh.L' etc."""
    arm = _armature(d)
    ids = {"armature": arm, "by_name": {}, "roles": {}, "unassigned": []}
    if not arm:
        return ids
    bones = arm.get("bones") or []
    by_name = {b["name"]: b for b in bones}
    ids["by_name"] = by_name
    roles: dict[str, list] = {}
    for b in bones:
        stem, side = split_side(b["name"])
        role = role_of(stem)
        if role is None:
            ids["unassigned"].append(b["name"])
            continue
        key = role if role in ("spine", "neck", "head", "root") else f"{role}.{side or '?'}"
        roles.setdefault(key, []).append(b)
    # side inferred from geometry when the name carries none
    for key in list(roles):
        if key.endswith(".?"):
            for b in roles.pop(key):
                side = "L" if b["head"][0] > 0.02 else ("R" if b["head"][0] < -0.02 else "?")
                roles.setdefault(key[:-2] + f".{side}", []).append(b)
    # geometry fallbacks for roles the names did not supply
    def taken():
        return {b["name"] for bl in roles.values() for b in bl}

    def free():
        t = taken()
        return [b for b in bones if b["name"] not in t]

    def near(p, q, tol):
        return dist(p, q) < tol

    if "root" not in roles:
        for b in free():
            if b["parent"] is None and dist(b["head"], [0, 0, 0]) < 0.05 and b["children"]:
                roles["root"] = [b]
                break
    centre = sorted([b for b in free() if abs(b["head"][0]) < 0.04 and abs(b["tail"][0]) < 0.04 and b["head"][2] > 0.3],
                    key=lambda b: b["head"][2])
    if "spine" not in roles and centre:
        low = [b for b in centre if b["head"][2] < 0.78 * CHARACTER_HEIGHT]
        if low:
            roles["spine"] = low
            centre = [b for b in centre if b not in low]
    if "head" not in roles and centre:
        roles["head"] = [centre[-1]]
        centre = centre[:-1]
    if "neck" not in roles and centre:
        roles["neck"] = [centre[-1]]
    centre_names = {b["name"] for k in ("spine", "neck", "head", "root") for b in roles.get(k, [])}
    for side, sgn in (("L", 1), ("R", -1)):
        def sided(bl):
            return [b for b in bl if sgn * b["head"][0] > 0.03]
        # legs: thigh hangs off a centre bone (or nothing) around hip height
        if f"thigh.{side}" not in roles:
            cands = [b for b in sided(free()) if b["head"][2] < 0.65 * CHARACTER_HEIGHT and b["tail"][2] < b["head"][2] - 0.1
                     and (b["parent"] in centre_names or b["parent"] is None)]
            if not cands:
                cands = [b for b in sided(free()) if b["head"][2] < 0.6 * CHARACTER_HEIGHT and b["tail"][2] < b["head"][2] - 0.1]
            if cands:
                roles[f"thigh.{side}"] = [max(cands, key=lambda b: b["head"][2])]
        thigh = one(ids | {"roles": roles}, f"thigh.{side}")
        if thigh and f"shin.{side}" not in roles:
            kids = [by_name[c] for c in thigh["children"] if c in by_name and by_name[c]["name"] not in taken()]
            if kids:
                roles[f"shin.{side}"] = [max(kids, key=lambda b: b["length"])]
        shin = one(ids | {"roles": roles}, f"shin.{side}")
        if shin:
            at_ankle = [b for b in sided(free()) if near(b["head"], shin["tail"], 0.03)]
            # the foot keeps a connected child (the toe) or still hangs off the shin; the IK
            # target is the other bone at the ankle (extruded along Y, parent cleared)
            def is_foot(b):
                conn_child = any(c in by_name and by_name[c]["use_connect"] for c in b["children"])
                return conn_child or b["parent"] == shin["name"]
            feet = [b for b in at_ankle if is_foot(b)]
            others = [b for b in at_ankle if not is_foot(b)]
            if f"foot.{side}" not in roles and feet:
                roles[f"foot.{side}"] = [feet[0]]
            elif f"foot.{side}" not in roles and len(at_ankle) == 1:
                roles[f"foot.{side}"] = [at_ankle[0]]
            foot = one(ids | {"roles": roles}, f"foot.{side}")
            if f"iktarget.{side}" not in roles:
                pool = [b for b in others if b is not foot] or [b for b in at_ankle if b is not foot]
                if pool:
                    roles[f"iktarget.{side}"] = [pool[0]]
            if foot and f"toe.{side}" not in roles:
                kids = [by_name[c] for c in foot["children"] if c in by_name and by_name[c]["name"] not in taken()]
                if kids:
                    roles[f"toe.{side}"] = [kids[0]]
            if f"ikpole.{side}" not in roles:
                knee = shin["head"]
                poles = [b for b in sided(free()) if b["head"][1] < knee[1] - 0.05 and abs(b["head"][2] - knee[2]) < 0.35]
                if poles:
                    roles[f"ikpole.{side}"] = [min(poles, key=lambda b: b["head"][1])]
        # arms: what is left on this side at shoulder height, by increasing |x|
        arms_ = sorted([b for b in sided(free()) if b["head"][2] >= 0.6 * CHARACTER_HEIGHT], key=lambda b: sgn * b["head"][0])
        for role in ("shoulder", "upperarm", "lowerarm", "hand", "finger"):
            if f"{role}.{side}" in roles:
                continue
            if arms_:
                roles[f"{role}.{side}"] = [arms_.pop(0)]
    # the spine chain in z order (spine1 = lowest)
    if "spine" in roles:
        roles["spine"] = sorted(roles["spine"], key=lambda b: b["head"][2])
    ids["roles"] = roles
    return ids


def one(ids, key):
    bl = ids["roles"].get(key)
    return bl[0] if bl else None


def pose_bone(ids, name):
    arm = ids["armature"]
    if not arm or not name:
        return None
    for pb in arm.get("pose_bones") or []:
        if pb["name"] == name:
            return pb
    return None


def cons(ids, bone, ctype):
    pb = pose_bone(ids, bone["name"] if bone else None)
    if not pb:
        return []
    return [c for c in pb["constraints"] if c["type"] == ctype and not c.get("mute")]


def dist(a, b):
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))


def character_mesh(d: dict) -> dict | None:
    meshes = d.get("meshes") or []
    if not meshes:
        return None
    for m in meshes:
        if m["name"].lower().startswith("lpmale"):
            return m
    tall = [m for m in meshes if (m.get("dimensions") or [0, 0, 0])[2] > 1.0]
    return max(tall, key=lambda m: m["verts"]) if tall else max(meshes, key=lambda m: m["verts"])


def hat_mesh(d: dict, char: dict | None) -> dict | None:
    for m in d.get("meshes") or []:
        if m["name"].lower().startswith("hat"):
            return m
    cands = [m for m in d.get("meshes") or [] if m is not char and m["verts"] >= 50 and m["faces"] > 0
             and 0.1 <= max(m["dimensions"][:2]) <= 0.4]
    return cands[0] if cands else None


def deform_bones(ids) -> list:
    out = []
    for key in ("spine", "neck", "head"):
        out += ids["roles"].get(key, [])
    for role in ("shoulder", "upperarm", "lowerarm", "hand", "finger", "thigh", "shin", "foot", "toe"):
        for side in ("L", "R"):
            out += ids["roles"].get(f"{role}.{side}", [])
    return out


def control_bones(ids) -> list:
    out = list(ids["roles"].get("root", []))
    for role in ("iktarget", "ikpole"):
        for side in ("L", "R"):
            out += ids["roles"].get(f"{role}.{side}", [])
    return out


# ---------------------------------------------------------------------------
# checks: each returns (fraction in [0,1], detail string)
# ---------------------------------------------------------------------------

def check_p1_saved(d, ids, blend):
    return (1.0 if blend == PREFERRED else 0.5), f"graded {blend}"


def check_p1_armature(d, ids, blend):
    arm = ids["armature"]
    if not arm:
        return 0.0, "no armature object"
    s, notes = 0.6, [f"armature {arm['name']} ({len(arm['bones'])} bones)"]
    at_origin = all(abs(v) < 0.02 for v in arm["location"]) and all(abs(v) < 1 for v in arm["rotation_deg"]) \
        and all(abs(v - 1) < 0.01 for v in arm["scale"])
    if at_origin:
        s += 0.4; notes.append("identity transform")
    else:
        notes.append(f"moved in object mode: loc {[round(v, 2) for v in arm['location']]} scale {[round(v, 2) for v in arm['scale']]}")
    return s, ", ".join(notes)


def _connected_chain(bones, by_name) -> float:
    """fraction of consecutive pairs where the later bone is a connected child of the earlier."""
    if len(bones) < 2:
        return 0.0
    ok = 0
    for a, b in zip(bones, bones[1:]):
        if b["parent"] == a["name"] and b["use_connect"]:
            ok += 1
    return ok / (len(bones) - 1)


def check_p1_spine(d, ids, blend):
    spine = ids["roles"].get("spine", [])
    neck, head = one(ids, "neck"), one(ids, "head")
    if not spine and not neck and not head:
        return 0.0, "no centre-line bones"
    s, notes = 0.0, []
    n = len(spine)
    s += 0.35 * min(1.0, n / 3); notes.append(f"{n} spine bones")
    centred = [b for b in spine + [x for x in (neck, head) if x] if abs(b["head"][0]) < 0.03 and abs(b["tail"][0]) < 0.03]
    if spine and len(centred) >= len(spine + [x for x in (neck, head) if x]) - 0:
        s += 0.15; notes.append("on the centre line")
    else:
        notes.append(f"{len(centred)} centred")
    chain = spine + [x for x in (neck, head) if x]
    frac = _connected_chain(chain, ids["by_name"])
    s += 0.2 * frac; notes.append(f"connected {frac:.2f}")
    if neck:
        s += 0.12; notes.append(f"neck {neck['name']}")
    if head:
        s += 0.18; notes.append(f"head {head['name']}")
    return min(1.0, s), ", ".join(notes)


def check_p1_leg(d, ids, blend):
    roles = ids["roles"]
    thigh, shin, foot, toe = (one(ids, f"{r}.L") for r in ("thigh", "shin", "foot", "toe"))
    present = [b for b in (thigh, shin, foot, toe) if b]
    if not present:
        return 0.0, "no left leg bones"
    s, notes = 0.15 * len(present), [f"{len(present)}/4 leg bones ({', '.join(b['name'] for b in present)})"]
    chain = [b for b in (thigh, shin, foot, toe) if b]
    frac = _connected_chain(chain, ids["by_name"]) if len(chain) >= 2 else 0.0
    # Part 2 re-parents the foot to the IK target: accept thigh->shin connected + foot/toe anywhere
    if thigh and shin and shin["parent"] == thigh["name"] and shin["use_connect"]:
        frac = max(frac, 0.67 + (0.33 if (toe and foot and toe["parent"] == foot["name"] and toe["use_connect"]) else 0))
    s += 0.2 * frac; notes.append(f"chain {frac:.2f}")
    if thigh and shin:
        hip, knee, ankle = thigh["head"], shin["head"], shin["tail"]
        # knee forward (-Y) of the hip->ankle line
        t = (knee[2] - ankle[2]) / max(1e-6, (hip[2] - ankle[2]))
        line_y = ankle[1] + t * (hip[1] - ankle[1])
        bend = line_y - knee[1]
        if bend > 0.005:
            s += 0.2; notes.append(f"knee bent forward {bend * 100:.1f} cm")
        else:
            notes.append(f"knee not forward ({bend * 100:.1f} cm)")
    return min(1.0, s), ", ".join(notes)


def check_p1_arm(d, ids, blend):
    sh, ua, la, hand, fin = (one(ids, f"{r}.L") for r in ("shoulder", "upperarm", "lowerarm", "hand", "finger"))
    present = [b for b in (sh, ua, la, hand) if b]
    if not present and not fin:
        return 0.0, "no left arm bones"
    s, notes = 0.15 * len(present), [f"{len(present)}/4 arm bones ({', '.join(b['name'] for b in present)})"]
    if fin:
        s += 0.1; notes.append(f"thumb {fin['name']}")
    if ua and la and la["parent"] == ua["name"] and la["use_connect"]:
        s += 0.15; notes.append("lower arm connected")
    if la and hand and hand["parent"] == la["name"] and hand["use_connect"]:
        s += 0.15; notes.append("hand connected")
    return min(1.0, s), ", ".join(notes)


def check_p1_names(d, ids, blend):
    arm = ids["armature"]
    if not arm:
        return 0.0, "no armature"
    names = [b["name"] for b in arm["bones"]]
    generic = [n for n in names if re.match(r"^Bone(\.\d+)?$", n)]
    sided_l = [n for n in names if split_side(n)[1] == "L" and role_of(split_side(n)[0])]
    sided_r = [n for n in names if split_side(n)[1] == "R" and role_of(split_side(n)[0])]
    centre = [n for n in names if split_side(n)[1] is None and role_of(n) in ("spine", "neck", "head", "root")]
    s, notes = 0.0, [f"{len(names)} bones, {len(generic)} still 'Bone*'"]
    s += 0.4 * min(1.0, len(sided_l) / 8); notes.append(f"{len(sided_l)} left-side names")
    s += 0.2 * min(1.0, len(sided_r) / 8); notes.append(f"{len(sided_r)} right-side names")
    s += 0.4 * min(1.0, len(centre) / 5); notes.append(f"{len(centre)} centre names")
    if generic and len(generic) > len(names) * 0.3:
        s *= 0.5; notes.append("mostly unnamed")
    return min(1.0, s), ", ".join(notes)


def check_p1_symmetrize(d, ids, blend):
    roles = ids["roles"]
    left = {k[:-2]: v[0] for k, v in roles.items() if k.endswith(".L") and v}
    right = {k[:-2]: v[0] for k, v in roles.items() if k.endswith(".R") and v}
    if not left:
        return 0.0, "no left-side bones"
    mirrored = 0
    for role, lb in left.items():
        rb = right.get(role)
        if not rb:
            continue
        hm = [-lb["head"][0], lb["head"][1], lb["head"][2]]
        tm = [-lb["tail"][0], lb["tail"][1], lb["tail"][2]]
        if dist(hm, rb["head"]) < 0.02 and dist(tm, rb["tail"]) < 0.02:
            mirrored += 1
    frac = mirrored / len(left)
    s = frac * min(1.0, len(left) / 8)
    return s, f"{mirrored}/{len(left)} left bones have a mirrored right bone"


def check_p1_parenting(d, ids, blend):
    roles = ids["roles"]
    spine_names = {b["name"] for b in roles.get("spine", [])}
    s, notes = 0.0, []
    for side in ("L", "R"):
        sh, ua, th, hand, fin = (one(ids, f"{r}.{side}") for r in ("shoulder", "upperarm", "thigh", "hand", "finger"))
        part = 0.0
        if ua and sh and ua["parent"] == sh["name"]:
            part += 0.25
        if sh and sh["parent"] in spine_names:
            part += 0.25
        if th and th["parent"] in spine_names:
            part += 0.25
        if fin and hand and fin["parent"] == hand["name"]:
            part += 0.25
        elif not fin and hand:
            part += 0.25   # the thumb is optional in the video
        s += part / 2
        notes.append(f"{side}: {part:.2f}")
    return s, "arm->shoulder->spine, thigh->spine, thumb->hand per side: " + ", ".join(notes)


def _armature_mod(mesh, arm):
    for m in mesh.get("modifiers") or []:
        if m["type"] == "ARMATURE" and (arm is None or m.get("object") == arm["name"]):
            return m
    return None


def check_p1_auto_weights(d, ids, blend):
    arm = ids["armature"]
    char = character_mesh(d)
    if not arm or not char:
        return 0.0, "no armature or no character mesh"
    s, notes = 0.0, []
    if _armature_mod(char, arm):
        s += 0.4; notes.append("Armature modifier")
    if char.get("parent") == arm["name"]:
        s += 0.1; notes.append("parented")
    bone_names = {b["name"] for b in arm["bones"]}
    weighted = [g for g in char.get("vertex_groups") or [] if g["name"] in bone_names and g["weighted_verts"] > 0]
    s += 0.5 * min(1.0, len(weighted) / 10); notes.append(f"{len(weighted)} weighted bone groups")
    return min(1.0, s), ", ".join(notes)


def check_p2_ik_target(d, ids, blend):
    shin = one(ids, "shin.L")
    tgt = one(ids, "iktarget.L")
    if not tgt:
        return 0.0, "no IK target bone on the left"
    s, notes = 0.2, [f"target {tgt['name']}"]
    if shin:
        dd = dist(tgt["head"], shin["tail"])
        if dd < 0.03:
            s += 0.5; notes.append(f"at the ankle ({dd * 100:.1f} cm)")
        elif dd < 0.10:
            s += 0.25; notes.append(f"near the ankle ({dd * 100:.1f} cm)")
        else:
            notes.append(f"{dd * 100:.0f} cm from the ankle")
    leg = {b["name"] for r in ("thigh", "shin", "foot", "toe") for b in ids["roles"].get(f"{r}.L", [])}
    if tgt["parent"] is None or (tgt["parent"] not in leg and not tgt["use_connect"]):
        s += 0.3; notes.append("cleared from the leg" + (f" (parent {tgt['parent']})" if tgt["parent"] else ""))
    else:
        notes.append(f"still parented to {tgt['parent']}")
    return min(1.0, s), ", ".join(notes)


def check_p2_ik_constraint(d, ids, blend):
    shin = one(ids, "shin.L")
    tgt = one(ids, "iktarget.L")
    if not shin:
        return 0.0, "no shin"
    iks = cons(ids, shin, "IK")
    if not iks:
        # maybe on the foot or another leg bone
        for r in ("foot", "thigh"):
            b = one(ids, f"{r}.L")
            if b and cons(ids, b, "IK"):
                return 0.2, f"IK constraint on {b['name']} instead of the shin"
        return 0.0, "no IK constraint on the left shin"
    c = iks[0]
    s, notes = 0.4, ["IK on the shin"]
    if tgt and c.get("subtarget") == tgt["name"] and c.get("target") == ids["armature"]["name"]:
        s += 0.3; notes.append(f"target {c['subtarget']}")
    elif c.get("subtarget"):
        s += 0.15; notes.append(f"target {c['subtarget']} (not the identified IK bone)")
    else:
        notes.append("no target")
    if c.get("chain_count") == 2:
        s += 0.3; notes.append("chain 2")
    else:
        notes.append(f"chain {c.get('chain_count')} (want 2)")
    return min(1.0, s), ", ".join(notes)


def _leg_rest_dev(ids, side):
    arm = ids["armature"]
    dev = (arm or {}).get("rest_deviation") or {}
    worst = 0.0
    for r in ("thigh", "shin", "foot"):
        b = one(ids, f"{r}.{side}")
        if b and b["name"] in dev:
            worst = max(worst, dev[b["name"]]["head"], dev[b["name"]]["tail"])
    return worst


def check_p2_pole(d, ids, blend):
    shin = one(ids, "shin.L")
    pole = one(ids, "ikpole.L")
    if not shin:
        return 0.0, "no shin"
    iks = cons(ids, shin, "IK")
    c = iks[0] if iks else None
    s, notes = 0.0, []
    if pole:
        knee = shin["head"]
        if pole["head"][1] < knee[1] - 0.05:
            s += 0.3; notes.append(f"pole {pole['name']} {(knee[1] - pole['head'][1]) * 100:.0f} cm in front of the knee")
        else:
            s += 0.1; notes.append(f"pole {pole['name']} not in front of the knee")
    else:
        notes.append("no pole bone")
    if c and c.get("pole_subtarget"):
        if pole and c["pole_subtarget"] == pole["name"]:
            s += 0.4; notes.append("pole target set")
        else:
            s += 0.2; notes.append(f"pole target {c['pole_subtarget']}")
    else:
        notes.append("no pole target on the IK")
    if c:
        dev = _leg_rest_dev(ids, "L")
        if dev < 0.03:
            s += 0.3; notes.append(f"leg at rest ({dev * 100:.1f} cm)")
        elif dev < 0.10:
            s += 0.15; notes.append(f"leg nearly at rest ({dev * 100:.1f} cm)")
        else:
            notes.append(f"leg flipped/moved at rest ({dev * 100:.0f} cm)")
    return min(1.0, s), ", ".join(notes)


def check_p2_foot_fix(d, ids, blend):
    foot = one(ids, "foot.L")
    tgt = one(ids, "iktarget.L")
    shin = one(ids, "shin.L")
    if not foot:
        return 0.0, "no foot"
    s, notes = 0.0, []
    if tgt and foot["parent"] == tgt["name"] and not foot["use_connect"]:
        s += 0.5; notes.append("foot parented to the IK target")
    else:
        notes.append(f"foot parent {foot['parent']}")
    cl = cons(ids, foot, "COPY_LOCATION")
    if cl:
        c = cl[0]
        if shin and c.get("subtarget") == shin["name"]:
            s += 0.25; notes.append("Copy Location -> shin")
            if (c.get("head_tail") or 0) >= 0.9:
                s += 0.25; notes.append("head/tail 1")
            else:
                notes.append(f"head/tail {c.get('head_tail')}")
        else:
            s += 0.1; notes.append(f"Copy Location -> {c.get('subtarget')}")
    else:
        notes.append("no Copy Location")
    return min(1.0, s), ", ".join(notes)


def check_p2_pole_parent(d, ids, blend):
    pole = one(ids, "ikpole.L")
    tgt = one(ids, "iktarget.L")
    if not pole or not tgt:
        return 0.0, "no pole or no target"
    if pole["parent"] == tgt["name"]:
        return 1.0, "pole parented to the IK target"
    return 0.0, f"pole parent {pole['parent']}"


def check_p2_symmetric(d, ids, blend):
    shin, tgt, pole, foot = (one(ids, f"{r}.R") for r in ("shin", "iktarget", "ikpole", "foot"))
    if not shin:
        return 0.0, "no right shin"
    s, notes = 0.0, []
    iks = cons(ids, shin, "IK")
    if iks:
        c = iks[0]
        s += 0.2; notes.append("IK on shin.R")
        if tgt and c.get("subtarget") == tgt["name"]:
            s += 0.2; notes.append("-> right target")
        if pole and c.get("pole_subtarget") == pole["name"]:
            s += 0.2; notes.append("right pole")
    else:
        notes.append("no IK on the right shin")
    if foot and tgt and foot["parent"] == tgt["name"]:
        s += 0.2; notes.append("foot.R -> target")
    if foot and cons(ids, foot, "COPY_LOCATION"):
        s += 0.2; notes.append("Copy Location on foot.R")
    return min(1.0, s), ", ".join(notes) or "nothing mirrored"


def check_p3_hat(d, ids, blend):
    arm = ids["armature"]
    char = character_mesh(d)
    hat = hat_mesh(d, char)
    if not hat:
        return 0.0, "no hat mesh"
    s, notes = 0.0, [f"hat {hat['name']}"]
    bb = hat.get("bbox")
    head = one(ids, "head")
    if bb:
        cz = bb["center"][2]
        top = char["bbox"]["max"][2] if char and char.get("bbox") else CHARACTER_HEIGHT
        target_z = head["tail"][2] if head else top
        if abs(cz - target_z) < 0.2 and abs(bb["center"][0]) < 0.15:
            s += 0.5; notes.append(f"on the head (z {cz:.2f})")
        elif cz > 0.7 * top:
            s += 0.25; notes.append(f"raised (z {cz:.2f})")
        else:
            notes.append(f"still at z {cz:.2f}")
    if arm and _armature_mod(hat, arm):
        s += 0.25; notes.append("Armature modifier")
    weighted = [g for g in hat.get("vertex_groups") or [] if g["weighted_verts"] > 0]
    if weighted:
        s += 0.25; notes.append(f"{len(weighted)} weighted groups")
    return min(1.0, s), ", ".join(notes)


def check_p3_weight_paint(d, ids, blend):
    sc = d.get("scene") or {}
    char = character_mesh(d)
    s, notes = 0.0, []
    if sc.get("use_auto_normalize"):
        s += 0.7; notes.append("auto normalize on")
    else:
        notes.append("auto normalize off")
    if char and char.get("use_mirror_vertex_groups") and char.get("use_mirror_x"):
        s += 0.3; notes.append("mirror vertex groups + X")
    wp = sc.get("weight_paint") or {}
    if wp.get("blend"):
        notes.append(f"brush blend {wp['blend']} strength {wp.get('strength')}")
    return s, ", ".join(notes)


def check_p3_root(d, ids, blend):
    root = one(ids, "root")
    arm = ids["armature"]
    if not arm:
        return 0.0, "no armature"
    if not root:
        # an unparented, non-deforming bone at the origin that parents the spine
        for b in arm["bones"]:
            if b["parent"] is None and not b["use_deform"] and dist(b["head"], [0, 0, 0]) < 0.05 and b["children"]:
                root = b
                break
    if not root:
        return 0.0, "no root bone"
    s, notes = 0.1, [f"root {root['name']}"]
    if dist(root["head"], [0, 0, 0]) < 0.05:
        s += 0.3; notes.append("at the origin")
    else:
        notes.append(f"head at {[round(v, 2) for v in root['head']]}")
    spine = ids["roles"].get("spine", [])
    if spine and spine[0]["parent"] == root["name"]:
        s += 0.3; notes.append("parents the spine")
    tl, tr = one(ids, "iktarget.L"), one(ids, "iktarget.R")
    n = sum(1 for t in (tl, tr) if t and t["parent"] == root["name"])
    s += 0.15 * n; notes.append(f"parents {n}/2 IK targets")
    return min(1.0, s), ", ".join(notes)


def check_p3_deform(d, ids, blend):
    ctrl = control_bones(ids)
    if not ctrl:
        return 0.0, "no root / IK bones"
    off = [b for b in ctrl if not b["use_deform"]]
    s = 0.6 * len(off) / len(ctrl)
    notes = [f"deform off on {len(off)}/{len(ctrl)} control bones"]
    char = character_mesh(d)
    if char:
        names = {b["name"] for b in ctrl}
        leftover = [g for g in char.get("vertex_groups") or [] if g["name"] in names and g["weighted_verts"] > 0]
        if not leftover and len(off) == len(ctrl):
            s += 0.4; notes.append("weights recalculated (no control-bone groups)")
        elif leftover:
            notes.append(f"{len(leftover)} control-bone groups still weighted")
    return min(1.0, s), ", ".join(notes)


def check_p3_bone_shapes(d, ids, blend):
    arm = ids["armature"]
    if not arm:
        return 0.0, "no armature"
    s, notes = 0.0, []
    shapes = [m for m in d.get("meshes") or [] if ("shape" in m["name"].lower() or "circle" in m["name"].lower()
                                                     or (m["faces"] == 0 and m["verts"] >= 8 and m["edges"] >= 8))]
    if shapes:
        s += 0.3; notes.append(f"shape object {shapes[0]['name']}")
    with_shape = [pb for pb in arm.get("pose_bones") or [] if pb.get("custom_shape")]
    if with_shape:
        s += 0.2; notes.append(f"{len(with_shape)} bones with custom shapes")
        s += 0.3 * min(1.0, len(with_shape) / 12)
    else:
        notes.append("no custom shapes")
    if not arm.get("show_in_front"):
        s += 0.2; notes.append("In Front off")
    else:
        notes.append("In Front still on")
    return min(1.0, s), ", ".join(notes)


def _palette(b):
    c = b.get("color") or {}
    p = c.get("palette")
    return p if p and p != "DEFAULT" else None


def check_p3_bone_colors(d, ids, blend):
    arm = ids["armature"]
    if not arm:
        return 0.0, "no armature"
    pal = {}
    for b in arm["bones"]:
        pal[b["name"]] = _palette(b)
    for pb in arm.get("pose_bones") or []:
        if not pal.get(pb["name"]):
            pal[pb["name"]] = _palette(pb)
    coloured = {k: v for k, v in pal.items() if v}
    if not coloured:
        return 0.0, "no bone colours"
    s, notes = 0.3, [f"{len(coloured)} coloured bones"]
    distinct = set(coloured.values())
    if len(distinct) >= 3:
        s += 0.4; notes.append(f"{len(distinct)} palettes")
    elif len(distinct) == 2:
        s += 0.2; notes.append("2 palettes")
    spine = [pal.get(b["name"]) for b in ids["roles"].get("spine", [])]
    left = {pal.get(b["name"]) for k, bl in ids["roles"].items() if k.endswith(".L") for b in bl} - {None}
    right = {pal.get(b["name"]) for k, bl in ids["roles"].items() if k.endswith(".R") for b in bl} - {None}
    if spine and all(spine) and len(set(spine)) == 1 and left and right and not (left & right):
        s += 0.3; notes.append("spine one colour, left != right")
    return min(1.0, s), ", ".join(notes)


def check_p3_bone_collections(d, ids, blend):
    arm = ids["armature"]
    if not arm:
        return 0.0, "no armature"
    colls = [c for c in arm.get("bone_collections") or [] if c["bones"]]
    total = len(arm["bones"])
    # a collection the agent made: not the default "Bones" holding (nearly) everything
    made = [c for c in colls if not (c["name"].lower() == "bones" and len(c["bones"]) >= total - 2)]
    if not made:
        return 0.0, f"no bone collection besides the default ({len(colls)} in use)"
    legs = {b["name"] for r in ("thigh", "shin", "foot", "toe") for side in ("L", "R") for b in ids["roles"].get(f"{r}.{side}", [])}
    s, notes = 0.4, [f"{len(made)} added bone collection(s): {', '.join(c['name'] for c in made[:3])}"]
    colls = made
    best = None
    for c in colls:
        if c["name"].lower() in ("bones",) and len(c["bones"]) > len(legs):
            continue
        if legs and len(set(c["bones"]) & legs) >= 4:
            best = c
            break
    if best:
        s += 0.3; notes.append(f"'{best['name']}' holds {len(set(best['bones']) & legs)} leg bones")
        if not best["is_visible"]:
            s += 0.3; notes.append("hidden")
    else:
        hidden = [c for c in colls if not c["is_visible"]]
        if hidden:
            s += 0.3; notes.append(f"'{hidden[0]['name']}' hidden")
    return min(1.0, s), ", ".join(notes)


def _anim(ids):
    arm = ids["armature"]
    return (arm or {}).get("animation") or None


def check_p4_keyframes(d, ids, blend):
    a = _anim(ids)
    if not a or not a.get("bones_keyed"):
        return 0.0, "no pose-bone keyframes"
    s, notes = 0.4, [f"action {a['action']}, {a['n_fcurves']} curves"]
    nb = len(a["bones_keyed"])
    if nb >= 5:
        s += 0.2; notes.append(f"{nb} bones keyed")
    else:
        s += 0.1; notes.append(f"only {nb} bones keyed")
    keyed = set(a["keyed_frames"])
    hit = [f for f in WALK_FRAMES if f in keyed]
    if len(hit) >= 8:
        s += 0.4
    elif len(hit) >= 4:
        s += 0.2
    notes.append(f"walk frames keyed: {hit}")
    return min(1.0, s), ", ".join(notes)


def _sample(ids, frame, name, tails=False):
    arm = ids["armature"]
    sm = (arm or {}).get("samples") or {}
    fr = sm.get(str(int(frame)))
    if not fr:
        return None
    return (fr.get("__tails__") or {}).get(name) if tails else fr.get(name)


def _foot_points(ids, frame, side):
    for r in ("iktarget", "foot", "toe"):
        b = one(ids, f"{r}.{side}")
        if b:
            p = _sample(ids, frame, b["name"])
            if p:
                return p
    return None


def check_p4_contact_poses(d, ids, blend):
    a = _anim(ids)
    if not a:
        return 0.0, "no animation"
    s, notes = 0.0, []
    l1, r1 = _foot_points(ids, 1, "L"), _foot_points(ids, 1, "R")
    if l1 and r1:
        sep1 = l1[1] - r1[1]
        if abs(sep1) > 0.15:
            s += 0.4; notes.append(f"frame 1: feet {abs(sep1) * 100:.0f} cm apart")
        else:
            notes.append(f"frame 1: feet only {abs(sep1) * 100:.0f} cm apart")
        l13, r13 = _foot_points(ids, 13, "L"), _foot_points(ids, 13, "R")
        if l13 and r13:
            sep13 = l13[1] - r13[1]
            if abs(sep13) > 0.15 and sep13 * sep1 < 0:
                s += 0.4; notes.append("frame 13: flipped")
            else:
                notes.append(f"frame 13: not flipped ({sep13 * 100:.0f} cm)")
    else:
        notes.append("no foot/IK samples")
    spine = ids["roles"].get("spine", [])
    root = one(ids, "root")
    ref = spine[0] if spine else root
    if ref:
        z4, z10 = _sample(ids, 4, ref["name"]), _sample(ids, 10, ref["name"])
        if z4 and z10 and z10[2] - z4[2] > 0.01:
            s += 0.2; notes.append(f"down (f4) below up (f10) by {(z10[2] - z4[2]) * 100:.1f} cm")
        elif z4 and z10:
            notes.append(f"no down/up bob ({(z10[2] - z4[2]) * 100:.1f} cm)")
    return min(1.0, s), ", ".join(notes)


def check_p4_cycle(d, ids, blend):
    a = _anim(ids)
    sc = d.get("scene") or {}
    if not a:
        return 0.0, "no animation"
    s, notes = 0.0, []
    end = sc.get("frame_end") or 0
    if end >= 24:
        s += 0.3; notes.append(f"frame_end {end}")
    else:
        notes.append(f"frame_end {end} (< 24)")
    arm = ids["armature"]
    sm = arm.get("samples") or {}
    f1, f25 = sm.get("1"), sm.get("25")
    root = one(ids, "root")
    if f1 and f25:
        # compare relative to the root, which walks forward between the two frames
        o1 = f1.get(root["name"]) if root else [0, 0, 0]
        o25 = f25.get(root["name"]) if root else [0, 0, 0]
        o1, o25 = o1 or [0, 0, 0], o25 or [0, 0, 0]
        worst = 0.0
        for name, p in f1.items():
            if name == "__tails__" or (root and name == root["name"]):
                continue
            q = f25.get(name)
            if q:
                worst = max(worst, dist([a - b for a, b in zip(p, o1)], [a - b for a, b in zip(q, o25)]))
        if worst < 0.03 and 25 in set(a["keyed_frames"]):
            s += 0.4; notes.append(f"frame 25 == frame 1 ({worst * 100:.1f} cm)")
        else:
            notes.append(f"frame 25 differs from frame 1 by {worst * 100:.0f} cm")
    keyed = a["keyed_frames"]
    if end >= 48 and keyed and keyed[-1] >= 48:
        s += 0.3; notes.append(f"extended to {keyed[-1]}")
    return min(1.0, s), ", ".join(notes)


def check_p4_root_motion(d, ids, blend):
    a = _anim(ids)
    root = one(ids, "root")
    if not a or not root:
        return 0.0, "no animation or no root"
    s, notes = 0.0, []
    curves = [c for c in a["fcurves"] if c["data_path"] == f'pose.bones["{root["name"]}"].location']
    frames = sorted({round(f) for c in curves for f in c["frames"]})
    if len(frames) >= 2:
        s += 0.3; notes.append(f"root keyed at {frames[:6]}")
    else:
        return 0.0, "root has no location keys"
    p0 = _sample(ids, frames[0], root["name"])
    p1 = _sample(ids, frames[-1], root["name"])
    if p0 and p1:
        dd = dist(p0, p1)
        if dd > 0.5:
            s += 0.4; notes.append(f"moves {dd:.2f} m")
        elif dd > 0.1:
            s += 0.2; notes.append(f"moves only {dd:.2f} m")
        else:
            notes.append("root does not move")
    interps = {i for c in curves for i in c["interpolation"]}
    if interps == {"LINEAR"}:
        s += 0.3; notes.append("linear")
    elif "LINEAR" in interps:
        s += 0.15; notes.append(f"interpolation {sorted(interps)}")
    else:
        notes.append(f"interpolation {sorted(interps)} (want LINEAR)")
    return min(1.0, s), ", ".join(notes)


CHECKS = {name: globals()["check_" + name] for name in WEIGHTS}


def grade(d: dict, blend: str) -> dict:
    ids = identify(d)
    res = {}
    for name, fn in CHECKS.items():
        try:
            frac, note = fn(d, ids, blend)
        except Exception as e:  # noqa: BLE001
            frac, note = 0.0, f"check error: {e!r}"
        res[name] = {"frac": max(0.0, min(1.0, float(frac))), "weight": WEIGHTS[name], "note": note}
    res["_total"] = sum(v["frac"] * v["weight"] for k, v in res.items() if not k.startswith("_"))
    res["_ids"] = {k: [b["name"] for b in v] for k, v in ids["roles"].items()}
    res["_unassigned"] = ids["unassigned"]
    return res


# ---------------------------------------------------------------------------
# pytest plumbing
# ---------------------------------------------------------------------------

@pytest.fixture(scope="session")
def scored():
    blends = find_blends()
    print(f"[verifier] .blend files: {blends or 'none'}")
    best, best_blend = None, None
    for b in blends[:6]:
        d = dump(b)
        if not d:
            continue
        r = grade(d, b)
        (GRADE_DIR / (Path(b).stem + ".grade.json")).write_text(json.dumps(r, indent=1))
        print(f"[verifier] {b}: {r['_total']:.4f}  bones={r['_ids']}")
        if best is None or r["_total"] > best["_total"]:
            best, best_blend = r, b
    if best is None:
        best = {k: {"frac": 0.0, "weight": w, "note": "no .blend graded"} for k, w in WEIGHTS.items()}
        best["_total"] = 0.0
        best["_ids"] = {}
    total = best["_total"]
    Path(REWARD_PATH).parent.mkdir(parents=True, exist_ok=True)
    Path(REWARD_PATH).write_text(f"{total:.4f}\n")
    print(f"[verifier] graded file: {best_blend}")
    for k, v in best.items():
        if k.startswith("_"):
            continue
        mark = "✓" if v["frac"] >= 0.999 else ("~" if v["frac"] > 0 else "✗")
        print(f"[verifier] {mark} {k:<22} {v['frac'] * v['weight']:.3f}/{v['weight']:.2f}  {v['note']}")
    print(f"[verifier] REWARD {total:.4f}")
    return best


def _mk(name):
    def test(scored):
        v = scored[name]
        assert v["frac"] >= 0.999, f"{name}: {v['note']}"
    test.__name__ = f"test_{name}"
    return test


for _n in WEIGHTS:
    globals()[f"test_{_n}"] = _mk(_n)


if __name__ == "__main__":
    # ad-hoc: python3 test_outputs.py dump.json [blend-path]
    import sys
    d = json.load(open(sys.argv[1]))
    r = grade(d, sys.argv[2] if len(sys.argv) > 2 else PREFERRED)
    for k, v in r.items():
        if not k.startswith("_"):
            print(f"{k:<22} {v['frac']:.2f} x {v['weight']:.2f}  {v['note']}")
    print("bones", r["_ids"], "unassigned", r["_unassigned"], "TOTAL", round(r["_total"], 4))