animsmith-core 0.4.1

Engine-agnostic data model, sampling, measurements, and checks for the animsmith animation-clip linter
Documentation
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
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
//! Clip transforms: slice, hold-extend, gait-anchor rotation. The
//! gait test uses an OPEN cyclic loop (no duplicated endpoint key),
//! the shape the rotation semantics are defined for: the wrap step is
//! a real frame and the cycle period is `duration + 1/fps`.

use animsmith_core::model::*;
use animsmith_core::profile::{ResolvedRoles, Role};
use animsmith_core::transform::{
    GAIT_ANCHOR_MAX_HORIZONTAL_ACCUMULATION_M, GAIT_ANCHOR_MAX_TRAJECTORY_POSE_SAMPLES,
    GAIT_ANCHOR_MAX_YAW_ACCUMULATION_DEG, GaitTrajectoryPolicy, align_gait_anchor, hold_extend,
    slice,
};
use glam::{Quat, Vec3};
use std::f64::consts::TAU;

/// Extract a Vec3 track's values, panicking otherwise (test helper).
fn vec3_values(track: &Track) -> Vec<Vec3> {
    match &track.values {
        TrackValues::Vec3s(v) => v.clone(),
        _ => panic!("expected a Vec3 track"),
    }
}

const KEYS: usize = 32; // open loop: one full cycle across KEYS frames
const FPS: f64 = 32.0;

fn skeleton() -> Skeleton {
    Skeleton {
        bones: vec![
            Bone {
                name: "pelvis".into(),
                parent: None,
                rest: Transform {
                    translation: Vec3::new(0.0, 1.0, 0.0),
                    ..Transform::IDENTITY
                },
                inverse_bind: None,
            },
            Bone {
                name: "l_foot".into(),
                parent: Some(0),
                rest: Transform {
                    translation: Vec3::new(0.1, -1.0, 0.0),
                    ..Transform::IDENTITY
                },
                inverse_bind: None,
            },
            Bone {
                name: "r_foot".into(),
                parent: Some(0),
                rest: Transform {
                    translation: Vec3::new(-0.1, -1.0, 0.0),
                    ..Transform::IDENTITY
                },
                inverse_bind: None,
            },
        ],
    }
}

fn roles(skel: &Skeleton) -> ResolvedRoles {
    ResolvedRoles::from_names(
        skel,
        [
            (Role::Hips, "pelvis".to_string()),
            (Role::LeftFoot, "l_foot".to_string()),
            (Role::RightFoot, "r_foot".to_string()),
        ],
    )
}

fn open_loop_foot_track_at_fps(bone: BoneId, rest: Vec3, sign: f32, fps: f64) -> Track {
    let times: Vec<f32> = (0..KEYS).map(|k| (k as f64 / fps) as f32).collect();
    let values: Vec<Vec3> = (0..KEYS)
        .map(|k| {
            let theta = (TAU * k as f64 / KEYS as f64) as f32;
            rest + Vec3::new(0.0, sign * 0.05 * theta.sin(), sign * 0.15 * theta.sin())
        })
        .collect();
    Track {
        bone,
        property: Property::Translation,
        interpolation: Interpolation::Linear,
        times,
        values: TrackValues::Vec3s(values),
    }
}

fn open_walk() -> (Skeleton, Clip) {
    open_walk_at_fps(FPS)
}

fn open_walk_at_fps(fps: f64) -> (Skeleton, Clip) {
    let skel = skeleton();
    let clip = Clip {
        name: "walk".into(),
        duration_s: (KEYS - 1) as f64 / fps,
        tracks: vec![
            open_loop_foot_track_at_fps(1, skel.bones[1].rest.translation, 1.0, fps),
            open_loop_foot_track_at_fps(2, skel.bones[2].rest.translation, -1.0, fps),
        ],
    };
    (skel, clip)
}

fn circular_delta(a: f64, b: f64) -> f64 {
    let d = (a - b).rem_euclid(1.0);
    d.min(1.0 - d)
}

#[test]
fn slice_keeps_window_and_retimes() {
    let (_, mut clip) = open_walk();
    let original = clip.clone();
    slice(&mut clip, 0.25, 0.75, FPS);
    assert!((clip.duration_s - 0.5).abs() < 1e-9);
    let track = &clip.tracks[0];
    let orig_track = &original.tracks[0];

    // The window [0.25, 0.75] with a half-frame epsilon at 32 fps keeps
    // exactly original keys 8..=24 (times 8/32 = 0.25 through 24/32 =
    // 0.75) — 17 keys — retimed so the first lands at 0 and the last at
    // the new 0.5 s duration. Both counts are analytic, not re-derived
    // from the epsilon rule the way the old oracle was.
    const FIRST: usize = 8; // 8/32 = 0.25
    const KEPT: usize = 17; // keys 8..=24 inclusive
    assert_eq!(
        track.key_count(),
        KEPT,
        "kept {} keys, want {KEPT}: {:?}",
        track.key_count(),
        track.times
    );
    assert_eq!(track.times[0], 0.0);
    assert!(
        (track.end_time() - 0.5).abs() < 1e-6,
        "end {}",
        track.end_time()
    );

    // Slice retimes; it never resamples — so every kept key carries its
    // original value verbatim across the WHOLE window (not just key 0),
    // at the fps-grid time (FIRST+i)/32 − 0.25.
    for i in 0..KEPT {
        assert_eq!(
            track.key_vec3(i),
            orig_track.key_vec3(FIRST + i),
            "key {i} value must equal original key {}",
            FIRST + i
        );
        let want_t = ((FIRST + i) as f32 / FPS as f32 - 0.25).clamp(0.0, 0.5);
        assert!(
            (track.times[i] - want_t).abs() < 1e-6,
            "key {i} time {} != {want_t}",
            track.times[i]
        );
    }
}

#[test]
fn hold_extend_appends_final_pose() {
    let (_, mut clip) = open_walk();
    let before_end = clip.tracks[0].end_time();
    let last = clip.tracks[0].key_vec3(clip.tracks[0].key_count() - 1);
    hold_extend(&mut clip, 1.0);
    let track = &clip.tracks[0];
    assert!((track.end_time() - (before_end + 1.0)).abs() < 1e-5);
    assert_eq!(track.key_vec3(track.key_count() - 1), last);
    assert!((clip.duration_s - (before_end as f64 + 1.0)).abs() < 1e-5);
}

#[test]
fn gait_anchor_rotation_moves_phase_to_zero_losslessly() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    let original = clip.clone();

    let outcome = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .expect("aligns");
    // The synthetic L−R foot-height signal is 2A·sin(2πk/32): its
    // fundamental trough sits at key 24 (a quarter cycle before the
    // wrap) — phase 0.75.
    assert!(
        (outcome.phase_before - 0.75).abs() < 0.05,
        "before: {}",
        outcome.phase_before
    );
    // `align_gait_anchor` may apply a ±1-frame wrap nudge: it tries
    // offsets 0/−1/+1 and keeps the cleanest seam. On this symmetric loop
    // the three seams tie, so *which* offset wins is an internal tie-break
    // (candidate order + comparison), not an observable contract — so the
    // test must not pin frame_offset to a specific value. Instead fold the
    // chosen nudge into the expected shift: the ANCHOR itself stays
    // analytically pinned (the trough of sin(2πk/32) is key 24), while the
    // nudge is read back as the one legitimate degree of freedom.
    assert!(
        outcome.frame_offset.abs() <= 1,
        "wrap nudge out of range: {}",
        outcome.frame_offset
    );
    const ANCHOR: i32 = 24; // trough of the L−R sine, analytic
    let shift = (ANCHOR + outcome.frame_offset).rem_euclid(KEYS as i32) as usize;
    // The anchor lands within one frame of its nudge-adjusted target. The
    // bound is deliberately below one frame (0.75/32 < 1/32 ≈ 0.031), so
    // an off-by-one *anchor* rounding cannot satisfy it — unlike the old
    // 0.06 bound (≈ two frames), which let an off-by-one rotation pass.
    let target_phase = ((-outcome.frame_offset) as f64 / KEYS as f64).rem_euclid(1.0);
    assert!(
        circular_delta(outcome.phase_after, target_phase) < 0.75 / KEYS as f64,
        "after: {} (target {target_phase}) — off-by-one anchor rounding?",
        outcome.phase_after
    );
    // Lossless: every rotated key equals the original key `shift` later
    // (the quantized shift lands exactly on an existing key), for EVERY
    // key — not all-but-one. The shift is pinned analytically (ANCHOR 24,
    // not read back from `phase_before`); an off-by-one anchor would shift
    // by 23 or 25 instead of 24 and fail here — the failure the previous
    // oracle (deriving its shift from the impl's own output) could not see.
    let rotated = &clip.tracks[0];
    let orig = &original.tracks[0];
    for k in 0..KEYS {
        let want = orig.key_vec3((k + shift) % KEYS).unwrap();
        let got = rotated.key_vec3(k).unwrap();
        assert!(
            (got - want).length() < 1e-6,
            "key {k}: rotated {got:?} != original key {} {want:?} — not a pure {shift}-frame rotation",
            (k + shift) % KEYS
        );
    }
}

#[test]
fn gait_anchor_permutes_authored_values_and_samples_authored_times_at_30_fps() {
    const NON_BINARY_FPS: f64 = 30.0;
    let (skel, mut clip) = open_walk_at_fps(NON_BINARY_FPS);
    let roles = roles(&skel);
    let original = clip.clone();

    let outcome = align_gait_anchor(
        &skel,
        &mut clip,
        &roles,
        NON_BINARY_FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .expect("30 fps authored grid remains lossless");
    let shift = ((outcome.phase_before * KEYS as f64).round() as i64
        + i64::from(outcome.frame_offset))
    .rem_euclid(KEYS as i64) as usize;
    for (track_index, (before, after)) in original.tracks.iter().zip(&clip.tracks).enumerate() {
        for key in 0..KEYS {
            assert_eq!(
                after.key_vec3(key),
                before.key_vec3((key + shift) % KEYS),
                "track {track_index} key {key} must be an exact authored-value permutation"
            );
        }
    }

    // A selected trajectory rotation with no horizontal forward direction at
    // one exact authored key must be observed at that key. Reconstructing the
    // nominal uniform time through duration*i/N can miss the exact f32 time.
    let (_, mut undefined_forward) = open_walk_at_fps(NON_BINARY_FPS);
    let mut rotations = vec![Quat::IDENTITY; KEYS];
    rotations[5] = Quat::from_rotation_x(std::f32::consts::FRAC_PI_2);
    undefined_forward.tracks.push(Track {
        bone: 0,
        property: Property::Rotation,
        interpolation: Interpolation::Linear,
        times: (0..KEYS)
            .map(|key| (key as f64 / NON_BINARY_FPS) as f32)
            .collect(),
        values: TrackValues::Quats(rotations),
    });
    let error = align_gait_anchor(
        &skel,
        &mut undefined_forward,
        &roles,
        NON_BINARY_FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert!(
        error.contains(
            "no finite horizontal projection for its selected local +Z heading basis at sample 5"
        ),
        "got: {error}"
    );
}

#[test]
fn gait_anchor_refuses_stationary_clips() {
    let skel = skeleton();
    let roles = roles(&skel);
    let mut clip = Clip {
        name: "idle".into(),
        duration_s: 1.0,
        tracks: vec![Track {
            bone: 1,
            property: Property::Translation,
            interpolation: Interpolation::Linear,
            times: (0..8).map(|k| k as f32 / 8.0).collect(),
            values: TrackValues::Vec3s(vec![Vec3::new(0.1, -1.0, 0.0); 8]),
        }],
    };
    let err = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();
    assert!(err.contains("stride anchor"), "got: {err}");
}

fn root_translation(values: impl IntoIterator<Item = Vec3>) -> Track {
    Track {
        bone: 0,
        property: Property::Translation,
        interpolation: Interpolation::Linear,
        times: (0..KEYS).map(|key| key as f32 / FPS as f32).collect(),
        values: TrackValues::Vec3s(values.into_iter().collect()),
    }
}

fn root_yaw(values: impl IntoIterator<Item = f32>) -> Track {
    Track {
        bone: 0,
        property: Property::Rotation,
        interpolation: Interpolation::Linear,
        times: (0..KEYS).map(|key| key as f32 / FPS as f32).collect(),
        values: TrackValues::Quats(values.into_iter().map(Quat::from_rotation_y).collect()),
    }
}

fn vertical_local_forward_basis() -> Quat {
    Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)
}

fn vertical_basis_root_yaw(values: impl IntoIterator<Item = f32>) -> Track {
    let basis = vertical_local_forward_basis();
    Track {
        bone: 0,
        property: Property::Rotation,
        interpolation: Interpolation::Linear,
        times: (0..KEYS).map(|key| key as f32 / FPS as f32).collect(),
        values: TrackValues::Quats(
            values
                .into_iter()
                .map(|yaw| Quat::from_rotation_y(yaw) * basis)
                .collect(),
        ),
    }
}

#[test]
fn gait_anchor_accepts_in_place_motion_when_local_z_is_vertical() {
    let (mut skel, mut clip) = open_walk();
    skel.bones[0].rest.rotation = vertical_local_forward_basis();
    let roles = roles(&skel);

    align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .expect("a fixed horizontal alternative-axis witness admits the vertical-+Z source basis");
}

#[test]
fn gait_anchor_vertical_z_tie_selects_y_once_and_never_falls_back_to_x() {
    let (skel, mut clip) = open_walk();
    // This exact quaternion maps local +Z vertically and gives local +Y and
    // +X exactly equal horizontal projections. Policy must choose +Y.
    let basis = Quat::from_xyzw(-0.5, -0.5, -0.5, 0.5);
    let mut rotations = vec![basis; KEYS];
    rotations[5] = Quat::IDENTITY;
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Rotation,
        interpolation: Interpolation::Linear,
        times: (0..KEYS).map(|key| key as f32 / FPS as f32).collect(),
        values: TrackValues::Quats(rotations),
    });
    let roles = roles(&skel);
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(
        error.contains(
            "no finite horizontal projection for its selected local +Y heading basis at sample 5"
        ),
        "got: {error}"
    );
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_selects_the_genuinely_longest_x_projection() {
    let (skel, mut clip) = open_walk();
    // At sample zero local +X is fully horizontal, +Y has length sqrt(3)/2,
    // and +Z has length 1/2. A first-usable implementation would choose +Z;
    // the greatest-projection policy must retain +X.
    let basis = Quat::from_rotation_x(std::f32::consts::FRAC_PI_3);
    let mut rotations = vec![basis; KEYS];
    rotations[5] = Quat::from_rotation_z(std::f32::consts::FRAC_PI_2);
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Rotation,
        interpolation: Interpolation::Linear,
        times: (0..KEYS).map(|key| key as f32 / FPS as f32).collect(),
        values: TrackValues::Quats(rotations),
    });
    let roles = roles(&skel);
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(
        error.contains(
            "no finite horizontal projection for its selected local +X heading basis at sample 5"
        ),
        "got: {error}"
    );
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_x_basis_measures_accumulated_yaw() {
    let (skel, mut clip) = open_walk();
    let basis = Quat::from_rotation_x(std::f32::consts::FRAC_PI_3);
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Rotation,
        interpolation: Interpolation::Linear,
        times: (0..KEYS).map(|key| key as f32 / FPS as f32).collect(),
        values: TrackValues::Quats(
            (0..KEYS)
                .map(|key| {
                    let yaw = key as f32 * std::f32::consts::FRAC_PI_2 / (KEYS - 1) as f32;
                    Quat::from_rotation_y(yaw) * basis
                })
                .collect(),
        ),
    });
    let roles = roles(&skel);
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert_gait_refusal_is_located_and_atomic(&clip, &before, &error);
    assert!(error.contains("yaw 90.000 deg"), "got: {error}");
}

#[test]
fn gait_anchor_vertical_basis_still_refuses_translation_and_yaw() {
    let (mut skel, base) = open_walk();
    skel.bones[0].rest.rotation = vertical_local_forward_basis();
    let roles = roles(&skel);

    let mut translation = base.clone();
    translation.tracks.push(root_translation(
        (0..KEYS).map(|key| Vec3::new(key as f32 * 0.1, 1.0, 0.0)),
    ));
    let translation_before = format!("{translation:?}");
    let translation_error = align_gait_anchor(
        &skel,
        &mut translation,
        &roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert_gait_refusal_is_located_and_atomic(
        &translation,
        &translation_before,
        &translation_error,
    );
    assert!(
        translation_error.contains("horizontal translation 3.1000 m"),
        "got: {translation_error}"
    );

    let mut yaw = base.clone();
    yaw.tracks
        .push(vertical_basis_root_yaw((0..KEYS).map(|key| {
            key as f32 * std::f32::consts::FRAC_PI_2 / (KEYS - 1) as f32
        })));
    let yaw_before = format!("{yaw:?}");
    let yaw_error =
        align_gait_anchor(&skel, &mut yaw, &roles, FPS, GaitTrajectoryPolicy::InPlace).unwrap_err();
    assert_gait_refusal_is_located_and_atomic(&yaw, &yaw_before, &yaw_error);
    assert!(yaw_error.contains("yaw 90.000 deg"), "got: {yaw_error}");

    let mut nonfinite = base.clone();
    let mut rotations = vec![vertical_local_forward_basis(); KEYS];
    rotations[KEYS / 2] = Quat::from_xyzw(f32::NAN, 0.0, 0.0, 1.0);
    nonfinite.tracks.push(Track {
        bone: 0,
        property: Property::Rotation,
        interpolation: Interpolation::Linear,
        times: (0..KEYS).map(|key| key as f32 / FPS as f32).collect(),
        values: TrackValues::Quats(rotations),
    });
    let nonfinite_before = format!("{nonfinite:?}");
    let nonfinite_error = align_gait_anchor(
        &skel,
        &mut nonfinite,
        &roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert!(
        nonfinite_error.contains("clip \"walk\""),
        "got: {nonfinite_error}"
    );
    assert!(
        nonfinite_error.contains("non-finite authored trajectory evidence in track 2"),
        "got: {nonfinite_error}"
    );
    assert!(
        nonfinite_error.contains("trajectory-preserving operation"),
        "got: {nonfinite_error}"
    );
    assert_eq!(format!("{nonfinite:?}"), nonfinite_before);

    let mut mixed = base;
    mixed.tracks.push(root_translation(
        (0..KEYS).map(|key| Vec3::new(0.0, 1.0, key as f32 * 0.05)),
    ));
    mixed.tracks.push(vertical_basis_root_yaw(
        (0..KEYS).map(|key| key as f32 * std::f32::consts::FRAC_PI_2 / (KEYS - 1) as f32),
    ));
    let mixed_before = format!("{mixed:?}");
    let mixed_error = align_gait_anchor(
        &skel,
        &mut mixed,
        &roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert_gait_refusal_is_located_and_atomic(&mixed, &mixed_before, &mixed_error);
    assert!(mixed_error.contains("1.5500 m"), "got: {mixed_error}");
    assert!(mixed_error.contains("yaw 90.000 deg"), "got: {mixed_error}");
}

fn assert_gait_refusal_is_located_and_atomic(clip: &Clip, before: &str, error: &str) {
    assert!(
        error.contains(&format!("clip {:?}", clip.name)),
        "got: {error}"
    );
    assert!(error.contains("Hips fallback"), "got: {error}");
    assert!(error.contains("pelvis"), "got: {error}");
    assert!(error.contains("horizontal translation"), "got: {error}");
    assert!(error.contains("yaw"), "got: {error}");
    assert!(error.contains("cap 0.0100 m"), "got: {error}");
    assert!(error.contains("cap 1.000 deg"), "got: {error}");
    assert!(error.contains("retain source root motion"), "got: {error}");
    assert!(error.contains("runtime phase offsets"), "got: {error}");
    assert!(
        error.contains("trajectory-preserving operation"),
        "got: {error}"
    );
    assert_eq!(
        format!("{clip:?}"),
        before,
        "refusal must not rewrite the clip"
    );
}

#[test]
fn gait_anchor_refuses_accumulating_root_translation() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.name = "walk_root_motion".into();
    clip.tracks.push(root_translation(
        (0..KEYS).map(|key| Vec3::new(key as f32 * 0.1, 1.0, 0.0)),
    ));
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert_gait_refusal_is_located_and_atomic(&clip, &before, &error);
    assert!(error.contains("3.1000 m"), "got: {error}");
    assert!(error.contains("yaw 0.000 deg"), "got: {error}");
}

#[test]
fn gait_anchor_refuses_accumulating_root_yaw_without_horizontal_speed() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.name = "turn_root_motion".into();
    clip.tracks.push(root_yaw(
        (0..KEYS).map(|key| key as f32 * std::f32::consts::FRAC_PI_2 / (KEYS - 1) as f32),
    ));
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert_gait_refusal_is_located_and_atomic(&clip, &before, &error);
    assert!(error.contains("translation 0.0000 m"), "got: {error}");
    assert!(error.contains("yaw 90.000 deg"), "got: {error}");
}

#[test]
fn gait_anchor_refuses_a_full_turn_even_when_endpoint_heading_aliases_start() {
    const WINDING_FRAMES: usize = 5;
    const WINDING_FPS: f64 = 1.0;
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.name = "full_turn_root_motion".into();
    clip.duration_s = (WINDING_FRAMES - 1) as f64;
    for track in &mut clip.tracks {
        track.times = (0..WINDING_FRAMES).map(|key| key as f32).collect();
        let TrackValues::Vec3s(values) = &mut track.values else {
            unreachable!()
        };
        values.truncate(WINDING_FRAMES);
    }
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Rotation,
        interpolation: Interpolation::Linear,
        times: (0..WINDING_FRAMES).map(|key| key as f32).collect(),
        values: TrackValues::Quats(
            (0..WINDING_FRAMES)
                .map(|key| Quat::from_rotation_y(key as f32 * std::f32::consts::FRAC_PI_2))
                .collect(),
        ),
    });
    let before = format!("{clip:?}");

    let error = align_gait_anchor(
        &skel,
        &mut clip,
        &roles,
        WINDING_FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();

    assert_gait_refusal_is_located_and_atomic(&clip, &before, &error);
    assert!(error.contains("translation 0.0000 m"), "got: {error}");
    assert!(error.contains("yaw 360.000 deg"), "got: {error}");
}

#[test]
fn gait_anchor_refuses_mixed_root_translation_and_yaw() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.name = "arc_root_motion".into();
    clip.tracks.push(root_translation(
        (0..KEYS).map(|key| Vec3::new(0.0, 1.0, key as f32 * 0.05)),
    ));
    clip.tracks.push(root_yaw(
        (0..KEYS).map(|key| key as f32 * std::f32::consts::FRAC_PI_2 / (KEYS - 1) as f32),
    ));
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert_gait_refusal_is_located_and_atomic(&clip, &before, &error);
    assert!(error.contains("1.5500 m"), "got: {error}");
    assert!(error.contains("yaw 90.000 deg"), "got: {error}");
}

#[test]
fn gait_anchor_refuses_abrupt_boundary_translation_and_yaw() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.name = "boundary_jump".into();
    clip.tracks.push(root_translation((0..KEYS).map(|key| {
        if key == 0 {
            Vec3::ZERO
        } else {
            Vec3::new(3.0, 1.0, 0.0)
        }
    })));
    clip.tracks.push(root_yaw(
        (0..KEYS).map(|key| if key == 0 { 0.0 } else { std::f32::consts::PI }),
    ));
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert_gait_refusal_is_located_and_atomic(&clip, &before, &error);
    assert!(error.contains("translation 3.0000 m"), "got: {error}");
    assert!(error.contains("yaw 180.000 deg"), "got: {error}");
}

#[test]
fn gait_anchor_refuses_abrupt_final_boundary_translation_and_yaw() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.name = "final_boundary_jump".into();
    clip.tracks.push(root_translation((0..KEYS).map(|key| {
        if key + 1 == KEYS {
            Vec3::new(3.0, 1.0, 0.0)
        } else {
            Vec3::new(0.0, 1.0, 0.0)
        }
    })));
    clip.tracks.push(root_yaw((0..KEYS).map(|key| {
        if key + 1 == KEYS {
            std::f32::consts::PI
        } else {
            0.0
        }
    })));
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert_gait_refusal_is_located_and_atomic(&clip, &before, &error);
    assert!(error.contains("translation 3.0000 m"), "got: {error}");
    assert!(error.contains("yaw 180.000 deg"), "got: {error}");
}

#[test]
fn gait_anchor_accepts_cyclic_root_translation_and_yaw() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.tracks.push(root_translation((0..KEYS).map(|key| {
        let theta = std::f32::consts::TAU * key as f32 / KEYS as f32;
        Vec3::new(0.05 * theta.sin(), 1.0, 0.05 * theta.cos())
    })));
    clip.tracks.push(root_yaw((0..KEYS).map(|key| {
        let theta = std::f32::consts::TAU * key as f32 / KEYS as f32;
        0.08 * theta.sin()
    })));

    align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .expect("cyclic root/pelvis motion is safe to rotate");
}

fn linear_root_translation_with_accumulation(accumulation_m: f64) -> Track {
    let step = accumulation_m as f32 / (KEYS - 1) as f32;
    root_translation((0..KEYS).map(|key| Vec3::new(step * key as f32, 1.0, 0.0)))
}

fn linear_root_yaw_with_accumulation(accumulation_deg: f64) -> Track {
    let step_rad = (accumulation_deg as f32 / (KEYS - 1) as f32).to_radians();
    root_yaw((0..KEYS).map(|key| step_rad * key as f32))
}

#[test]
fn gait_anchor_policy_pins_translation_and_yaw_caps() {
    let (skel, base) = open_walk();
    let roles = roles(&skel);

    let mut inside = base.clone();
    inside
        .tracks
        .push(linear_root_translation_with_accumulation(
            GAIT_ANCHOR_MAX_HORIZONTAL_ACCUMULATION_M * 0.99,
        ));
    inside.tracks.push(linear_root_yaw_with_accumulation(
        GAIT_ANCHOR_MAX_YAW_ACCUMULATION_DEG * 0.99,
    ));
    align_gait_anchor(
        &skel,
        &mut inside,
        &roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .expect("facts immediately inside both fixed caps are admitted");

    let mut at_cap = base.clone();
    at_cap.tracks.push(root_translation((0..KEYS).map(|key| {
        Vec3::new(
            if key + 1 == KEYS {
                GAIT_ANCHOR_MAX_HORIZONTAL_ACCUMULATION_M as f32
            } else {
                0.0
            },
            1.0,
            0.0,
        )
    })));
    at_cap.tracks.push(root_yaw((0..KEYS).map(|key| {
        if key + 1 == KEYS {
            (GAIT_ANCHOR_MAX_YAW_ACCUMULATION_DEG as f32).to_radians()
        } else {
            0.0
        }
    })));
    align_gait_anchor(
        &skel,
        &mut at_cap,
        &roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .expect("facts exactly at both inclusive fixed caps are admitted");

    let mut translation_outside = base.clone();
    translation_outside
        .tracks
        .push(linear_root_translation_with_accumulation(
            GAIT_ANCHOR_MAX_HORIZONTAL_ACCUMULATION_M * 1.01,
        ));
    let translation_error = align_gait_anchor(
        &skel,
        &mut translation_outside,
        &roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert!(
        translation_error.contains("horizontal translation 0.0101 m"),
        "got: {translation_error}"
    );
    assert!(
        translation_error.contains("cap 0.0100 m"),
        "got: {translation_error}"
    );
    assert!(
        translation_error.contains("cap 1.000 deg"),
        "got: {translation_error}"
    );

    let mut yaw_outside = base;
    yaw_outside.tracks.push(linear_root_yaw_with_accumulation(
        GAIT_ANCHOR_MAX_YAW_ACCUMULATION_DEG * 1.000_01,
    ));
    let yaw_error = align_gait_anchor(
        &skel,
        &mut yaw_outside,
        &roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert!(yaw_error.contains("and yaw "), "got: {yaw_error}");
    assert!(yaw_error.contains("cap 0.0100 m"), "got: {yaw_error}");
    assert!(yaw_error.contains("cap 1.000 deg"), "got: {yaw_error}");
}

fn long_walk_with_distributed_yaw(accumulation_deg: f64) -> (Skeleton, Clip) {
    const LONG_FRAMES: usize = 100_001;
    const LONG_FPS: f64 = 100_000.0;
    let skel = skeleton();
    let times: Vec<f32> = (0..LONG_FRAMES)
        .map(|key| (key as f64 / LONG_FPS) as f32)
        .collect();
    let rest_translations: Vec<Vec3> = skel
        .bones
        .iter()
        .map(|bone| bone.rest.translation)
        .collect();
    let foot = |bone: usize, sign: f32| Track {
        bone,
        property: Property::Translation,
        interpolation: Interpolation::Linear,
        times: times.clone(),
        values: TrackValues::Vec3s(
            (0..LONG_FRAMES)
                .map(|key| {
                    let theta = (TAU * key as f64 / LONG_FRAMES as f64) as f32;
                    rest_translations[bone]
                        + Vec3::new(0.0, sign * 0.05 * theta.sin(), sign * 0.15 * theta.sin())
                })
                .collect(),
        ),
    };
    let yaw = Track {
        bone: 0,
        property: Property::Rotation,
        interpolation: Interpolation::Linear,
        times: times.clone(),
        values: TrackValues::Quats(
            (0..LONG_FRAMES)
                .map(|key| {
                    let degrees = accumulation_deg * key as f64 / (LONG_FRAMES - 1) as f64;
                    Quat::from_rotation_y((degrees as f32).to_radians())
                })
                .collect(),
        ),
    };
    (
        skel,
        Clip {
            name: "long_distributed_yaw".into(),
            duration_s: (LONG_FRAMES - 1) as f64 / LONG_FPS,
            tracks: vec![foot(1, 1.0), foot(2, -1.0), yaw],
        },
    )
}

#[test]
fn gait_anchor_long_grid_yaw_cap_is_stable_and_minimally_above_refuses() {
    const LONG_FPS: f64 = 100_000.0;
    let (skel, mut at_cap) = long_walk_with_distributed_yaw(GAIT_ANCHOR_MAX_YAW_ACCUMULATION_DEG);
    let resolved_roles = roles(&skel);
    align_gait_anchor(
        &skel,
        &mut at_cap,
        &resolved_roles,
        LONG_FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .expect("100,000 distributed yaw steps at the exact inclusive cap are admitted");

    let (skel, mut above) =
        long_walk_with_distributed_yaw(GAIT_ANCHOR_MAX_YAW_ACCUMULATION_DEG * 1.000_01);
    let resolved_roles = roles(&skel);
    let last_before = above.tracks[2].key_quat(100_000);
    let error = align_gait_anchor(
        &skel,
        &mut above,
        &resolved_roles,
        LONG_FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert!(error.contains("and yaw "), "got: {error}");
    assert!(error.contains("cap 1.000 deg"), "got: {error}");
    assert_eq!(above.tracks[2].key_quat(100_000), last_before);
}

#[test]
fn gait_anchor_fails_closed_without_root_or_hips_evidence() {
    let (skel, mut clip) = open_walk();
    let roles = ResolvedRoles::from_names(
        &skel,
        [
            (Role::LeftFoot, "l_foot".to_string()),
            (Role::RightFoot, "r_foot".to_string()),
        ],
    );
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(error.contains("walk"), "got: {error}");
    assert!(error.contains("evidence is missing"), "got: {error}");
    assert!(error.contains("retain source root motion"), "got: {error}");
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_fails_closed_on_out_of_range_selected_role() {
    let (mut skel, mut clip) = open_walk();
    let roles = roles(&skel);
    skel.bones.clear();
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(error.contains("Hips fallback"), "got: {error}");
    assert!(
        error.contains("index 0 is outside the skeleton"),
        "got: {error}"
    );
    assert!(error.contains("evidence is missing"), "got: {error}");
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_fails_closed_on_out_of_range_ancestor() {
    let (mut skel, mut clip) = open_walk();
    skel.bones[0].parent = Some(99);
    let roles = roles(&skel);
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(error.contains("pelvis"), "got: {error}");
    assert!(
        error.contains("out-of-range ancestor index 99"),
        "got: {error}"
    );
    assert!(error.contains("evidence is missing"), "got: {error}");
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_fails_closed_on_cyclic_ancestor_chain() {
    let (mut skel, mut clip) = open_walk();
    skel.bones[0].parent = Some(0);
    let roles = roles(&skel);
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(error.contains("pelvis"), "got: {error}");
    assert!(error.contains("cyclic ancestor chain"), "got: {error}");
    assert!(error.contains("evidence is missing"), "got: {error}");
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_fails_closed_on_non_finite_root_evidence() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.tracks.push(root_translation((0..KEYS).map(|key| {
        if key == KEYS / 2 {
            Vec3::new(f32::NAN, 1.0, 0.0)
        } else {
            Vec3::new(0.0, 1.0, 0.0)
        }
    })));
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(error.contains("walk"), "got: {error}");
    assert!(
        error.contains("non-finite authored trajectory evidence"),
        "got: {error}"
    );
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_fails_closed_on_non_finite_authored_interval_between_samples() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.name = "hidden_nan".into();
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Translation,
        interpolation: Interpolation::Step,
        times: vec![0.0, 0.0001, 0.0002, clip.duration_s as f32],
        values: TrackValues::Vec3s(vec![
            Vec3::ZERO,
            Vec3::splat(f32::NAN),
            Vec3::ZERO,
            Vec3::ZERO,
        ]),
    });
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(
        error.contains("non-finite authored trajectory evidence in track 2"),
        "got: {error}"
    );
    assert!(error.contains("hidden_nan"), "got: {error}");
    assert!(error.contains("retain source root motion"), "got: {error}");
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_fails_closed_on_finite_step_turn_between_uniform_samples() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.name = "hidden_full_turn".into();
    let mut times: Vec<f32> = (0..KEYS).map(|key| key as f32 / FPS as f32).collect();
    times[1..5].copy_from_slice(&[0.001, 0.002, 0.003, 0.004]);
    let mut values = vec![Quat::IDENTITY; KEYS];
    for (slot, degrees) in values[..5]
        .iter_mut()
        .zip([0.0f32, 90.0, 180.0, 270.0, 360.0])
    {
        *slot = Quat::from_rotation_y(degrees.to_radians());
    }
    values[5..].fill(Quat::from_rotation_y(std::f32::consts::TAU));
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Rotation,
        interpolation: Interpolation::Step,
        times,
        values: TrackValues::Quats(values),
    });
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(error.contains("hidden_full_turn"), "got: {error}");
    assert!(error.contains("Hips fallback"), "got: {error}");
    assert!(error.contains("pelvis"), "got: {error}");
    assert!(
        error.contains("duplicate/non-frame-aligned whole-frame trajectory evidence"),
        "got: {error}"
    );
    assert!(error.contains("track 2, key 1"), "got: {error}");
    assert!(error.contains("retain source root motion"), "got: {error}");
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_fails_closed_on_non_frame_aligned_trajectory_key() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    let mut yaw = root_yaw((0..KEYS).map(|key| {
        let theta = std::f32::consts::TAU * key as f32 / KEYS as f32;
        0.1 * theta.sin()
    }));
    yaw.times[5] += 0.001;
    clip.tracks.push(yaw);
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(
        error.contains("duplicate/non-frame-aligned whole-frame trajectory evidence"),
        "got: {error}"
    );
    assert!(error.contains("track 2, key 5"), "got: {error}");
    assert!(error.contains("32 fps"), "got: {error}");
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_fails_closed_on_duplicate_declared_frame_key() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    let mut yaw = root_yaw((0..KEYS).map(|key| {
        let theta = std::f32::consts::TAU * key as f32 / KEYS as f32;
        0.1 * theta.sin()
    }));
    yaw.times[5] = yaw.times[4];
    clip.tracks.push(yaw);
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(
        error.contains("duplicate/non-frame-aligned whole-frame trajectory evidence"),
        "got: {error}"
    );
    assert!(error.contains("track 2, key 5"), "got: {error}");
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_fails_closed_on_sparse_frame_aligned_selected_trajectory() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    // This in-place bump is keyed on declared frames but omits the frames a
    // gait phase shift can target. Resampling it at the unchanged three key
    // times would synthesize new values instead of permuting authored keys.
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Translation,
        interpolation: Interpolation::Linear,
        times: vec![0.0, 1.0 / FPS as f32, clip.duration_s as f32],
        values: TrackValues::Vec3s(vec![
            Vec3::new(0.0, 1.0, 0.0),
            Vec3::new(0.005, 1.0, 0.0),
            Vec3::new(0.0, 1.0, 0.0),
        ]),
    });
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(
        error.contains("incomplete whole-frame rotation evidence in track 2"),
        "got: {error}"
    );
    assert!(
        error.contains("3 keys instead of exactly 32"),
        "got: {error}"
    );
    assert!(error.contains("retain source root motion"), "got: {error}");
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_fails_closed_before_oversized_trajectory_grid_allocation() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    let frames = GAIT_ANCHOR_MAX_TRAJECTORY_POSE_SAMPLES / skel.bones.len() + 1;
    clip.name = "oversized_grid".into();
    clip.duration_s = (frames - 1) as f64;
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, 1.0, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert!(error.contains("oversized_grid"), "got: {error}");
    assert!(error.contains("trajectory pose samples"), "got: {error}");
    assert!(error.contains("333334 frames x 3 bones"), "got: {error}");
    assert!(
        error.contains("1000000 sample safety budget"),
        "got: {error}"
    );
    assert_eq!(format!("{clip:?}"), before);
}

fn extend_skeleton_to(skeleton: &mut Skeleton, count: usize) {
    while skeleton.bones.len() < count {
        skeleton.bones.push(Bone {
            name: format!("unused_{}", skeleton.bones.len()),
            parent: None,
            rest: Transform::IDENTITY,
            inverse_bind: None,
        });
    }
}

#[test]
fn gait_anchor_bounds_unrelated_authored_key_work_before_sampling() {
    let (mut skel, mut clip) = open_walk();
    extend_skeleton_to(&mut skel, 100);
    let roles = roles(&skel);
    clip.name = "unrelated_key_bomb".into();
    clip.tracks.push(Track {
        bone: 99,
        property: Property::Scale,
        interpolation: Interpolation::Linear,
        times: (0..20_001).map(|key| key as f32).collect(),
        values: TrackValues::Vec3s(vec![Vec3::ONE; 20_001]),
    });
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();
    assert!(error.contains("2000100 pose samples"), "got: {error}");
    assert!(error.contains("sample safety budget"), "got: {error}");
    assert_eq!(format!("{clip:?}"), before);
}

#[test]
fn gait_anchor_rejects_duplicate_channels_before_sampling_or_mutation() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    for _ in 0..2_001 {
        clip.tracks.push(Track {
            bone: 0,
            property: Property::Scale,
            interpolation: Interpolation::Linear,
            times: vec![0.0],
            values: TrackValues::Vec3s(vec![Vec3::ONE]),
        });
    }
    let track_count = clip.tracks.len();
    let first = clip.tracks[2].key_vec3(0);
    let last = clip.tracks.last().and_then(|track| track.key_vec3(0));

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();
    assert!(
        error.contains("track 3 duplicates the scale channel"),
        "got: {error}"
    );
    assert_eq!(clip.tracks.len(), track_count);
    assert_eq!(clip.tracks[2].key_vec3(0), first);
    assert_eq!(clip.tracks.last().and_then(|track| track.key_vec3(0)), last);
}

#[test]
fn gait_anchor_bounds_frame_by_track_sampling_work() {
    let (mut skel, mut clip) = open_walk();
    extend_skeleton_to(&mut skel, 10_500);
    let roles = roles(&skel);
    for bone in 0..skel.bones.len() {
        for property in [Property::Rotation, Property::Scale] {
            let values = if property == Property::Rotation {
                TrackValues::Quats(vec![Quat::IDENTITY])
            } else {
                TrackValues::Vec3s(vec![Vec3::ONE])
            };
            clip.tracks.push(Track {
                bone,
                property,
                interpolation: Interpolation::Linear,
                times: vec![0.0],
                values,
            });
        }
        if bone != 1 && bone != 2 {
            clip.tracks.push(Track {
                bone,
                property: Property::Translation,
                interpolation: Interpolation::Linear,
                times: vec![0.0],
                values: TrackValues::Vec3s(vec![skel.bones[bone].rest.translation]),
            });
        }
    }
    let track_count = clip.tracks.len();

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();
    assert!(error.contains("1008000 channel samples"), "got: {error}");
    assert!(error.contains("32 frames x 31500 tracks"), "got: {error}");
    assert_eq!(clip.tracks.len(), track_count);
}

#[test]
fn gait_anchor_validates_the_whole_skeleton_and_every_metric_role() {
    let (mut child_first, mut clip) = open_walk();
    child_first.bones[0].parent = Some(2);
    let child_roles = roles(&child_first);
    let before = format!("{clip:?}");
    let error = align_gait_anchor(
        &child_first,
        &mut clip,
        &child_roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert!(error.contains("parents-before-children"), "got: {error}");
    assert_eq!(format!("{clip:?}"), before);

    let (mut unrelated_bad, mut clip) = open_walk();
    unrelated_bad.bones.push(Bone {
        name: "unrelated".into(),
        parent: Some(99),
        rest: Transform::IDENTITY,
        inverse_bind: None,
    });
    let unrelated_roles = roles(&unrelated_bad);
    let error = align_gait_anchor(
        &unrelated_bad,
        &mut clip,
        &unrelated_roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert!(error.contains("unrelated"), "got: {error}");
    assert!(
        error.contains("out-of-range ancestor index 99"),
        "got: {error}"
    );

    let (mut mismatched_role, mut clip) = open_walk();
    let mismatched_roles = roles(&mismatched_role);
    mismatched_role.bones.pop();
    let error = align_gait_anchor(
        &mismatched_role,
        &mut clip,
        &mismatched_roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert!(error.contains("right_foot bone index 2"), "got: {error}");
}

#[test]
fn gait_anchor_requires_a_dense_grid_for_unrelated_motion_and_exact_duration() {
    let (mut skel, mut sparse) = open_walk();
    extend_skeleton_to(&mut skel, 4);
    let sparse_roles = roles(&skel);
    sparse.tracks.push(Track {
        bone: 3,
        property: Property::Scale,
        interpolation: Interpolation::Linear,
        times: vec![0.0, sparse.duration_s as f32],
        values: TrackValues::Vec3s(vec![Vec3::ONE, Vec3::splat(2.0)]),
    });
    let before = format!("{sparse:?}");
    let error = align_gait_anchor(
        &skel,
        &mut sparse,
        &sparse_roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert!(error.contains("track 2"), "got: {error}");
    assert!(
        error.contains("2 keys instead of exactly 32"),
        "got: {error}"
    );
    assert_eq!(format!("{sparse:?}"), before);

    let (skel, mut off_frame) = open_walk();
    let off_frame_roles = roles(&skel);
    let duration = off_frame.duration_s as f32;
    off_frame.duration_s = f64::from(f32::from_bits(duration.to_bits() + 1));
    let error = align_gait_anchor(
        &skel,
        &mut off_frame,
        &off_frame_roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert!(error.contains("key 31"), "got: {error}");
    assert!(error.contains("required frame time"), "got: {error}");
}

#[test]
fn gait_anchor_rejects_vec3_quaternion_and_cubic_cardinality_mismatches() {
    let (skel, base) = open_walk();
    let roles = roles(&skel);
    for (label, values, interpolation) in [
        (
            "vec3",
            TrackValues::Vec3s(vec![Vec3::ZERO; KEYS - 1]),
            Interpolation::Linear,
        ),
        (
            "quaternion",
            TrackValues::Quats(vec![Quat::IDENTITY; KEYS - 1]),
            Interpolation::Linear,
        ),
        (
            "cubic",
            TrackValues::Vec3s(vec![Vec3::ZERO; KEYS * 3 - 1]),
            Interpolation::CubicSpline,
        ),
    ] {
        let mut clip = base.clone();
        clip.tracks.push(Track {
            bone: 0,
            property: if label == "quaternion" {
                Property::Rotation
            } else {
                Property::Translation
            },
            interpolation,
            times: (0..KEYS).map(|key| key as f32 / FPS as f32).collect(),
            values,
        });
        let before = format!("{clip:?}");
        let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
            .unwrap_err();
        assert!(error.contains("track 2"), "{label}: {error}");
        assert!(error.contains("expected exactly"), "{label}: {error}");
        assert_eq!(format!("{clip:?}"), before);
    }
}

#[test]
fn interior_outliers_never_mask_endpoint_translation_or_yaw() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.name = "outlier_mask".into();
    let mut translations = vec![Vec3::ZERO; KEYS];
    translations[10].x = 100.0;
    translations[11].x = -100.0;
    translations[KEYS - 1].x = 3.0;
    clip.tracks.push(root_translation(translations));
    let mut yaws = vec![0.0; KEYS];
    yaws[10] = 170.0f32.to_radians();
    yaws[11] = (-170.0f32).to_radians();
    yaws[KEYS - 1] = 90.0f32.to_radians();
    clip.tracks.push(root_yaw(yaws));

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();
    assert!(error.contains("translation 3.0000 m"), "got: {error}");
    assert!(error.contains("and yaw "), "got: {error}");
    assert!(error.contains("cap 1.000 deg"), "got: {error}");
}

#[test]
fn gait_anchor_pose_budget_is_inclusive_at_the_exact_cap() {
    let (mut skel, mut at_cap) = open_walk();
    extend_skeleton_to(&mut skel, 100);
    let roles = roles(&skel);
    at_cap.duration_s = 9_999.0;
    let at_cap_error = align_gait_anchor(
        &skel,
        &mut at_cap,
        &roles,
        1.0,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert!(
        !at_cap_error.contains("above the 1000000 sample safety budget"),
        "exactly 1,000,000 samples must pass the budget gate: {at_cap_error}"
    );
    assert!(at_cap_error.contains("incomplete whole-frame"));

    let (_, mut above) = open_walk();
    above.duration_s = 10_000.0;
    let error = align_gait_anchor(
        &skel,
        &mut above,
        &roles,
        1.0,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();
    assert!(
        error.contains("1000100 trajectory pose samples"),
        "got: {error}"
    );
    assert!(error.contains("above the 1000000 sample safety budget"));
}

#[test]
fn gait_anchor_fails_closed_on_unrepresentable_trajectory_grid() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.name = "overflowing_grid".into();
    let before = format!("{clip:?}");

    let error = align_gait_anchor(
        &skel,
        &mut clip,
        &roles,
        f64::MAX,
        GaitTrajectoryPolicy::InPlace,
    )
    .unwrap_err();

    assert!(error.contains("overflowing_grid"), "got: {error}");
    assert!(
        error.contains("sample count that cannot be represented on this platform"),
        "got: {error}"
    );
    assert_eq!(format!("{clip:?}"), before);
}

fn open_walk_with_motion_ancestor() -> (Skeleton, Clip) {
    let (old_skel, mut clip) = open_walk();
    let mut bones = vec![Bone {
        name: "motion_root".into(),
        parent: None,
        rest: Transform::IDENTITY,
        inverse_bind: None,
    }];
    bones.extend(old_skel.bones.into_iter().map(|mut bone| {
        bone.parent = bone.parent.map(|parent| parent + 1).or(Some(0));
        bone
    }));
    for track in &mut clip.tracks {
        track.bone += 1;
    }
    (Skeleton { bones }, clip)
}

#[test]
fn gait_anchor_measures_ancestor_driven_model_space_trajectory() {
    let (skel, mut clip) = open_walk_with_motion_ancestor();
    clip.name = "ancestor_driven".into();
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Translation,
        interpolation: Interpolation::Linear,
        times: (0..KEYS).map(|key| key as f32 / FPS as f32).collect(),
        values: TrackValues::Vec3s(
            (0..KEYS)
                .map(|key| Vec3::new(key as f32 * 0.1, 0.0, 0.0))
                .collect(),
        ),
    });
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Rotation,
        interpolation: Interpolation::Linear,
        times: (0..KEYS).map(|key| key as f32 / FPS as f32).collect(),
        values: TrackValues::Quats(
            (0..KEYS)
                .map(|key| {
                    Quat::from_rotation_y(
                        key as f32 * std::f32::consts::FRAC_PI_2 / (KEYS - 1) as f32,
                    )
                })
                .collect(),
        ),
    });
    let roles = roles(&skel);
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert_gait_refusal_is_located_and_atomic(&clip, &before, &error);
    assert!(error.contains("3.1000 m"), "got: {error}");
    assert!(error.contains("yaw 90.000 deg"), "got: {error}");
}

#[test]
fn gait_anchor_measures_ancestor_scale_in_model_space_trajectory() {
    let (mut skel, mut clip) = open_walk_with_motion_ancestor();
    // Hips is one metre to the side of its ancestor, so ancestor scale moves
    // the selected Hips origin horizontally even without a translation track.
    skel.bones[1].rest.translation.x = 1.0;
    clip.name = "ancestor_scale".into();
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Scale,
        interpolation: Interpolation::Linear,
        times: (0..KEYS).map(|key| key as f32 / FPS as f32).collect(),
        values: TrackValues::Vec3s(
            (0..KEYS)
                .map(|key| Vec3::splat(1.0 + key as f32 / (KEYS - 1) as f32))
                .collect(),
        ),
    });
    let roles = roles(&skel);
    let before = format!("{clip:?}");

    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();

    assert_gait_refusal_is_located_and_atomic(&clip, &before, &error);
    assert!(error.contains("1.0000 m"), "got: {error}");
    assert!(error.contains("yaw 0.000 deg"), "got: {error}");
}

#[test]
fn hold_extend_handles_cubic_tracks() {
    let (_, mut clip) = open_walk();
    // Rebuild track 0 as CUBICSPLINE with zero tangents.
    let orig = clip.tracks[0].clone();
    let TrackValues::Vec3s(vals) = &orig.values else {
        unreachable!()
    };
    let mut cubic_vals = Vec::new();
    for v in vals {
        cubic_vals.push(Vec3::ZERO);
        cubic_vals.push(*v);
        cubic_vals.push(Vec3::ZERO);
    }
    clip.tracks[0] = Track {
        interpolation: Interpolation::CubicSpline,
        values: TrackValues::Vec3s(cubic_vals),
        ..orig.clone()
    };
    let last_value = orig.key_vec3(orig.key_count() - 1).unwrap();
    hold_extend(&mut clip, 0.5);
    let track = &clip.tracks[0];
    assert_eq!(track.key_count(), orig.key_count() + 1);
    assert_eq!(track.key_vec3(track.key_count() - 1), Some(last_value));
    // The appended triplet has zero tangents (flat hold).
    let TrackValues::Vec3s(v) = &track.values else {
        unreachable!()
    };
    assert_eq!(v[v.len() - 3], Vec3::ZERO);
    assert_eq!(v[v.len() - 1], Vec3::ZERO);
}

/// #26: keys denser than the fps within the start epsilon must not all
/// collapse onto t=0, and a key just past the end must clamp into the
/// window rather than exceed the declared duration.
#[test]
fn slice_dedupes_start_boundary_and_clamps_end() {
    // fps=30 → eps = 1/60 ≈ 0.0167. Three keys fall within [start-eps,
    // start]; one falls within (end, end+eps].
    let times: Vec<f32> = vec![0.24, 0.245, 0.25, 0.40, 0.60, 0.75, 0.7575];
    let values: Vec<Vec3> = (0..times.len())
        .map(|i| Vec3::new(i as f32, 0.0, 0.0))
        .collect();
    let mut clip = Clip {
        name: "dense".into(),
        duration_s: 1.0,
        tracks: vec![Track {
            bone: 0,
            property: Property::Translation,
            interpolation: Interpolation::Linear,
            times,
            values: TrackValues::Vec3s(values),
        }],
    };

    slice(&mut clip, 0.25, 0.75, 30.0);
    let t = &clip.tracks[0];

    assert_eq!(
        t.times.iter().filter(|&&x| x == 0.0).count(),
        1,
        "at most one key at t=0: {:?}",
        t.times
    );
    for w in t.times.windows(2) {
        assert!(
            w[1] > w[0],
            "times must be strictly increasing: {:?}",
            t.times
        );
    }
    assert!(
        t.end_time() <= 0.5 + 1e-6,
        "last key {} exceeds duration 0.5",
        t.end_time()
    );
    assert!((clip.duration_s - 0.5).abs() < 1e-9);
    // Every surviving key keeps its original value (losslessness): the
    // boundary keys are the ones closest to the window — 0.25 (value 2)
    // and 0.75 (value 5) — and the interior keys 0.40/0.60 carry values
    // 3 and 4 verbatim.
    assert_eq!(
        (0..t.key_count())
            .map(|k| t.key_vec3(k).unwrap().x)
            .collect::<Vec<_>>(),
        vec![2.0, 3.0, 4.0, 5.0],
    );
}

/// #26 for CUBICSPLINE: dedup keeps whole tangent triplets aligned with
/// their (retimed) keys — a per-key stride of 1 would shred them.
#[test]
fn slice_dedupes_cubic_keeps_triplets_aligned() {
    // Two keys inside the start epsilon (0.24, 0.25); values are
    // triplets [in, value, out] with the value carrying the key index.
    let times: Vec<f32> = vec![0.24, 0.25, 0.40, 0.60, 0.75];
    let values: Vec<Vec3> = (0..times.len())
        .flat_map(|i| {
            [
                Vec3::new(i as f32, -1.0, 0.0), // in-tangent
                Vec3::new(i as f32, 0.0, 0.0),  // value
                Vec3::new(i as f32, 1.0, 0.0),  // out-tangent
            ]
        })
        .collect();
    let mut clip = Clip {
        name: "cubic".into(),
        duration_s: 1.0,
        tracks: vec![Track {
            bone: 0,
            property: Property::Translation,
            interpolation: Interpolation::CubicSpline,
            times,
            values: TrackValues::Vec3s(values),
        }],
    };

    slice(&mut clip, 0.25, 0.75, 30.0);
    let t = &clip.tracks[0];
    let TrackValues::Vec3s(v) = &t.values else {
        unreachable!()
    };
    assert_eq!(t.key_count(), 4, "0.24 dropped as a start duplicate");
    assert_eq!(v.len(), 3 * t.key_count(), "triplets intact");
    // Surviving original key indices are 1,2,3,4; their triplets must
    // land verbatim (in/value/out), proving cubic per_key=3 alignment.
    for (out_key, orig_i) in [1usize, 2, 3, 4].into_iter().enumerate() {
        assert_eq!(v[out_key * 3], Vec3::new(orig_i as f32, -1.0, 0.0));
        assert_eq!(v[out_key * 3 + 1], Vec3::new(orig_i as f32, 0.0, 0.0));
        assert_eq!(v[out_key * 3 + 2], Vec3::new(orig_i as f32, 1.0, 0.0));
    }
}

/// #26: the end clamp is load-bearing on its own — a single key just
/// past `end` (no key exactly at `end`, so the dedup never fires) must
/// still be pulled back into the window.
#[test]
fn slice_clamps_lone_past_end_key() {
    let times: Vec<f32> = vec![0.30, 0.50, 0.7575];
    let values: Vec<Vec3> = (0..times.len())
        .map(|i| Vec3::new(i as f32, 0.0, 0.0))
        .collect();
    let mut clip = Clip {
        name: "past-end".into(),
        duration_s: 1.0,
        tracks: vec![Track {
            bone: 0,
            property: Property::Translation,
            interpolation: Interpolation::Linear,
            times,
            values: TrackValues::Vec3s(values),
        }],
    };

    slice(&mut clip, 0.25, 0.75, 30.0);
    let t = &clip.tracks[0];
    assert!(
        t.end_time() <= 0.5 + 1e-6,
        "past-end key {} not clamped into the window",
        t.end_time()
    );
}

fn cubic_ramp_track(bone: BoneId) -> Track {
    // 3 keys, distinct values, zero tangents → non-constant CUBICSPLINE.
    let flat = |v: Vec3| [Vec3::ZERO, v, Vec3::ZERO];
    let values: Vec<Vec3> = [Vec3::ONE, Vec3::splat(1.5), Vec3::splat(2.0)]
        .into_iter()
        .flat_map(flat)
        .collect();
    Track {
        bone,
        property: Property::Scale,
        interpolation: Interpolation::CubicSpline,
        times: vec![0.0, 0.5, 1.0],
        values: TrackValues::Vec3s(values),
    }
}

/// #27: a non-constant CUBICSPLINE track cannot be rotated coherently;
/// align must refuse (naming it) rather than shift the linear tracks
/// and leave the cubic one behind.
#[test]
fn gait_anchor_refuses_mixed_interpolation_clips() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    clip.tracks.push(cubic_ramp_track(0));
    let original = clip.clone();

    let err = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();
    assert!(err.contains("cannot gait-anchor"), "got: {err}");
    assert!(
        err.contains("track 2"),
        "error should name the track: {err}"
    );
    // Refusal is total: the clip is left untouched, not partially rotated.
    assert_eq!(clip.tracks.len(), original.tracks.len());
    for (a, b) in clip.tracks.iter().zip(&original.tracks) {
        assert_eq!(a.key_vec3(0), b.key_vec3(0));
    }
}

/// A sparse nonconstant track cannot be resampled losslessly by a whole-frame
/// phase shift and must refuse before any sibling track changes.
#[test]
fn gait_anchor_refuses_short_non_constant_tracks() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    let dur = clip.duration_s as f32;
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Scale,
        interpolation: Interpolation::Linear,
        times: vec![0.0, dur],
        values: TrackValues::Vec3s(vec![Vec3::ONE, Vec3::splat(2.0)]),
    });
    let before = format!("{clip:?}");
    let error = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();
    assert!(error.contains("track 2"), "got: {error}");
    assert!(
        error.contains("2 keys instead of exactly 32"),
        "got: {error}"
    );
    assert_eq!(format!("{clip:?}"), before);
}

/// #27: a *constant* CUBICSPLINE track is rotation-invariant, so
/// alignment must skip it (not refuse the whole clip) and leave it
/// byte-identical.
#[test]
fn gait_anchor_skips_constant_cubic_tracks() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    // Constant cubic: same value at every key, zero tangents.
    let held = Vec3::new(0.0, 2.0, 0.0);
    let values: Vec<Vec3> = (0..3)
        .flat_map(|_| [Vec3::ZERO, held, Vec3::ZERO])
        .collect();
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Translation,
        interpolation: Interpolation::CubicSpline,
        times: vec![0.0, 0.5, 1.0],
        values: TrackValues::Vec3s(values),
    });
    let constant_before = clip.tracks.last().unwrap().clone();

    align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .expect("aligns, does not refuse");
    let constant_after = clip.tracks.last().unwrap();
    assert_eq!(
        vec3_values(&constant_before),
        vec3_values(constant_after),
        "a constant cubic track must be left untouched"
    );
}

#[test]
fn gait_anchor_constant_track_past_duration_cannot_change_the_rotation_period() {
    let (skel, mut control) = open_walk();
    let roles = roles(&skel);
    let mut with_constant = control.clone();
    let held = Vec3::new(0.0, 2.0, 0.0);
    with_constant.tracks.push(Track {
        bone: 0,
        property: Property::Translation,
        interpolation: Interpolation::CubicSpline,
        times: vec![0.0, 1.0, 2.0],
        values: TrackValues::Vec3s(
            (0..3)
                .flat_map(|_| [Vec3::ZERO, held, Vec3::ZERO])
                .collect(),
        ),
    });
    let constant_before = with_constant.tracks[2].clone();

    let control_outcome = align_gait_anchor(
        &skel,
        &mut control,
        &roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .expect("control aligns");
    let constant_outcome = align_gait_anchor(
        &skel,
        &mut with_constant,
        &roles,
        FPS,
        GaitTrajectoryPolicy::InPlace,
    )
    .expect("an exempt constant track cannot alter the declared period");

    assert_eq!(constant_outcome.frame_offset, control_outcome.frame_offset);
    for track in 0..2 {
        assert_eq!(
            vec3_values(&with_constant.tracks[track]),
            vec3_values(&control.tracks[track]),
            "constant track endpoint must not affect nonconstant track {track}"
        );
    }
    assert_eq!(
        vec3_values(&with_constant.tracks[2]),
        vec3_values(&constant_before),
        "the exempt constant track itself remains untouched"
    );
}

/// #27: a CUBICSPLINE track whose keyed values are equal but whose
/// tangents are non-zero is an *animated* Hermite curve — the sampler
/// interpolates through the tangents. It must be refused (naming it),
/// not mistaken for a constant hold and silently left behind while the
/// rest of the rig rotates.
#[test]
fn gait_anchor_refuses_cubic_with_nonzero_tangents() {
    let (skel, mut clip) = open_walk();
    let roles = roles(&skel);
    let held = Vec3::new(0.0, 2.0, 0.0);
    let tangent = Vec3::new(1.0, 0.0, 0.0); // non-zero → curved segment
    let values: Vec<Vec3> = (0..3).flat_map(|_| [tangent, held, tangent]).collect();
    clip.tracks.push(Track {
        bone: 0,
        property: Property::Translation,
        interpolation: Interpolation::CubicSpline,
        times: vec![0.0, 0.5, 1.0],
        values: TrackValues::Vec3s(values),
    });
    let before = clip.clone();

    let err = align_gait_anchor(&skel, &mut clip, &roles, FPS, GaitTrajectoryPolicy::InPlace)
        .unwrap_err();
    assert!(err.contains("cannot gait-anchor"), "got: {err}");
    assert!(err.contains("pelvis"), "error should name the bone: {err}");
    assert!(
        err.contains("track 2"),
        "error should name the track: {err}"
    );
    // Refusal is total — nothing rotated.
    for (a, b) in clip.tracks.iter().zip(&before.tracks) {
        assert_eq!(vec3_values(a), vec3_values(b));
    }
}