animsmith-gltf 0.6.0

glTF/GLB ingestion into the animsmith core model
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
//! Artifact-level proof: what the in-memory candidate proof cannot see.
//!
//! [`animsmith_core::scale::prove_scale`] runs on a normalized
//! [`animsmith_core::Document`], so it can only prove claims about domains
//! that model represents. This layer proves the rest, directly against the
//! emitted container bytes:
//!
//! 1. every raw source payload the normalized document does not model
//!    (materials, images, textures, samplers, `TANGENT`/`COLOR_n`, secondary
//!    influences, extension payloads, names, `asset`);
//! 2. byte preservation of every buffer byte outside the converted accessor
//!    ranges;
//! 3. array identities — every array length and every index-valued field,
//!    plus honest reporting: the accessor indices and JSON pointers the
//!    artifact says it rewrote are exactly the ones the validated binding
//!    inventory and proof-owned disposition checks derive;
//! 4. determinism — rewriting the same source twice yields identical bytes;
//! 5. container integrity — GLB header and chunk framing, 4-byte padding, and
//!    declared buffer lengths;
//! 6. `min`/`max` consistency — the rewritten bounds still bound the
//!    rewritten data;
//! 7. single-narrowing agreement — every converted `f32` is bit-identical to
//!    the one-step narrowing of `before * q`.
//!
//! The in-memory layer is kept, not replaced: `SkinMatrix` (`W * B`),
//! `Trajectory`, `CubicInterior` and `Bounds` residuals live there, and
//! re-deriving them from raw bytes would be duplicate math with a second
//! chance to be wrong.
//!
//! Expected locations come from [`super::plan::GltfScalePlan`]'s validated,
//! numeric-free raw binding inventory. This module independently interprets
//! the compiled dispositions and derives all expected numeric values; it
//! never asks the writer for a rule or multiplier.

use super::bytes::{self, AccessorSpan};
use super::plan::{GltfScalePlan, RawAccessorTarget, plan_mismatch};
use super::{
    GltfRawJsonDifference, GltfRawJsonDifferenceKind, GltfRawJsonDifferenceSummary,
    GltfScaleArtifact, GltfScaleRewriteError,
};
use crate::capability::{GltfContainerKind, GltfScaleSource, raw_json_bytes};
use crate::{LoadError, load_bytes, resolve_buffers};
use animsmith_core::Property;
use animsmith_core::scale::{
    ScaleCandidate, ScaleFieldDisposition, ScaleOperation, ScalePlan, ScaleProof, ScaleRewriteRule,
    ScaleSourceRestField, ScaleTolerancePolicy, prove_scale,
};
use serde_json::{Map, Value};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

const GLB_JSON_CHUNK: u32 = 0x4e4f_534a;
const GLB_BIN_CHUNK: u32 = 0x004e_4942;
const MAX_RAW_JSON_DIFFERENCES: usize = 16;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProofAccessorRule {
    AllComponents,
    Mat4TranslationColumn,
}

impl ProofAccessorRule {
    fn required_accessor_type(self) -> Option<&'static str> {
        match self {
            Self::AllComponents => None,
            Self::Mat4TranslationColumn => Some("MAT4"),
        }
    }
}

fn proof_scales_component(rule: ProofAccessorRule, component: usize) -> bool {
    match rule {
        ProofAccessorRule::AllComponents => true,
        ProofAccessorRule::Mat4TranslationColumn => matches!(component, 12..=14),
    }
}

/// Observed artifact-level evidence from [`prove_rewritten_artifact`] or
/// [`super::prove_rewritten_rest_bind`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct GltfScaleArtifactProof {
    /// The in-memory candidate proof, run on the reloaded artifact.
    pub core: ScaleProof,
    /// Maximum `abs(after - before * m)` across every rewritten raw element,
    /// in JSON and in buffer payloads, where `m` is the multiplier that
    /// element's domain analytically requires: the declared `q` for a
    /// whole-document conversion, and `s_parent`, `s_parent / s_i` or `s_i`
    /// per DESIGN.md Appendix D §D.2 for a rest/bind reparameterization.
    pub length_factor_residual: f64,
    /// Maximum `abs(after - before)` across every element that lives *inside*
    /// a rewritten range and must nevertheless come through unchanged — a
    /// whole-document `MAT4` linear part, a `matrix` node's homogeneous row,
    /// an unaffected joint's inverse-bind slot, and the untouched entries of
    /// a rewritten accessor's `min`/`max`. Everything outside a rewritten
    /// range is proved byte-identical instead.
    pub dimensionless_residual: f64,
    /// Number of maximal buffer byte ranges outside the rewritten accessor
    /// ranges that were verified byte-identical to the source.
    pub preserved_byte_ranges: usize,
    /// Number of unique accessors rewritten.
    pub rewritten_accessor_count: usize,
}

/// Independently re-derive and check every artifact-level claim.
///
/// # Errors
///
/// Returns [`GltfScaleRewriteError::ArtifactProofFailed`] for the first
/// failed claim, [`GltfScaleRewriteError::Plan`] when the reloaded candidate
/// fails the shared core proof, and [`GltfScaleRewriteError::Load`] when the
/// artifact cannot be re-read.
pub fn prove_rewritten_artifact(
    source: &GltfScaleSource,
    artifact: &GltfScaleArtifact,
    plan: &ScalePlan,
) -> Result<GltfScaleArtifactProof, GltfScaleRewriteError> {
    let tolerance = plan.tolerance_policy();
    let ScaleOperation::WholeDocumentLinearUnits { factor } = plan.operation() else {
        return Err(failed(
            "plan declares a whole-document unit conversion",
            1.0,
            0.0,
        ));
    };
    if factor != artifact.declared_factor() {
        return Err(failed(
            "plan factor equals the artifact's declared factor",
            (factor - artifact.declared_factor()).abs(),
            0.0,
        ));
    }

    let reloaded = load_bytes(Path::new("scale-artifact"), artifact.bytes())?;
    let core = prove_scale(
        source.document(),
        &ScaleCandidate::from_document(reloaded),
        plan,
    )
    .map_err(GltfScaleRewriteError::Plan)?;

    let (container, json_bytes) = raw_json_bytes(artifact.bytes())?;
    if container != artifact.container() {
        return Err(failed("artifact container kind is unchanged", 1.0, 0.0));
    }
    let artifact_json: Value = serde_json::from_slice(json_bytes)
        .map_err(|error| LoadError::Malformed(format!("artifact JSON is invalid: {error}")))?;
    let source_root = object(source.raw_json())?;
    let artifact_root = object(&artifact_json)?;
    let artifact_gltf = gltf::Gltf::from_slice(artifact.bytes()).map_err(LoadError::Gltf)?;
    let artifact_buffers = resolve_buffers(&artifact_gltf, None)?;

    check_container_integrity(artifact, artifact_root, &artifact_buffers)?;
    check_array_identities(source_root, artifact_root)?;
    let gltf_plan = GltfScalePlan::new(source, plan)?;

    let mut proof = GltfScaleArtifactProof {
        core,
        length_factor_residual: 0.0,
        dimensionless_residual: 0.0,
        preserved_byte_ranges: 0,
        rewritten_accessor_count: 0,
    };

    let mut converted_pointers = BTreeSet::new();
    check_node_transforms(
        source_root,
        artifact_root,
        &gltf_plan,
        factor,
        &tolerance,
        &mut converted_pointers,
        &mut proof,
    )?;

    let expected = scale_bearing_accessors(&gltf_plan, factor != 1.0)?;
    if artifact.rewritten_accessors() != expected.keys().copied().collect::<Vec<_>>() {
        return Err(failed(
            "artifact reports exactly the accessors this proof independently derives",
            artifact.rewritten_accessors().len() as f64,
            expected.len() as f64,
        ));
    }
    proof.rewritten_accessor_count = expected.len();

    let mut spans = Vec::with_capacity(expected.len());
    for (&accessor_index, &rule) in &expected {
        let span = bytes::accessor_span_typed(
            source_root,
            source.resolved_buffers(),
            accessor_index,
            rule.required_accessor_type(),
        )?;
        let artifact_span = bytes::accessor_span_typed(
            artifact_root,
            &artifact_buffers,
            accessor_index,
            rule.required_accessor_type(),
        )?;
        if span != artifact_span {
            return Err(failed(
                "converted accessors keep their source byte layout",
                artifact_span.start as f64,
                span.start as f64,
            ));
        }
        spans.push((span, rule));
    }

    check_converted_payloads(
        source.resolved_buffers(),
        &artifact_buffers,
        &spans,
        factor,
        &tolerance,
        &mut proof,
    )?;
    check_accessor_bounds(
        source_root,
        artifact_root,
        &artifact_buffers,
        &spans,
        factor,
        &tolerance,
        &mut converted_pointers,
        &mut proof,
    )?;

    // The artifact's own report of what it changed is evidence, so it is
    // checked rather than trusted: `converted_pointers` was accumulated by
    // this module's independent scan, and it is exactly the set the rewriter
    // is allowed to have touched.
    if artifact.rewritten_json_pointers() != converted_pointers.iter().cloned().collect::<Vec<_>>()
    {
        return Err(failed(
            "artifact reports exactly the JSON pointers this proof independently derives",
            artifact.rewritten_json_pointers().len() as f64,
            converted_pointers.len() as f64,
        ));
    }

    let mut allowed = converted_pointers;
    for &buffer_index in artifact.reencoded_buffers() {
        allowed.insert(format!("/buffers/{buffer_index}/uri"));
    }
    check_preserved_json(
        source.raw_json(),
        &artifact_json,
        &allowed,
        "every raw JSON location outside the converted set is preserved exactly",
    )?;

    let converted_spans: Vec<AccessorSpan> = spans.iter().map(|(span, _)| *span).collect();
    proof.preserved_byte_ranges = check_preserved_bytes(
        source.resolved_buffers(),
        &artifact_buffers,
        &converted_spans,
    )?;

    let repeat = super::rewrite_scale_plan(source, plan)?;
    if repeat.bytes() != artifact.bytes() {
        return Err(failed(
            "rewriting the same source twice yields identical bytes",
            repeat.bytes().len() as f64,
            artifact.bytes().len() as f64,
        ));
    }
    Ok(proof)
}

// --- Claims ---------------------------------------------------------------

/// GLB header/chunk framing and declared buffer lengths.
pub(super) fn check_container_integrity(
    artifact: &GltfScaleArtifact,
    artifact_root: &Map<String, Value>,
    artifact_buffers: &[Vec<u8>],
) -> Result<(), GltfScaleRewriteError> {
    if artifact.container() == GltfContainerKind::Glb {
        let bytes = artifact.bytes();
        let word = |offset: usize| -> Result<u32, GltfScaleRewriteError> {
            bytes
                .get(offset..offset + 4)
                .and_then(|slice| slice.try_into().ok())
                .map(u32::from_le_bytes)
                .ok_or_else(|| failed("GLB container is long enough for its own framing", 0.0, 1.0))
        };
        if &bytes[0..4.min(bytes.len())] != b"glTF" || word(4)? != 2 {
            return Err(failed("GLB declares magic 'glTF' and version 2", 0.0, 1.0));
        }
        if word(8)? as usize != bytes.len() {
            return Err(failed(
                "GLB total length equals the emitted byte count",
                f64::from(word(8)?),
                bytes.len() as f64,
            ));
        }
        let json_len = word(12)? as usize;
        if word(16)? != GLB_JSON_CHUNK || !json_len.is_multiple_of(4) {
            return Err(failed(
                "GLB JSON chunk is typed and 4-byte padded",
                0.0,
                1.0,
            ));
        }
        let mut offset = 20 + json_len;
        let mut framed = offset;
        if offset < bytes.len() {
            let bin_len = word(offset)? as usize;
            if word(offset + 4)? != GLB_BIN_CHUNK || !bin_len.is_multiple_of(4) {
                return Err(failed("GLB BIN chunk is typed and 4-byte padded", 0.0, 1.0));
            }
            offset += 8;
            framed = offset + bin_len;
        }
        if framed != bytes.len() {
            return Err(failed(
                "GLB chunk lengths account for every emitted byte",
                framed as f64,
                bytes.len() as f64,
            ));
        }
    }
    let declared = artifact_root
        .get("buffers")
        .and_then(Value::as_array)
        .map(Vec::as_slice)
        .unwrap_or_default();
    for (buffer_index, buffer) in declared.iter().enumerate() {
        let byte_length = buffer
            .get("byteLength")
            .and_then(Value::as_u64)
            .unwrap_or_default() as usize;
        let resolved = artifact_buffers.get(buffer_index).map_or(0, Vec::len);
        if resolved < byte_length {
            return Err(failed(
                "every declared buffer byteLength is backed by resolved bytes",
                resolved as f64,
                byte_length as f64,
            ));
        }
    }
    Ok(())
}

/// Every top-level array keeps its length, so every index-valued field in the
/// document still names the same element.
pub(super) fn check_array_identities(
    source_root: &Map<String, Value>,
    artifact_root: &Map<String, Value>,
) -> Result<(), GltfScaleRewriteError> {
    const ARRAYS: &[&str] = &[
        "accessors",
        "animations",
        "bufferViews",
        "buffers",
        "cameras",
        "images",
        "materials",
        "meshes",
        "nodes",
        "samplers",
        "scenes",
        "skins",
        "textures",
    ];
    for key in ARRAYS {
        let length =
            |root: &Map<String, Value>| root.get(*key).and_then(Value::as_array).map(Vec::len);
        if length(source_root) != length(artifact_root) {
            return Err(failed(
                "every top-level array keeps its source length",
                length(artifact_root).unwrap_or_default() as f64,
                length(source_root).unwrap_or_default() as f64,
            ));
        }
    }
    Ok(())
}

/// Node `translation` scales; a node `matrix` scales exactly its translation
/// column and preserves its 3x3 and homogeneous component.
fn check_node_transforms(
    source_root: &Map<String, Value>,
    artifact_root: &Map<String, Value>,
    plan: &GltfScalePlan,
    factor: f64,
    tolerance: &ScaleTolerancePolicy,
    converted_pointers: &mut BTreeSet<String>,
    proof: &mut GltfScaleArtifactProof,
) -> Result<(), GltfScaleRewriteError> {
    let source_nodes = source_root
        .get("nodes")
        .and_then(Value::as_array)
        .map(Vec::as_slice)
        .unwrap_or_default();
    let artifact_nodes = artifact_root
        .get("nodes")
        .and_then(Value::as_array)
        .map(Vec::as_slice)
        .unwrap_or_default();
    for binding in plan.node_bindings() {
        let node_index = binding.source_node_index;
        let before = source_nodes
            .get(node_index)
            .ok_or_else(|| plan_mismatch("source_node_payload_missing"))?;
        let after = artifact_nodes
            .get(node_index)
            .ok_or_else(|| plan_mismatch("artifact_node_payload_missing"))?;
        for (member, field, length, scales) in [
            (
                "translation",
                ScaleSourceRestField::Translation,
                3usize,
                &[0usize, 1, 2] as &[usize],
            ),
            (
                "matrix",
                ScaleSourceRestField::MatrixTranslation,
                16,
                &[12, 13, 14],
            ),
        ] {
            if (member == "translation" && !binding.translation_declared)
                || (member == "matrix" && !binding.matrix_declared)
            {
                continue;
            }
            let Some(source_values) = before.get(member).and_then(Value::as_array) else {
                continue;
            };
            let rewrites = validate_proof_whole_document_disposition(
                plan.source_rest(node_index, field)?,
                factor != 1.0,
            )?;
            if !rewrites {
                continue;
            }
            let pointer = format!("/nodes/{node_index}/{member}");
            let artifact_values = after
                .get(member)
                .and_then(Value::as_array)
                .filter(|values| values.len() == length && source_values.len() == length)
                .ok_or_else(|| {
                    failed(
                        "a converted node transform keeps its authored arity",
                        0.0,
                        length as f64,
                    )
                })?;
            for component in 0..length {
                let before = numeric(&source_values[component], &pointer)?;
                let after = numeric(&artifact_values[component], &pointer)?;
                if scales.contains(&component) {
                    track_length(before, after, factor, tolerance, proof)?;
                } else {
                    track_dimensionless(before, after, proof)?;
                }
            }
            converted_pointers.insert(pointer);
        }
    }
    Ok(())
}

/// Every converted `f32` in a buffer payload is the single-step narrowing of
/// `before * q`, and every component the rule leaves alone is bit-identical.
fn check_converted_payloads(
    source_buffers: &[Vec<u8>],
    artifact_buffers: &[Vec<u8>],
    spans: &[(AccessorSpan, ProofAccessorRule)],
    factor: f64,
    tolerance: &ScaleTolerancePolicy,
    proof: &mut GltfScaleArtifactProof,
) -> Result<(), GltfScaleRewriteError> {
    for &(span, rule) in spans {
        let before = bytes::read_span(source_buffers, span);
        let after = bytes::read_span(artifact_buffers, span);
        if before.len() != after.len() {
            return Err(failed(
                "a converted accessor keeps its element count",
                after.len() as f64,
                before.len() as f64,
            ));
        }
        for (index, (&before, &after)) in before.iter().zip(&after).enumerate() {
            if proof_scales_component(rule, index % span.components) {
                let expected = f64::from(before) * factor;
                if after.to_bits() != (expected as f32).to_bits() {
                    return Err(failed(
                        "every converted element is the single narrowing of before * q",
                        f64::from(after),
                        expected,
                    ));
                }
                track_length(
                    f64::from(before),
                    f64::from(after),
                    factor,
                    tolerance,
                    proof,
                )?;
            } else if after.to_bits() != before.to_bits() {
                return Err(failed(
                    "a converted accessor's dimensionless components are bit-identical",
                    f64::from(after),
                    f64::from(before),
                ));
            }
        }
    }
    Ok(())
}

/// A converted accessor's `min`/`max` scale by `q` and still bound the
/// rewritten data.
#[allow(clippy::too_many_arguments)]
fn check_accessor_bounds(
    source_root: &Map<String, Value>,
    artifact_root: &Map<String, Value>,
    artifact_buffers: &[Vec<u8>],
    spans: &[(AccessorSpan, ProofAccessorRule)],
    factor: f64,
    tolerance: &ScaleTolerancePolicy,
    converted_pointers: &mut BTreeSet<String>,
    proof: &mut GltfScaleArtifactProof,
) -> Result<(), GltfScaleRewriteError> {
    for &(span, rule) in spans {
        let payload = bytes::read_span(artifact_buffers, span);
        for (member, is_min) in [("min", true), ("max", false)] {
            let pointer = format!("/accessors/{}/{member}", span.accessor_index);
            let Some(source_bounds) = source_root
                .get("accessors")
                .and_then(Value::as_array)
                .and_then(|accessors| accessors.get(span.accessor_index))
                .and_then(|accessor| accessor.get(member))
                .and_then(Value::as_array)
            else {
                continue;
            };
            let artifact_bounds = artifact_root
                .get("accessors")
                .and_then(Value::as_array)
                .and_then(|accessors| accessors.get(span.accessor_index))
                .and_then(|accessor| accessor.get(member))
                .and_then(Value::as_array)
                .filter(|bounds| bounds.len() == source_bounds.len())
                .ok_or_else(|| {
                    failed(
                        "a converted accessor keeps its authored bound arity",
                        0.0,
                        source_bounds.len() as f64,
                    )
                })?;
            for component in 0..source_bounds.len() {
                let before = numeric(&source_bounds[component], &pointer)?;
                let after = numeric(&artifact_bounds[component], &pointer)?;
                if !proof_scales_component(rule, component) {
                    track_dimensionless(before, after, proof)?;
                    continue;
                }
                // A converted bound tracks `before * q` within the shared
                // tolerance. It is deliberately not required to be exactly
                // `before * q` or wider: narrowing `before * q` to `f32`
                // rounds in either direction, and the binding obligation is
                // the next one — that the emitted bound bounds the emitted
                // bytes.
                track_length(before, after, factor, tolerance, proof)?;
                let observed = payload
                    .iter()
                    .skip(component)
                    .step_by(span.components)
                    .copied()
                    .fold(
                        if is_min {
                            f32::INFINITY
                        } else {
                            f32::NEG_INFINITY
                        },
                        |accumulator, value| {
                            if is_min {
                                accumulator.min(value)
                            } else {
                                accumulator.max(value)
                            }
                        },
                    );
                // Compared in `f32`, the model glTF actually declares for
                // `min`/`max`: a JSON number is `f64` in transit, but its
                // shortest decimal spelling need not equal the full `f64`
                // widening of the represented `f32`. Comparing in `f64`
                // would therefore test lexical transit precision rather than
                // the model value that matters.
                let declared = after as f32;
                let bounds_data = if is_min {
                    declared <= observed
                } else {
                    declared >= observed
                };
                if !bounds_data {
                    return Err(failed(
                        "a converted bound still bounds the converted payload",
                        f64::from(declared),
                        f64::from(observed),
                    ));
                }
            }
            converted_pointers.insert(pointer);
        }
    }
    Ok(())
}

/// Buffer bytes outside the converted ranges are identical, counted as
/// maximal preserved ranges.
pub(super) fn check_preserved_bytes(
    source_buffers: &[Vec<u8>],
    artifact_buffers: &[Vec<u8>],
    spans: &[AccessorSpan],
) -> Result<usize, GltfScaleRewriteError> {
    if source_buffers.len() != artifact_buffers.len() {
        return Err(failed(
            "the artifact declares the same number of resolved buffers",
            artifact_buffers.len() as f64,
            source_buffers.len() as f64,
        ));
    }
    let mut preserved = 0usize;
    for (buffer_index, (before, after)) in source_buffers.iter().zip(artifact_buffers).enumerate() {
        if before.len() != after.len() {
            return Err(failed(
                "every resolved buffer keeps its source byte length",
                after.len() as f64,
                before.len() as f64,
            ));
        }
        let mut converted: Vec<(usize, usize)> = spans
            .iter()
            .filter(|span| span.buffer == buffer_index)
            .map(|span| (span.start, span.end))
            .collect();
        converted.sort_unstable();
        let mut cursor = 0usize;
        for (start, end) in converted.into_iter().chain([(before.len(), before.len())]) {
            if cursor < start {
                if before[cursor..start] != after[cursor..start] {
                    return Err(failed(
                        "buffer bytes outside the converted ranges are preserved",
                        cursor as f64,
                        start as f64,
                    ));
                }
                preserved += 1;
            }
            // `max` rather than a plain assignment. Unreachable through
            // `prove_rewritten_artifact` — `converted` is sorted and #280
            // rejects a source whose scale-bearing accessor ranges overlap,
            // so no later span can end before the cursor — but a nested span
            // must never rewind the cursor and re-compare bytes that were
            // already accounted for. Pinned by
            // `a_nested_converted_range_does_not_rewind_the_preserved_byte_cursor`.
            cursor = cursor.max(end);
        }
    }
    Ok(preserved)
}

#[derive(Debug, Default)]
struct RawJsonDifferenceCollector {
    differences: Vec<GltfRawJsonDifference>,
    total: usize,
}

impl RawJsonDifferenceCollector {
    fn record(&mut self, pointer: String, kind: GltfRawJsonDifferenceKind) {
        self.total += 1;
        if self.differences.len() < MAX_RAW_JSON_DIFFERENCES {
            self.differences
                .push(GltfRawJsonDifference { pointer, kind });
        }
    }

    fn finish(self) -> GltfRawJsonDifferenceSummary {
        let omitted = self.total - self.differences.len();
        GltfRawJsonDifferenceSummary {
            differences: self.differences,
            omitted,
        }
    }
}

/// Check that every raw JSON location outside `allowed` is preserved.
pub(super) fn check_preserved_json(
    before: &Value,
    after: &Value,
    allowed: &BTreeSet<String>,
    claim: &'static str,
) -> Result<(), GltfScaleRewriteError> {
    let mut collector = RawJsonDifferenceCollector::default();
    collect_json_differences(before, after, "", allowed, &mut collector);
    if collector.total == 0 {
        return Ok(());
    }
    let total = collector.total;
    let summary = collector.finish();
    Err(GltfScaleRewriteError::ArtifactProofFailed {
        claim,
        observed: total as f64,
        tolerance: 0.0,
        raw_json_differences: Some(summary),
    })
}

/// Collect every JSON location where the artifact differs from the source,
/// skipping the pointers the conversion is allowed to change.
fn collect_json_differences(
    before: &Value,
    after: &Value,
    pointer: &str,
    allowed: &BTreeSet<String>,
    out: &mut RawJsonDifferenceCollector,
) {
    if allowed.contains(pointer) {
        return;
    }
    match (before, after) {
        (Value::Object(before), Value::Object(after)) => {
            let keys: BTreeSet<&String> = before.keys().chain(after.keys()).collect();
            for key in keys {
                let child = format!("{pointer}/{}", key.replace('~', "~0").replace('/', "~1"));
                match (before.get(key), after.get(key)) {
                    (Some(before), Some(after)) => {
                        collect_json_differences(before, after, &child, allowed, out);
                    }
                    // A member only one side declares is a difference unless
                    // the caller's own scan already accounted for it. The
                    // rest/bind reparameterization materializes exactly one
                    // such member — the closure root's `scale`, whose glTF
                    // default `[1, 1, 1]` is not fixed under `* 1/s` — and its
                    // caller records that pointer only after checking the
                    // materialized value against that default. Skipping the
                    // `allowed` test here would make an added member
                    // unreportable *and* unchecked; the whole-document
                    // conversion adds no member at all, so nothing there
                    // changes either way.
                    _ if allowed.contains(&child) => {}
                    (None, Some(_)) => {
                        out.record(child, GltfRawJsonDifferenceKind::ArtifactAdded);
                    }
                    (Some(_), None) => {
                        out.record(child, GltfRawJsonDifferenceKind::ArtifactRemoved);
                    }
                    (None, None) => unreachable!("a key came from at least one object"),
                }
            }
        }
        (Value::Array(before), Value::Array(after)) if before.len() == after.len() => {
            for (index, (before, after)) in before.iter().zip(after).enumerate() {
                collect_json_differences(
                    before,
                    after,
                    &format!("{pointer}/{index}"),
                    allowed,
                    out,
                );
            }
        }
        (Value::Number(before), Value::Number(after)) => {
            if !json_numbers_have_identical_value_and_zero_sign(before, after) {
                out.record(pointer.to_owned(), GltfRawJsonDifferenceKind::ValueChanged);
            }
        }
        (before, after) if before == after => {}
        _ => out.record(pointer.to_owned(), GltfRawJsonDifferenceKind::ValueChanged),
    }
}

/// JSON number equality with the authored sign bit preserved for zero.
///
/// `serde_json::Number` follows ordinary floating-point equality, under which
/// `-0.0 == 0.0`. Raw glTF preservation is stricter: a writer may not
/// canonicalize an untouched authored zero merely because its numeric value is
/// unchanged.
fn json_numbers_have_identical_value_and_zero_sign(
    before: &serde_json::Number,
    after: &serde_json::Number,
) -> bool {
    if before != after {
        return false;
    }
    match (before.as_f64(), after.as_f64()) {
        (Some(before), Some(after)) if before == 0.0 && after == 0.0 => {
            before.to_bits() == after.to_bits()
        }
        _ => true,
    }
}

// --- Independent domain scan ------------------------------------------------

/// Every accessor a whole-document conversion must convert, selected from the
/// shared structural inventory with a proof-owned disposition interpretation.
/// The map is keyed by unique accessor index because a `POSITION` shared by
/// two primitives is one conversion, not `q^2`.
fn scale_bearing_accessors(
    plan: &GltfScalePlan,
    factor_changes: bool,
) -> Result<BTreeMap<usize, ProofAccessorRule>, GltfScaleRewriteError> {
    let mut out = BTreeMap::new();
    for binding in plan.accessor_bindings() {
        let rule = match &binding.target {
            RawAccessorTarget::MeshPositions { disposition } => {
                validate_proof_whole_document_disposition(*disposition, factor_changes)?
                    .then_some(ProofAccessorRule::AllComponents)
            }
            RawAccessorTarget::MorphPositions => {
                factor_changes.then_some(ProofAccessorRule::AllComponents)
            }
            RawAccessorTarget::InstanceInverseBind { source_skin_index } => {
                let skin = plan.skin_binding(*source_skin_index)?;
                let mut rewrite = None;
                for slot in &skin.slots {
                    let slot_rewrite = validate_proof_whole_document_disposition(
                        slot.disposition
                            .ok_or_else(|| plan_mismatch("inverse_bind_disposition_missing"))?,
                        factor_changes,
                    )?;
                    match rewrite {
                        Some(previous) if previous != slot_rewrite => {
                            return Err(plan_mismatch("mixed_whole_document_accessor_disposition"));
                        }
                        Some(_) => {}
                        None => rewrite = Some(slot_rewrite),
                    }
                }
                rewrite
                    .unwrap_or(false)
                    .then_some(ProofAccessorRule::Mat4TranslationColumn)
            }
            RawAccessorTarget::Animation {
                property: Property::Translation,
                disposition,
                ..
            } => validate_proof_whole_document_disposition(*disposition, factor_changes)?
                .then_some(ProofAccessorRule::AllComponents),
            RawAccessorTarget::MeshNormals { .. } => None,
            RawAccessorTarget::PreserveExact | RawAccessorTarget::Animation { .. } => None,
        };
        if let Some(rule) = rule {
            out.insert(binding.accessor_index, rule);
        }
    }
    Ok(out)
}

/// Proof-owned interpretation of the whole-document structural rule.
///
/// Kept separate from the writer's identical match so sharing the field
/// vocabulary cannot make the proof repeat a writer selection defect.
fn validate_proof_whole_document_disposition(
    disposition: ScaleFieldDisposition,
    factor_changes: bool,
) -> Result<bool, GltfScaleRewriteError> {
    match (factor_changes, disposition) {
        (true, ScaleFieldDisposition::Rewrite(ScaleRewriteRule::WholeDocumentLength)) => Ok(true),
        (false, ScaleFieldDisposition::PreserveExact) => Ok(false),
        _ => Err(plan_mismatch("invalid_whole_document_field_disposition")),
    }
}

// --- Residual bookkeeping ---------------------------------------------------

pub(super) fn track_length(
    before: f64,
    after: f64,
    factor: f64,
    tolerance: &ScaleTolerancePolicy,
    proof: &mut GltfScaleArtifactProof,
) -> Result<(), GltfScaleRewriteError> {
    let expected = before * factor;
    let residual = (after - expected).abs();
    proof.length_factor_residual = proof.length_factor_residual.max(residual);
    let bound = tolerance.scalar_tolerance(expected, after);
    if residual > bound {
        return Err(failed(
            "every converted length differs from the source by exactly the declared factor",
            residual,
            bound,
        ));
    }
    Ok(())
}

pub(super) fn track_dimensionless(
    before: f64,
    after: f64,
    proof: &mut GltfScaleArtifactProof,
) -> Result<(), GltfScaleRewriteError> {
    let residual = (after - before).abs();
    proof.dimensionless_residual = proof.dimensionless_residual.max(residual);
    if before.to_bits() != after.to_bits() {
        return Err(failed(
            "every dimensionless value inside a converted range is invariant",
            residual,
            0.0,
        ));
    }
    Ok(())
}

pub(super) fn failed(claim: &'static str, observed: f64, tolerance: f64) -> GltfScaleRewriteError {
    GltfScaleRewriteError::ArtifactProofFailed {
        claim,
        observed,
        tolerance,
        raw_json_differences: None,
    }
}

pub(super) fn object(value: &Value) -> Result<&Map<String, Value>, GltfScaleRewriteError> {
    value
        .as_object()
        .ok_or_else(|| LoadError::Malformed("top-level glTF JSON is not an object".into()).into())
}

pub(super) fn numeric(value: &Value, location: &str) -> Result<f64, GltfScaleRewriteError> {
    value
        .as_f64()
        .ok_or_else(|| LoadError::Malformed(format!("{location} is not a number")).into())
}

#[cfg(test)]
mod tests {
    //! Per-claim negative tests.
    //!
    //! Each test corrupts exactly one thing about an otherwise valid artifact
    //! and asserts the exact claim string that must catch it. These live here
    //! rather than in `tests/scale_rewrite.rs` because
    //! [`super::super::GltfScaleArtifact`]'s fields are private, and two of
    //! the claims — the accessor and JSON-pointer cross-checks — can only be
    //! falsified by making the artifact's own report disagree with its bytes.
    //!
    //! The fixture is a `.gltf`, not a GLB, so an artifact is pure JSON and a
    //! corruption is a `serde_json` edit plus a base64 round trip. No test
    //! below asserts a value this crate produced: every expectation is a
    //! claim string, and every payload literal is exact under a factor of
    //! four.

    use super::*;
    use crate::preflight_scale_source_bytes;
    use animsmith_core::scale::{ScaleOperation, ScaleRequest, plan_scale};
    use base64::{Engine as _, engine::general_purpose::STANDARD};
    use serde_json::json;

    /// Byte offsets inside the fixture's single buffer.
    mod offsets {
        pub const POSITION: usize = 0; // 36 bytes, converted
        pub const INVERSE_BIND: usize = 36; // 64 bytes, converted
        pub const JOINTS: usize = 100; // 24 bytes, preserved
        pub const WEIGHTS: usize = 124; // 48 bytes, preserved
        pub const SPARE: usize = 172; // 4 bytes, reached by no bufferView
        pub const LENGTH: usize = 176;
    }

    const FACTOR: f64 = 4.0;

    const POSITIONS: [f32; 9] = [1.0, 2.0, -3.0, 0.5, -0.25, 4.0, 2.0, 0.0, 1.5];
    const INVERSE_BIND: [f32; 16] = [
        1.0, 0.0, 0.0, 0.0, //
        0.0, 1.0, 0.0, 0.0, //
        0.0, 0.0, 1.0, 0.0, //
        -1.0, 2.0, -0.5, 1.0,
    ];

    fn data_uri(bytes: &[u8]) -> String {
        format!(
            "data:application/octet-stream;base64,{}",
            STANDARD.encode(bytes)
        )
    }

    fn fixture_buffer() -> Vec<u8> {
        let mut buffer = vec![0u8; offsets::LENGTH];
        for (index, value) in POSITIONS.iter().enumerate() {
            let at = offsets::POSITION + index * 4;
            buffer[at..at + 4].copy_from_slice(&value.to_le_bytes());
        }
        for (index, value) in INVERSE_BIND.iter().enumerate() {
            let at = offsets::INVERSE_BIND + index * 4;
            buffer[at..at + 4].copy_from_slice(&value.to_le_bytes());
        }
        // One joint, full weight on it, for each of the three vertices.
        for vertex in 0..3 {
            let at = offsets::WEIGHTS + vertex * 16;
            buffer[at..at + 4].copy_from_slice(&1.0f32.to_le_bytes());
        }
        buffer
    }

    /// A skinned source whose buffer carries four bytes no `bufferView`
    /// reaches, so a byte can be flipped outside every converted range
    /// without disturbing anything the normalized `Document` models.
    fn fixture_json(buffer: &[u8]) -> Value {
        json!({
            "asset": { "version": "2.0" },
            "buffers": [{ "uri": data_uri(buffer), "byteLength": offsets::LENGTH }],
            "bufferViews": [
                { "buffer": 0, "byteOffset": offsets::POSITION, "byteLength": 36 },
                { "buffer": 0, "byteOffset": offsets::INVERSE_BIND, "byteLength": 64 },
                { "buffer": 0, "byteOffset": offsets::JOINTS, "byteLength": 24 },
                { "buffer": 0, "byteOffset": offsets::WEIGHTS, "byteLength": 48 }
            ],
            "accessors": [
                { "bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3",
                  "min": [0.5, -0.25, -3.0], "max": [2.0, 2.0, 4.0] },
                { "bufferView": 1, "componentType": 5126, "count": 1, "type": "MAT4" },
                { "bufferView": 2, "componentType": 5123, "count": 3, "type": "VEC4" },
                { "bufferView": 3, "componentType": 5126, "count": 3, "type": "VEC4" }
            ],
            "materials": [{ "name": "surface" }],
            "meshes": [{ "primitives": [{
                "attributes": { "POSITION": 0, "JOINTS_0": 2, "WEIGHTS_0": 3 },
                "material": 0
            }] }],
            "nodes": [{ "name": "joint" }, { "name": "holder", "mesh": 0, "skin": 0 }],
            "scenes": [{ "nodes": [0, 1] }],
            "scene": 0,
            "skins": [{ "joints": [0], "skeleton": 0, "inverseBindMatrices": 1 }]
        })
    }

    fn fixture() -> (GltfScaleSource, GltfScaleArtifact, ScalePlan) {
        let value = fixture_json(&fixture_buffer());
        fixture_from_value(&value)
    }

    fn fixture_from_value(value: &Value) -> (GltfScaleSource, GltfScaleArtifact, ScalePlan) {
        fixture_from_value_with_factor(value, FACTOR)
    }

    fn fixture_from_value_with_factor(
        value: &Value,
        factor: f64,
    ) -> (GltfScaleSource, GltfScaleArtifact, ScalePlan) {
        let bytes = serde_json::to_vec(&value).expect("fixture serializes");
        let source = preflight_scale_source_bytes(Path::new("proof-fixture.gltf"), &bytes)
            .expect("the fixture preflights cleanly");
        let plan = plan_scale(&ScaleRequest {
            operation: ScaleOperation::WholeDocumentLinearUnits { factor },
            document: source.document(),
            capability: &super::super::capability_facts(source.manifest()),
        })
        .expect("plan");
        let artifact = super::super::rewrite_linear_units(&source, factor).expect("rewrite");
        (source, artifact, plan)
    }

    /// The artifact's JSON, as a mutable tree.
    fn artifact_value(artifact: &GltfScaleArtifact) -> Value {
        serde_json::from_slice(artifact.bytes()).expect("a .gltf artifact is JSON")
    }

    fn put_artifact_value(artifact: &mut GltfScaleArtifact, value: &Value) {
        artifact.bytes = serde_json::to_vec(value).expect("corrupted fixture serializes");
    }

    fn artifact_buffer(value: &Value) -> Vec<u8> {
        let uri = value["buffers"][0]["uri"].as_str().expect("data URI");
        STANDARD
            .decode(uri.split_once("base64,").expect("base64 data URI").1)
            .expect("valid base64")
    }

    fn put_artifact_buffer(value: &mut Value, bytes: &[u8]) {
        value["buffers"][0]["uri"] = json!(data_uri(bytes));
    }

    /// Assert that proving `artifact` fails with exactly `expected`.
    fn expect_claim(
        source: &GltfScaleSource,
        artifact: &GltfScaleArtifact,
        plan: &ScalePlan,
        expected: &str,
    ) {
        match prove_rewritten_artifact(source, artifact, plan) {
            Err(GltfScaleRewriteError::ArtifactProofFailed {
                claim,
                raw_json_differences,
                ..
            }) => {
                assert_eq!(claim, expected);
                assert_eq!(
                    raw_json_differences, None,
                    "ordinary proof claims do not carry raw JSON diagnostics"
                );
            }
            other => panic!("expected the claim {expected:?} to fail, got {other:?}"),
        }
    }

    #[test]
    fn the_uncorrupted_fixture_proves_and_reports_its_evidence() {
        // Without this, every negative below could be passing for the wrong
        // reason: a fixture that never proves cannot show which claim caught
        // which corruption.
        let (source, artifact, plan) = fixture();
        let proof = prove_rewritten_artifact(&source, &artifact, &plan).expect("artifact proof");
        assert_eq!(proof.rewritten_accessor_count, 2, "POSITION and the IBM");
        assert_eq!(proof.length_factor_residual, 0.0);
        assert_eq!(proof.dimensionless_residual, 0.0);
        // 0..36 and 36..100 are converted, so 100..104 is the only preserved
        // complement range.
        assert_eq!(proof.preserved_byte_ranges, 1);
        assert_eq!(artifact.rewritten_accessors(), [0, 1]);
        assert_eq!(
            artifact.rewritten_json_pointers(),
            ["/accessors/0/max", "/accessors/0/min"]
        );
    }

    #[test]
    fn a_flipped_byte_outside_every_converted_range_fails_byte_preservation() {
        let (source, mut artifact, plan) = fixture();
        let mut value = artifact_value(&artifact);
        let mut buffer = artifact_buffer(&value);
        buffer[offsets::SPARE] ^= 0xff;
        put_artifact_buffer(&mut value, &buffer);
        put_artifact_value(&mut artifact, &value);
        expect_claim(
            &source,
            &artifact,
            &plan,
            "buffer bytes outside the converted ranges are preserved",
        );
    }

    #[test]
    fn a_dimensionless_component_inside_a_converted_range_must_be_bit_identical() {
        // The inverse bind's 3x3 entry 1 is `+0.0`; setting its sign bit
        // makes it `-0.0`, which is numerically identical and so invisible to
        // every residual — only the bit comparison catches it.
        let (source, mut artifact, plan) = fixture();
        let mut value = artifact_value(&artifact);
        let mut buffer = artifact_buffer(&value);
        const SIGN_BYTE: usize = offsets::INVERSE_BIND + 4 + 3;
        buffer[SIGN_BYTE] |= 0x80;
        put_artifact_buffer(&mut value, &buffer);
        put_artifact_value(&mut artifact, &value);
        expect_claim(
            &source,
            &artifact,
            &plan,
            "a converted accessor's dimensionless components are bit-identical",
        );
    }

    #[test]
    fn a_dimensionless_node_matrix_component_must_be_exact_in_parsed_f64() {
        let mut value = fixture_json(&fixture_buffer());
        value["nodes"][0] = json!({
            "name": "joint",
            "matrix": [
                1.0, 0.0, 0.0, 0.0,
                0.0, 1.0, 0.0, 0.0,
                0.0, 0.0, 1.0, 0.0,
                0.0, 0.0, 0.0, 1.0
            ]
        });
        let (source, mut artifact, plan) = fixture_from_value(&value);
        let mut doctored = artifact_value(&artifact);
        let adjacent = f64::from_bits(1.0f64.to_bits() + 1);
        doctored["nodes"][0]["matrix"][0] = json!(adjacent);
        put_artifact_value(&mut artifact, &doctored);
        let error = prove_rewritten_artifact(&source, &artifact, &plan)
            .expect_err("an adjacent identity-multiplier matrix value must be refused");
        match error {
            GltfScaleRewriteError::ArtifactProofFailed {
                claim, observed, ..
            } => {
                assert_eq!(
                    claim,
                    "every dimensionless value inside a converted range is invariant"
                );
                assert_eq!(observed, adjacent - 1.0, "one adjacent matrix f64");
            }
            other => panic!("expected a dimensionless matrix residual, got {other:?}"),
        }
    }

    #[test]
    fn a_factor_one_matrix_translation_is_preserved_by_the_public_artifact_proof() {
        let mut value = fixture_json(&fixture_buffer());
        let authored = f64::from_bits(1.0f64.to_bits() + 1);
        value["nodes"][1]["matrix"] = json!([
            1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, authored, 0.0, 0.0, 1.0
        ]);
        let (source, mut artifact, plan) = fixture_from_value_with_factor(&value, 1.0);
        assert!(artifact.rewritten_accessors().is_empty());
        assert!(artifact.rewritten_json_pointers().is_empty());
        assert_eq!(
            artifact_value(&artifact)["nodes"][1]["matrix"][12]
                .as_f64()
                .expect("numeric matrix translation")
                .to_bits(),
            authored.to_bits()
        );
        let proof =
            prove_rewritten_artifact(&source, &artifact, &plan).expect("factor-one artifact proof");
        assert_eq!(proof.rewritten_accessor_count, 0);

        let mut doctored = artifact_value(&artifact);
        let adjacent = f64::from_bits(authored.to_bits() + 1);
        doctored["nodes"][1]["matrix"][12] = json!(adjacent);
        put_artifact_value(&mut artifact, &doctored);
        let error = prove_rewritten_artifact(&source, &artifact, &plan)
            .expect_err("a changed factor-one matrix translation must be refused");
        match error {
            GltfScaleRewriteError::ArtifactProofFailed {
                claim,
                observed,
                raw_json_differences: Some(summary),
                ..
            } => {
                assert_eq!(
                    claim,
                    "every raw JSON location outside the converted set is preserved exactly"
                );
                assert_eq!(observed, 1.0);
                assert_eq!(summary.differences.len(), 1);
                assert_eq!(summary.differences[0].pointer, "/nodes/1/matrix/12");
                assert_eq!(
                    summary.differences[0].kind,
                    GltfRawJsonDifferenceKind::ValueChanged
                );
            }
            other => panic!("expected a located raw JSON difference, got {other:?}"),
        }
    }

    #[test]
    fn an_under_reported_converted_accessor_fails_the_accessor_cross_check() {
        let (source, mut artifact, plan) = fixture();
        artifact.rewritten_accessors.pop();
        expect_claim(
            &source,
            &artifact,
            &plan,
            "artifact reports exactly the accessors this proof independently derives",
        );
    }

    #[test]
    fn an_under_reported_rewritten_json_pointer_fails_the_pointer_cross_check() {
        let (source, mut artifact, plan) = fixture();
        artifact.rewritten_json_pointers.pop();
        expect_claim(
            &source,
            &artifact,
            &plan,
            "artifact reports exactly the JSON pointers this proof independently derives",
        );
    }

    #[test]
    fn added_and_removed_preserved_json_locations_keep_whole_document_direction() {
        let (source, mut artifact, plan) = fixture();
        let mut value = artifact_value(&artifact);
        let material = value["materials"][0]
            .as_object_mut()
            .expect("fixture material is an object");
        material.remove("name");
        material.insert("replacement".into(), json!(true));
        put_artifact_value(&mut artifact, &value);
        let error = prove_rewritten_artifact(&source, &artifact, &plan)
            .expect_err("changed preserved JSON must fail");
        assert_eq!(
            error.to_string(),
            "artifact proof claim \"every raw JSON location outside the converted set is preserved exactly\" observed 2, tolerance 0; raw JSON differences: /materials/0/name (artifact-removed), /materials/0/replacement (artifact-added)"
        );
        match error {
            GltfScaleRewriteError::ArtifactProofFailed {
                claim,
                observed,
                tolerance,
                raw_json_differences: Some(summary),
            } => {
                assert_eq!(
                    claim,
                    "every raw JSON location outside the converted set is preserved exactly"
                );
                assert_eq!(observed, 2.0);
                assert_eq!(tolerance, 0.0);
                assert_eq!(
                    summary,
                    GltfRawJsonDifferenceSummary {
                        differences: vec![
                            GltfRawJsonDifference {
                                pointer: "/materials/0/name".into(),
                                kind: GltfRawJsonDifferenceKind::ArtifactRemoved,
                            },
                            GltfRawJsonDifference {
                                pointer: "/materials/0/replacement".into(),
                                kind: GltfRawJsonDifferenceKind::ArtifactAdded,
                            },
                        ],
                        omitted: 0,
                    }
                );
            }
            other => panic!("expected located JSON diagnostics, got {other:?}"),
        }
    }

    #[test]
    fn json_difference_collection_is_typed_escaped_ordered_and_allowlisted() {
        let before = json!({
            "a~/b~/c": 1,
            "allowed": "source secret",
            "allowedly": 1,
            "removed": true,
            "value": 1
        });
        let after = json!({
            "a~/b~/c": 2,
            "added": true,
            "allowed": "artifact secret",
            "allowedly": 2,
            "value": 2
        });
        let allowed = BTreeSet::from(["/allowed".to_owned()]);
        let mut collector = RawJsonDifferenceCollector::default();
        collect_json_differences(&before, &after, "", &allowed, &mut collector);
        assert_eq!(
            collector.finish(),
            GltfRawJsonDifferenceSummary {
                differences: vec![
                    GltfRawJsonDifference {
                        pointer: "/added".into(),
                        kind: GltfRawJsonDifferenceKind::ArtifactAdded,
                    },
                    GltfRawJsonDifference {
                        pointer: "/allowedly".into(),
                        kind: GltfRawJsonDifferenceKind::ValueChanged,
                    },
                    GltfRawJsonDifference {
                        pointer: "/a~0~1b~0~1c".into(),
                        kind: GltfRawJsonDifferenceKind::ValueChanged,
                    },
                    GltfRawJsonDifference {
                        pointer: "/removed".into(),
                        kind: GltfRawJsonDifferenceKind::ArtifactRemoved,
                    },
                    GltfRawJsonDifference {
                        pointer: "/value".into(),
                        kind: GltfRawJsonDifferenceKind::ValueChanged,
                    },
                ],
                omitted: 0,
            }
        );
    }

    #[test]
    fn json_difference_collection_preserves_zero_sign_and_quaternion_sign() {
        let before: Value = serde_json::from_str(
            r#"{"extras":{"authoredZero":-0.0},"nodes":[{"rotation":[0.0,0.0,0.0,-1.0]}]}"#,
        )
        .expect("source JSON");
        let after: Value = serde_json::from_str(
            r#"{"extras":{"authoredZero":0.0},"nodes":[{"rotation":[0.0,0.0,0.0,1.0]}]}"#,
        )
        .expect("artifact JSON");
        assert_eq!(
            before["extras"]["authoredZero"]
                .as_f64()
                .expect("source zero")
                .to_bits(),
            (-0.0f64).to_bits()
        );
        let mut collector = RawJsonDifferenceCollector::default();
        collect_json_differences(&before, &after, "", &BTreeSet::new(), &mut collector);
        assert_eq!(
            collector.finish(),
            GltfRawJsonDifferenceSummary {
                differences: vec![
                    GltfRawJsonDifference {
                        pointer: "/extras/authoredZero".into(),
                        kind: GltfRawJsonDifferenceKind::ValueChanged,
                    },
                    GltfRawJsonDifference {
                        pointer: "/nodes/0/rotation/3".into(),
                        kind: GltfRawJsonDifferenceKind::ValueChanged,
                    },
                ],
                omitted: 0,
            }
        );
    }

    #[test]
    fn json_difference_collection_caps_storage_but_counts_every_difference() {
        let mut before = Map::new();
        let mut after = Map::new();
        for index in 0..20 {
            let key = format!("key-{index:02}");
            match index % 3 {
                0 => {
                    before.insert(key.clone(), json!(0));
                    after.insert(key, json!(1));
                }
                1 => {
                    after.insert(key, json!(1));
                }
                _ => {
                    before.insert(key, json!(0));
                }
            }
        }
        let error = check_preserved_json(
            &Value::Object(before),
            &Value::Object(after),
            &BTreeSet::new(),
            "the capped preservation fixture stays exact",
        )
        .expect_err("twenty preserved-location differences must fail");
        let GltfScaleRewriteError::ArtifactProofFailed {
            claim,
            observed,
            tolerance,
            raw_json_differences: Some(summary),
        } = error
        else {
            panic!("expected located JSON diagnostics, got {error:?}");
        };
        assert_eq!(claim, "the capped preservation fixture stays exact");
        assert_eq!(observed, 20.0, "observed retains the full count");
        assert_eq!(tolerance, 0.0);
        assert_eq!(summary.differences.len() + summary.omitted, 20);
        assert_eq!(summary.omitted, 4);
        assert_eq!(
            summary.differences,
            (0..MAX_RAW_JSON_DIFFERENCES)
                .map(|index| GltfRawJsonDifference {
                    pointer: format!("/key-{index:02}"),
                    kind: match index % 3 {
                        0 => GltfRawJsonDifferenceKind::ValueChanged,
                        1 => GltfRawJsonDifferenceKind::ArtifactAdded,
                        _ => GltfRawJsonDifferenceKind::ArtifactRemoved,
                    },
                })
                .collect::<Vec<_>>()
        );
        let display = super::super::RawJsonDifferenceSuffix(Some(&summary)).to_string();
        assert!(display.ends_with("; 4 omitted"));
        assert!(display.contains("/key-15 (value-changed)"));
        assert!(
            !display.contains("/key-16"),
            "omitted pointers stay omitted"
        );
    }

    #[test]
    fn unequal_arrays_report_one_value_change_at_the_array_root() {
        for (before, after) in [
            (json!({ "nodes": [1] }), json!({ "nodes": [1, 2] })),
            (json!({ "nodes": [1, 2] }), json!({ "nodes": [1] })),
        ] {
            let mut collector = RawJsonDifferenceCollector::default();
            collect_json_differences(&before, &after, "", &BTreeSet::new(), &mut collector);
            assert_eq!(
                collector.finish(),
                GltfRawJsonDifferenceSummary {
                    differences: vec![GltfRawJsonDifference {
                        pointer: "/nodes".into(),
                        kind: GltfRawJsonDifferenceKind::ValueChanged,
                    }],
                    omitted: 0,
                }
            );
        }
    }

    #[test]
    fn a_changed_top_level_array_length_fails_array_identity() {
        let (source, mut artifact, plan) = fixture();
        let mut value = artifact_value(&artifact);
        value["materials"]
            .as_array_mut()
            .expect("materials array")
            .push(json!({ "name": "smuggled" }));
        put_artifact_value(&mut artifact, &value);
        expect_claim(
            &source,
            &artifact,
            &plan,
            "every top-level array keeps its source length",
        );
    }

    #[test]
    fn a_resolved_buffer_that_grew_fails_the_buffer_length_claim() {
        // `byteLength` is left alone, so the growth is invisible to the JSON
        // comparison and only the resolved-bytes claim can see it.
        let (source, mut artifact, plan) = fixture();
        let mut value = artifact_value(&artifact);
        let mut buffer = artifact_buffer(&value);
        buffer.extend_from_slice(&[0u8; 4]);
        put_artifact_buffer(&mut value, &buffer);
        put_artifact_value(&mut artifact, &value);
        expect_claim(
            &source,
            &artifact,
            &plan,
            "every resolved buffer keeps its source byte length",
        );
    }

    #[test]
    fn a_declared_buffer_length_without_backing_bytes_fails_container_integrity() {
        let (source, mut artifact, plan) = fixture();
        let mut value = artifact_value(&artifact);
        value["buffers"][0]["byteLength"] = json!(offsets::LENGTH + 4);
        put_artifact_value(&mut artifact, &value);
        expect_claim(
            &source,
            &artifact,
            &plan,
            "every declared buffer byteLength is backed by resolved bytes",
        );
    }

    #[test]
    fn a_flipped_container_kind_fails_the_container_claim() {
        let (source, mut artifact, plan) = fixture();
        artifact.container = GltfContainerKind::Glb;
        expect_claim(
            &source,
            &artifact,
            &plan,
            "artifact container kind is unchanged",
        );
    }

    #[test]
    fn a_bound_that_no_longer_bounds_the_converted_payload_fails() {
        // One ULP above the converted minimum: far inside the shared scalar
        // tolerance, so every residual still passes and only the bounding
        // obligation itself can reject it.
        let (source, mut artifact, plan) = fixture();
        let mut value = artifact_value(&artifact);
        value["accessors"][0]["min"][0] = json!(2.0000002f32 as f64);
        put_artifact_value(&mut artifact, &value);
        expect_claim(
            &source,
            &artifact,
            &plan,
            "a converted bound still bounds the converted payload",
        );
    }

    #[test]
    fn bytes_that_are_not_the_rewriters_own_output_fail_the_determinism_claim() {
        // Same JSON value, different bytes. Every claim that reads the
        // artifact through `serde_json` still passes, so nothing but the
        // byte-for-byte repeat comparison can notice.
        let (source, mut artifact, plan) = fixture();
        let value = artifact_value(&artifact);
        artifact.bytes = serde_json::to_vec_pretty(&value).expect("pretty serializes");
        expect_claim(
            &source,
            &artifact,
            &plan,
            "rewriting the same source twice yields identical bytes",
        );
    }

    #[test]
    fn a_nested_converted_range_does_not_rewind_the_preserved_byte_cursor() {
        // `check_preserved_bytes` is exercised directly here because #280
        // rejects a source whose scale-bearing accessor ranges overlap, so
        // `prove_rewritten_artifact` can never hand it a nested pair. The
        // guard that makes the walk safe anyway is `cursor.max(end)`: without
        // it the inner span rewinds the cursor to 8 and bytes 8..16 — which
        // lie *inside* the outer converted range and are legitimately allowed
        // to differ — get compared as if they were preserved.
        let mut before = vec![0u8; 20];
        let mut after = vec![0u8; 20];
        before[10] = 1;
        after[10] = 2;
        let span = |start: usize, end: usize| AccessorSpan {
            accessor_index: 0,
            buffer: 0,
            start,
            end,
            components: 1,
        };
        let spans = [span(0, 16), span(4, 8)];
        let preserved = check_preserved_bytes(&[before], &[after], &spans)
            .expect("only 16..20 lies outside the converted ranges");
        assert_eq!(preserved, 1);
    }
}