animsmith-engine 0.14.0

Strict, versioned engine-import profile facts and deterministic settings resolution for AnimSmith
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
//! Engine-owned checks derived from immutable profile and same-load source evidence.

use crate::addressability::{
    GltfAnimationAddressabilityBevyAdapterV1, GltfAnimationAddressabilityInventoryV1,
};
use crate::error::PredictionRuleError;
use crate::registry::profiles_v1;
use animsmith_core::{
    Applicability, Check, CheckCtx, CheckOutput, CheckSelection, EngineAnimationAddressabilityV1,
    EngineFactIdV1, EngineFactStateV1, EngineFactValueV1, EnginePredictionBasisV1,
    EnginePredictionBasisV2, EnginePredictionFacetV1, EnginePredictionFacetV2,
    EnginePredictionFacetV3, EnginePredictionV1, EnginePredictionV2, EnginePredictionV3,
    EvaluationScope, EvaluationScopeCode, LoadedSource, PredictionBasisReferenceV1,
    PredictionBasisReferenceV2, PredictionFacetDemandV2, PredictionProvenanceV1,
    PredictionProvenanceV2, PredictionProvenanceV3, PredictionRuleAllocationV2,
    PredictionUnavailableReasonV1, RAW_SOURCE_V1_MAX_CLIPS, RawSourceBasisReferenceV1,
    RawSourceBindingV1, RawSourceBindingV2, RawSourceDomainV1, RawSourceFieldIdV1, RawSourceKeyV1,
    SourceFormatV1, SourceSetCoverageStateV1, evaluate_checks,
};

/// A Bevy animation asset-label index outside the bounded raw-source
/// animation inventory.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("source animation index {source_clip_index} is outside the V1 limit of {limit} animations")]
pub struct BevyAnimationAssetLabelError {
    /// Supplied source animation index.
    pub source_clip_index: usize,
    /// Exclusive upper bound for V1 source animation indices.
    pub limit: usize,
}

/// Typed failure while constructing the optional exact Bevy adapter for a
/// glTF animation-addressability document.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum GltfAnimationAddressabilityAdapterError {
    /// Same-load source binding or frozen-profile validation failed.
    #[error(transparent)]
    PredictionRule(#[from] PredictionRuleError),
    /// The existing engine-addressability check could not form a valid
    /// [`animsmith_core::CheckEvaluation`].
    #[error(transparent)]
    Evaluation(#[from] animsmith_core::EvaluationError),
    /// The standalone contract rejected inconsistent inventory, provenance,
    /// or check evidence.
    #[error(transparent)]
    Contract(#[from] crate::GltfAnimationAddressabilityError),
}

/// Stable check id for engine scene, animation, target, and runtime-label addressability.
pub const ENGINE_ADDRESSABILITY_CHECK_ID: &str = "engine-addressability";

/// Versioned engine-owned check ids callers may use for pre-I/O selection validation.
pub const ENGINE_CHECK_IDS_V1: &[&str] = &[ENGINE_ADDRESSABILITY_CHECK_ID];

/// Current engine-owned check ids in immutable catalog order.
///
/// The V1 catalog remains unchanged for historical standalone addressability
/// artifacts; current lint may additionally register the V3-only exact source
/// boundary rule.
pub const ENGINE_CHECK_IDS_V2: &[&str] = &[
    ENGINE_ADDRESSABILITY_CHECK_ID,
    crate::clip_boundary::ENGINE_CLIP_BOUNDARY_CHECK_ID,
    crate::unit_scale::ENGINE_UNIT_SCALE_CHECK_ID,
    crate::track_support::ENGINE_TRACK_SUPPORT_CHECK_ID,
    crate::root_motion::ENGINE_ROOT_MOTION_CHECK_ID,
];

const BEVY_FAMILY: &str = "bevy";
const BEVY_PROFILE_REVISION: u32 = 1;
const BEVY_ENGINE_VERSION: &str = "0.19.0";
const BEVY_IMPORTER: &str = "gltf-asset-loader";
const BEVY_ANIMATION_LABEL_SOURCE: &str = "bevy-gltf-asset-label-0.19.0";

/// One exact Bevy 0.19.0 `GltfAssetLabel::Animation(index)` display selector.
///
/// The source animation index is authoritative. Source names are optional,
/// non-unique metadata and never affect this value. Construction enforces the
/// same 4,096-row ceiling as raw-source facts, so the retained selector text is
/// bounded to `Animation0` through `Animation4095`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BevyAnimationAssetLabelV1 {
    source_clip_index: usize,
    display_selector: String,
}

impl BevyAnimationAssetLabelV1 {
    /// Construct the indexed selector for one retained source animation.
    ///
    /// # Errors
    ///
    /// Returns [`BevyAnimationAssetLabelError`] when the index cannot occur in
    /// the bounded V1 raw-source animation inventory.
    pub fn new(source_clip_index: usize) -> Result<Self, BevyAnimationAssetLabelError> {
        if source_clip_index >= RAW_SOURCE_V1_MAX_CLIPS {
            return Err(BevyAnimationAssetLabelError {
                source_clip_index,
                limit: RAW_SOURCE_V1_MAX_CLIPS,
            });
        }
        Ok(Self {
            source_clip_index,
            display_selector: format!("Animation{source_clip_index}"),
        })
    }

    /// Exact source animation index carried by this selector.
    pub const fn source_clip_index(&self) -> usize {
        self.source_clip_index
    }

    /// Exact Bevy display selector, such as `Animation0`.
    pub fn as_str(&self) -> &str {
        &self.display_selector
    }
}

/// The engine addressability check over borrowed same-load source evidence.
///
/// When provenance is absent or is not exactly the frozen Bevy 0.19.0 glTF profile, the check
/// records a stable not-applicable evaluation. Construction performs bounded in-memory
/// validation against the immutable source sidecars but no filesystem or parser work.
pub struct EngineAddressabilityCheck<'a> {
    source: &'a LoadedSource,
    provenance: Option<&'a PredictionProvenanceV1>,
}

/// Current-lint V2 engine addressability check. Standalone addressability
/// artifacts keep using [`EngineAddressabilityCheck`] and immutable V1 wire
/// evidence.
pub struct EngineAddressabilityCheckV2<'a> {
    source: &'a LoadedSource,
    provenance: Option<&'a PredictionProvenanceV2>,
}

/// Current-output V3 engine addressability check.
///
/// This preserves the V2 rule and allocation behavior while lifting its basis
/// references and prediction attachment into the exact-source-capable V3
/// contracts required by current lint output.
pub struct EngineAddressabilityCheckV3<'a> {
    source: &'a LoadedSource,
    provenance: Option<&'a PredictionProvenanceV3>,
}

impl<'a> EngineAddressabilityCheckV3<'a> {
    /// Bind current V3 provenance to same-load source evidence.
    pub fn new(
        source: &'a LoadedSource,
        provenance: Option<&'a PredictionProvenanceV3>,
    ) -> Result<Self, PredictionRuleError> {
        if let Some(provenance) = provenance {
            provenance
                .validate()
                .map_err(|_| PredictionRuleError::SourceProvenanceMismatch)?;
            let raw_source = RawSourceBindingV2::from_source(
                source.source_facts(),
                source.exact_source_timing(),
            )
            .map_err(|_| PredictionRuleError::SourceProvenanceMismatch)?;
            if &raw_source != provenance.raw_source()
                || source.dependency_closure() != provenance.dependency_closure()
            {
                return Err(PredictionRuleError::SourceProvenanceMismatch);
            }
            let selection = provenance.profile().selection();
            if selection.family() == BEVY_FAMILY
                && selection.profile_revision() == BEVY_PROFILE_REVISION
                && selection.engine_version() == BEVY_ENGINE_VERSION
                && selection.importer() == BEVY_IMPORTER
                && !profiles_v1().iter().any(|profile| {
                    let selection = profile.selection();
                    selection.family() == BEVY_FAMILY
                        && selection.profile_revision() == BEVY_PROFILE_REVISION
                        && selection.engine_version() == BEVY_ENGINE_VERSION
                        && selection.importer() == BEVY_IMPORTER
                        && profile.facts_identity() == provenance.profile().facts_identity()
                })
            {
                return Err(PredictionRuleError::FrozenProfileMismatch);
            }
        }
        Ok(Self { source, provenance })
    }
}

impl Check for EngineAddressabilityCheckV3<'_> {
    fn id(&self) -> &'static str {
        ENGINE_ADDRESSABILITY_CHECK_ID
    }

    fn applicability(&self, _ctx: &CheckCtx<'_>) -> Applicability {
        match self.provenance {
            Some(provenance)
                if is_bevy_gltf_v3(self.source, provenance)
                    && !facts_are_complete_and_empty(self.source) =>
            {
                Applicability::Applicable
            }
            _ => Applicability::NotApplicable,
        }
    }

    fn evaluate(&self, _ctx: &CheckCtx<'_>) -> CheckOutput {
        let Some(provenance) = self.provenance else {
            return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
        };
        if !is_bevy_gltf_v3(self.source, provenance) || facts_are_complete_and_empty(self.source) {
            return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
        }
        evaluate_animation_asset_labels_v3(self.source, provenance)
    }

    fn prediction_facet_demand_v2(&self, _ctx: &CheckCtx<'_>) -> PredictionFacetDemandV2 {
        match self.provenance {
            Some(provenance)
                if is_bevy_gltf_v3(self.source, provenance)
                    && !facts_are_complete_and_empty(self.source) =>
            {
                if self.source.source_facts().clips().coverage().state()
                    != SourceSetCoverageStateV1::Complete
                    || matches!(
                        provenance.settings().clip_coverage().state(),
                        animsmith_core::ResolvedEngineSettingsCoverageStateV2::Partial
                    )
                {
                    PredictionFacetDemandV2::Exact(1)
                } else {
                    PredictionFacetDemandV2::Exact(self.source.source_facts().clips().rows().len())
                }
            }
            _ => PredictionFacetDemandV2::Exact(0),
        }
    }

    fn evaluate_with_prediction_allocation_v2(
        &self,
        _ctx: &CheckCtx<'_>,
        allocation: PredictionRuleAllocationV2<'_>,
    ) -> CheckOutput {
        let Some(provenance) = self.provenance else {
            return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
        };
        if !is_bevy_gltf_v3(self.source, provenance) || facts_are_complete_and_empty(self.source) {
            return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
        }
        evaluate_animation_asset_labels_v3_allocated(self.source, provenance, allocation)
    }
}

impl<'a> EngineAddressabilityCheckV2<'a> {
    /// Bind current-lint V2 provenance to same-load source evidence.
    pub fn new(
        source: &'a LoadedSource,
        provenance: Option<&'a PredictionProvenanceV2>,
    ) -> Result<Self, PredictionRuleError> {
        if let Some(provenance) = provenance {
            provenance
                .validate()
                .map_err(|_| PredictionRuleError::SourceProvenanceMismatch)?;
            let raw_source = RawSourceBindingV1::from_source(source.source_facts());
            if &raw_source != provenance.raw_source()
                || source.dependency_closure() != provenance.dependency_closure()
            {
                return Err(PredictionRuleError::SourceProvenanceMismatch);
            }
            let selection = provenance.profile().selection();
            if selection.family() == BEVY_FAMILY
                && selection.profile_revision() == BEVY_PROFILE_REVISION
                && selection.engine_version() == BEVY_ENGINE_VERSION
                && selection.importer() == BEVY_IMPORTER
                && !profiles_v1().iter().any(|profile| {
                    let selection = profile.selection();
                    selection.family() == BEVY_FAMILY
                        && selection.profile_revision() == BEVY_PROFILE_REVISION
                        && selection.engine_version() == BEVY_ENGINE_VERSION
                        && selection.importer() == BEVY_IMPORTER
                        && profile.facts_identity() == provenance.profile().facts_identity()
                })
            {
                return Err(PredictionRuleError::FrozenProfileMismatch);
            }
        }
        Ok(Self { source, provenance })
    }
}

impl Check for EngineAddressabilityCheckV2<'_> {
    fn id(&self) -> &'static str {
        ENGINE_ADDRESSABILITY_CHECK_ID
    }

    fn applicability(&self, _ctx: &CheckCtx<'_>) -> Applicability {
        let Some(provenance) = self.provenance else {
            return Applicability::NotApplicable;
        };
        if !is_bevy_gltf_v2(self.source, provenance) || facts_are_complete_and_empty(self.source) {
            Applicability::NotApplicable
        } else {
            Applicability::Applicable
        }
    }

    fn evaluate(&self, _ctx: &CheckCtx<'_>) -> CheckOutput {
        let Some(provenance) = self.provenance else {
            return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
        };
        if !is_bevy_gltf_v2(self.source, provenance) || facts_are_complete_and_empty(self.source) {
            return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
        }
        evaluate_animation_asset_labels_v2(self.source, provenance)
    }

    fn prediction_facet_demand_v2(&self, _ctx: &CheckCtx<'_>) -> PredictionFacetDemandV2 {
        match self.provenance {
            Some(provenance)
                if is_bevy_gltf_v2(self.source, provenance)
                    && !facts_are_complete_and_empty(self.source) =>
            {
                // An incomplete raw/settings inventory produces one
                // unavailable inventory facet, not one facet per retained
                // row.  Its pre-evaluation reservation must match that
                // actual candidate work.
                if self.source.source_facts().clips().coverage().state()
                    != SourceSetCoverageStateV1::Complete
                    || matches!(
                        provenance.settings().clip_coverage().state(),
                        animsmith_core::ResolvedEngineSettingsCoverageStateV2::Partial
                    )
                {
                    PredictionFacetDemandV2::Exact(1)
                } else {
                    PredictionFacetDemandV2::Exact(self.source.source_facts().clips().rows().len())
                }
            }
            _ => PredictionFacetDemandV2::Exact(0),
        }
    }

    fn evaluate_with_prediction_allocation_v2(
        &self,
        _ctx: &CheckCtx<'_>,
        allocation: PredictionRuleAllocationV2<'_>,
    ) -> CheckOutput {
        let Some(provenance) = self.provenance else {
            return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
        };
        if !is_bevy_gltf_v2(self.source, provenance) || facts_are_complete_and_empty(self.source) {
            return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
        }
        evaluate_animation_asset_labels_v2_allocated(self.source, provenance, allocation)
    }
}

impl<'a> EngineAddressabilityCheck<'a> {
    /// Bind one source and optional immutable prediction provenance.
    ///
    /// # Errors
    ///
    /// Returns [`PredictionRuleError::SourceProvenanceMismatch`] when the
    /// provenance was not projected from the supplied same-load source facts
    /// and dependency closure, or [`PredictionRuleError::FrozenProfileMismatch`]
    /// when an exact Bevy tuple does not carry the frozen registry facts.
    pub fn new(
        source: &'a LoadedSource,
        provenance: Option<&'a PredictionProvenanceV1>,
    ) -> Result<Self, PredictionRuleError> {
        if let Some(provenance) = provenance {
            let raw_source = RawSourceBindingV1::from_source(source.source_facts());
            if &raw_source != provenance.raw_source()
                || source.dependency_closure() != provenance.dependency_closure()
            {
                return Err(PredictionRuleError::SourceProvenanceMismatch);
            }
            if is_bevy_tuple(provenance)
                && !profiles_v1().iter().any(|profile| {
                    let selection = profile.selection();
                    selection.family() == BEVY_FAMILY
                        && selection.profile_revision() == BEVY_PROFILE_REVISION
                        && selection.engine_version() == BEVY_ENGINE_VERSION
                        && selection.importer() == BEVY_IMPORTER
                        && profile.facts_identity() == provenance.profile().facts_identity()
                })
            {
                return Err(PredictionRuleError::FrozenProfileMismatch);
            }
        }
        Ok(Self { source, provenance })
    }
}

impl Check for EngineAddressabilityCheck<'_> {
    fn id(&self) -> &'static str {
        ENGINE_ADDRESSABILITY_CHECK_ID
    }

    fn applicability(&self, _ctx: &CheckCtx<'_>) -> Applicability {
        borrowed_applicability(self.source, self.provenance)
    }

    fn evaluate(&self, _ctx: &CheckCtx<'_>) -> CheckOutput {
        let Some(provenance) = self.provenance else {
            return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
        };
        if !is_bevy_gltf(self.source, provenance) || facts_are_complete_and_empty(self.source) {
            return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
        }
        evaluate_animation_asset_labels(self.source, provenance)
    }
}

/// Build the optional exact Bevy 0.19.0 adapter for one addressability document.
///
/// This is the single adapter assembly path: it binds the existing
/// [`EngineAddressabilityCheck`] to the supplied same-load source and
/// provenance, sends that one check through [`evaluate_checks`] exactly once,
/// then lets the standalone contract validate the unchanged resulting evaluation
/// against the neutral inventory. No-profile and valid non-Bevy provenance
/// produce `None` without adding another check or prediction lifecycle.
///
/// # Errors
///
/// Returns [`GltfAnimationAddressabilityAdapterError`] when same-load or
/// frozen-profile validation fails, the existing check cannot produce a valid
/// evaluation, or the standalone contract rejects inconsistent evidence.
pub fn build_bevy_animation_addressability_adapter_v1(
    source: &LoadedSource,
    inventory: &GltfAnimationAddressabilityInventoryV1,
    prediction_provenance: Option<PredictionProvenanceV1>,
    ctx: &CheckCtx<'_>,
) -> Result<Option<GltfAnimationAddressabilityBevyAdapterV1>, GltfAnimationAddressabilityAdapterError>
{
    let Some(prediction_provenance) = prediction_provenance else {
        return Ok(None);
    };
    let check = EngineAddressabilityCheck::new(source, Some(&prediction_provenance))?;
    if !is_bevy_gltf(source, &prediction_provenance) {
        return Ok(None);
    }

    let evaluation = {
        let checks: [Box<dyn Check + '_>; 1] = [Box::new(check)];
        let mut evaluations = evaluate_checks(ctx, &checks, CheckSelection::All)?;
        let evaluation = evaluations
            .pop()
            .expect("one valid static check catalog produces one evaluation");
        debug_assert!(evaluations.is_empty());
        evaluation
    };
    Ok(Some(GltfAnimationAddressabilityBevyAdapterV1::new(
        prediction_provenance,
        evaluation,
        inventory,
    )?))
}

fn borrowed_applicability(
    source: &LoadedSource,
    provenance: Option<&PredictionProvenanceV1>,
) -> Applicability {
    let Some(provenance) = provenance else {
        return Applicability::NotApplicable;
    };
    if !is_bevy_gltf(source, provenance) {
        return Applicability::NotApplicable;
    }
    if facts_are_complete_and_empty(source) {
        Applicability::NotApplicable
    } else {
        Applicability::Applicable
    }
}

fn facts_are_complete_and_empty(source: &LoadedSource) -> bool {
    let clips = source.source_facts().clips();
    clips.coverage().state() == SourceSetCoverageStateV1::Complete && clips.rows().is_empty()
}

fn is_bevy_gltf(source: &LoadedSource, provenance: &PredictionProvenanceV1) -> bool {
    let facts = source.source_facts();
    facts.format() == provenance.source_format()
        && is_bevy_tuple(provenance)
        && matches!(
            provenance.source_format(),
            SourceFormatV1::GltfJson | SourceFormatV1::Glb
        )
        && matches!(
            provenance
                .profile()
                .fact(EngineFactIdV1::AnimationAddressability)
                .map(|fact| fact.state()),
            Some(EngineFactStateV1::Known(
                EngineFactValueV1::AnimationAddressability(
                    EngineAnimationAddressabilityV1::GltfAssetLabel
                )
            ))
        )
        && provenance
            .profile()
            .source(BEVY_ANIMATION_LABEL_SOURCE)
            .is_some()
}

fn is_bevy_gltf_v2(source: &LoadedSource, provenance: &PredictionProvenanceV2) -> bool {
    let selection = provenance.profile().selection();
    source.source_facts().format() == provenance.source_format()
        && selection.family() == BEVY_FAMILY
        && selection.profile_revision() == BEVY_PROFILE_REVISION
        && selection.engine_version() == BEVY_ENGINE_VERSION
        && selection.importer() == BEVY_IMPORTER
        && matches!(
            provenance
                .profile()
                .fact(EngineFactIdV1::AnimationAddressability)
                .map(|fact| fact.state()),
            Some(EngineFactStateV1::Known(
                EngineFactValueV1::AnimationAddressability(
                    EngineAnimationAddressabilityV1::GltfAssetLabel
                )
            ))
        )
        && provenance
            .profile()
            .source(BEVY_ANIMATION_LABEL_SOURCE)
            .is_some()
}

fn is_bevy_gltf_v3(source: &LoadedSource, provenance: &PredictionProvenanceV3) -> bool {
    let selection = provenance.profile().selection();
    source.source_facts().format() == provenance.source_format()
        && selection.family() == BEVY_FAMILY
        && selection.profile_revision() == BEVY_PROFILE_REVISION
        && selection.engine_version() == BEVY_ENGINE_VERSION
        && selection.importer() == BEVY_IMPORTER
        && matches!(
            provenance
                .profile()
                .fact(EngineFactIdV1::AnimationAddressability)
                .map(|fact| fact.state()),
            Some(EngineFactStateV1::Known(
                EngineFactValueV1::AnimationAddressability(
                    EngineAnimationAddressabilityV1::GltfAssetLabel
                )
            ))
        )
        && provenance
            .profile()
            .source(BEVY_ANIMATION_LABEL_SOURCE)
            .is_some()
}

fn is_bevy_tuple(provenance: &PredictionProvenanceV1) -> bool {
    let selection = provenance.profile().selection();
    selection.family() == BEVY_FAMILY
        && selection.profile_revision() == BEVY_PROFILE_REVISION
        && selection.engine_version() == BEVY_ENGINE_VERSION
        && selection.importer() == BEVY_IMPORTER
}

fn evaluate_animation_asset_labels(
    source: &LoadedSource,
    provenance: &PredictionProvenanceV1,
) -> CheckOutput {
    let facts = source.source_facts();
    let inventory_scope =
        EvaluationScope::new(EvaluationScopeCode::ANIMATION_ASSET_LABEL_INVENTORY);
    if facts.format() != provenance.source_format()
        || facts.clips().coverage().state() != SourceSetCoverageStateV1::Complete
    {
        return unavailable_inventory(provenance, inventory_scope);
    }

    let mut scopes = Vec::with_capacity(facts.clips().rows().len());
    let mut facets = Vec::with_capacity(facts.clips().rows().len());
    for clip in facts.clips().rows() {
        let source_index = clip.source_clip_index();
        let label = BevyAnimationAssetLabelV1::new(source_index)
            .expect("loader-valid retained clip indices satisfy the V1 raw-source bound");
        let scope = EvaluationScope::new(EvaluationScopeCode::ANIMATION_ASSET_LABEL)
            .subject(label.as_str().to_owned());
        let source_name = RawSourceBasisReferenceV1::from_source(
            RawSourceDomainV1::Clip,
            RawSourceKeyV1::Clip {
                source_clip_index: source_index as u64,
            },
            RawSourceFieldIdV1::new("source_name.state").expect("static field is valid"),
            facts,
        )
        .expect("loader-valid retained clip rows must resolve their own raw-source witness");
        let basis = EnginePredictionBasisV1::new(vec![
            PredictionBasisReferenceV1::profile_fact("animation_addressability")
                .expect("static fact id is valid"),
            PredictionBasisReferenceV1::primary_source(BEVY_ANIMATION_LABEL_SOURCE)
                .expect("static primary-source id is valid"),
            PredictionBasisReferenceV1::raw_source(source_name),
        ])
        .expect("three distinct static basis references are valid");
        let facet = EnginePredictionFacetV1::available(scope.clone(), basis)
            .expect("complete source rows have unique bounded scopes");
        scopes.push(scope);
        facets.push(facet);
    }

    if facets.is_empty() {
        return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
    }
    let prediction = EnginePredictionV1::new(provenance.identity().clone(), facets)
        .expect("complete bounded source rows form one valid canonical prediction");
    CheckOutput::from_coverage(Vec::new(), scopes, Vec::new()).with_engine_prediction(prediction)
}

fn unavailable_inventory(
    provenance: &PredictionProvenanceV1,
    scope: EvaluationScope,
) -> CheckOutput {
    let basis = EnginePredictionBasisV1::new(vec![
        PredictionBasisReferenceV1::profile_fact("animation_addressability")
            .expect("static fact id is valid"),
        PredictionBasisReferenceV1::primary_source(BEVY_ANIMATION_LABEL_SOURCE)
            .expect("static primary-source id is valid"),
    ])
    .expect("static basis is nonempty and canonical");
    let facet = EnginePredictionFacetV1::required_unavailable(
        scope,
        basis,
        vec![PredictionUnavailableReasonV1::RawSourceIncomplete],
    )
    .expect("static unavailable facet is valid");
    let prediction = EnginePredictionV1::new(provenance.identity().clone(), vec![facet])
        .expect("one static facet is valid");
    CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new())
        .with_engine_prediction(prediction)
}

fn evaluate_animation_asset_labels_v2(
    source: &LoadedSource,
    provenance: &PredictionProvenanceV2,
) -> CheckOutput {
    let facts = source.source_facts();
    let inventory_scope =
        EvaluationScope::new(EvaluationScopeCode::ANIMATION_ASSET_LABEL_INVENTORY);
    let settings_overflow = matches!(
        provenance.settings().clip_coverage().state(),
        animsmith_core::ResolvedEngineSettingsCoverageStateV2::Partial
    );
    if facts.clips().coverage().state() != SourceSetCoverageStateV1::Complete || settings_overflow {
        let basis = EnginePredictionBasisV1::new(vec![
            PredictionBasisReferenceV1::profile_fact("animation_addressability")
                .expect("static fact id is valid"),
            PredictionBasisReferenceV1::primary_source(BEVY_ANIMATION_LABEL_SOURCE)
                .expect("static primary-source id is valid"),
        ])
        .expect("static basis is canonical");
        let mut reasons = Vec::new();
        if facts.clips().coverage().state() != SourceSetCoverageStateV1::Complete {
            reasons.push(animsmith_core::PredictionUnavailableReasonV2::RawSourceIncomplete);
        }
        if settings_overflow {
            reasons.push(animsmith_core::PredictionUnavailableReasonV2::ResolvedSettingsOverflow);
        }
        let facet = EnginePredictionFacetV2::required_unavailable(inventory_scope, basis, reasons)
            .expect("static unavailable V2 facet is valid");
        let prediction = EnginePredictionV2::new(provenance.identity().clone(), vec![facet])
            .expect("one static V2 facet is valid");
        return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new())
            .with_engine_prediction_v2(prediction);
    }

    let mut scopes = Vec::with_capacity(facts.clips().rows().len());
    let mut facets = Vec::with_capacity(facts.clips().rows().len());
    for clip in facts.clips().rows() {
        let source_index = clip.source_clip_index();
        let label = BevyAnimationAssetLabelV1::new(source_index)
            .expect("loader-valid retained clip indices satisfy the V1 raw-source bound");
        let scope = EvaluationScope::new(EvaluationScopeCode::ANIMATION_ASSET_LABEL)
            .subject(label.as_str().to_owned());
        let source_name = RawSourceBasisReferenceV1::from_source(
            RawSourceDomainV1::Clip,
            RawSourceKeyV1::Clip {
                source_clip_index: source_index as u64,
            },
            RawSourceFieldIdV1::new("source_name.state").expect("static field is valid"),
            facts,
        )
        .expect("retained clip rows resolve their raw-source witness");
        let basis = EnginePredictionBasisV1::new(vec![
            PredictionBasisReferenceV1::profile_fact("animation_addressability")
                .expect("static fact id is valid"),
            PredictionBasisReferenceV1::primary_source(BEVY_ANIMATION_LABEL_SOURCE)
                .expect("static primary-source id is valid"),
            PredictionBasisReferenceV1::raw_source(source_name),
        ])
        .expect("three static basis references are valid");
        facets.push(
            EnginePredictionFacetV2::available(scope.clone(), basis)
                .expect("complete rows form V2 facets"),
        );
        scopes.push(scope);
    }
    if facets.is_empty() {
        return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
    }
    let prediction = EnginePredictionV2::new(provenance.identity().clone(), facets)
        .expect("complete bounded source rows form V2 prediction");
    CheckOutput::from_coverage(Vec::new(), scopes, Vec::new()).with_engine_prediction_v2(prediction)
}

fn evaluate_animation_asset_labels_v2_allocated(
    source: &LoadedSource,
    provenance: &PredictionProvenanceV2,
    allocation: PredictionRuleAllocationV2<'_>,
) -> CheckOutput {
    let facts = source.source_facts();
    let settings_partial = matches!(
        provenance.settings().clip_coverage().state(),
        animsmith_core::ResolvedEngineSettingsCoverageStateV2::Partial
    );
    let raw_partial = facts.clips().coverage().state() != SourceSetCoverageStateV1::Complete;
    let mut scopes = Vec::with_capacity(allocation.candidate_capacity());
    let mut facets = Vec::with_capacity(
        allocation.candidate_capacity() + usize::from(allocation.summary_required()),
    );

    if raw_partial || settings_partial {
        // The incomplete-inventory representation has exactly one candidate.
        // When its capacity is zero, do not construct it only to discard it.
        if allocation.candidate_capacity() != 0 {
            let mut reasons = Vec::new();
            if raw_partial {
                reasons.push(animsmith_core::PredictionUnavailableReasonV2::RawSourceIncomplete);
            }
            if settings_partial {
                reasons
                    .push(animsmith_core::PredictionUnavailableReasonV2::ResolvedSettingsOverflow);
            }
            let basis = EnginePredictionBasisV1::new(vec![
                PredictionBasisReferenceV1::profile_fact("animation_addressability")
                    .expect("static fact"),
                PredictionBasisReferenceV1::primary_source(BEVY_ANIMATION_LABEL_SOURCE)
                    .expect("static source"),
            ])
            .expect("static basis");
            facets.push(
                EnginePredictionFacetV2::required_unavailable(
                    EvaluationScope::new(EvaluationScopeCode::ANIMATION_ASSET_LABEL_INVENTORY),
                    basis,
                    reasons,
                )
                .expect("static unavailable V2 facet"),
            );
        }
    } else {
        // Construct only the catalog-allocated prefix.  In particular, do not
        // form raw-source basis references/facets for omitted candidates.
        for clip in facts
            .clips()
            .rows()
            .iter()
            .take(allocation.candidate_capacity())
        {
            let source_index = clip.source_clip_index();
            let label = BevyAnimationAssetLabelV1::new(source_index)
                .expect("loader-valid retained clip indices satisfy the V1 raw-source bound");
            let scope = EvaluationScope::new(EvaluationScopeCode::ANIMATION_ASSET_LABEL)
                .subject(label.as_str().to_owned());
            let source_name = RawSourceBasisReferenceV1::from_source(
                RawSourceDomainV1::Clip,
                RawSourceKeyV1::Clip {
                    source_clip_index: source_index as u64,
                },
                RawSourceFieldIdV1::new("source_name.state").expect("static field is valid"),
                facts,
            )
            .expect("retained clip rows resolve their raw-source witness");
            let basis = EnginePredictionBasisV1::new(vec![
                PredictionBasisReferenceV1::profile_fact("animation_addressability")
                    .expect("static fact id is valid"),
                PredictionBasisReferenceV1::primary_source(BEVY_ANIMATION_LABEL_SOURCE)
                    .expect("static primary-source id is valid"),
                PredictionBasisReferenceV1::raw_source(source_name),
            ])
            .expect("three static basis references are valid");
            facets.push(
                EnginePredictionFacetV2::available(scope.clone(), basis)
                    .expect("complete rows form V2 facets"),
            );
            scopes.push(scope);
        }
    }

    if allocation.summary_required() {
        let basis = EnginePredictionBasisV1::new(vec![
            PredictionBasisReferenceV1::profile_fact("animation_addressability")
                .expect("static fact"),
            PredictionBasisReferenceV1::primary_source(BEVY_ANIMATION_LABEL_SOURCE)
                .expect("static source"),
        ])
        .expect("static basis");
        facets.push(
            EnginePredictionFacetV2::required_unavailable(
                EvaluationScope::new(EvaluationScopeCode::custom(
                    "engine-addressability:facet-budget",
                )),
                basis,
                vec![animsmith_core::PredictionUnavailableReasonV2::FacetBudgetExceeded],
            )
            .expect("budget summary facet"),
        );
    }
    if facets.is_empty() {
        return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
    }
    CheckOutput::from_coverage(Vec::new(), scopes, Vec::new()).with_engine_prediction_v2(
        EnginePredictionV2::new(provenance.identity().clone(), facets)
            .expect("allocated V2 facets"),
    )
}

fn evaluate_animation_asset_labels_v3(
    source: &LoadedSource,
    provenance: &PredictionProvenanceV3,
) -> CheckOutput {
    let raw_partial =
        source.source_facts().clips().coverage().state() != SourceSetCoverageStateV1::Complete;
    let settings_partial = matches!(
        provenance.settings().clip_coverage().state(),
        animsmith_core::ResolvedEngineSettingsCoverageStateV2::Partial
    );
    let candidate_capacity = if raw_partial || settings_partial {
        1
    } else {
        source.source_facts().clips().rows().len()
    };
    evaluate_animation_asset_labels_v3_with_limits(source, provenance, candidate_capacity, false)
}

fn evaluate_animation_asset_labels_v3_allocated(
    source: &LoadedSource,
    provenance: &PredictionProvenanceV3,
    allocation: PredictionRuleAllocationV2<'_>,
) -> CheckOutput {
    evaluate_animation_asset_labels_v3_with_limits(
        source,
        provenance,
        allocation.candidate_capacity(),
        allocation.summary_required(),
    )
}

fn evaluate_animation_asset_labels_v3_with_limits(
    source: &LoadedSource,
    provenance: &PredictionProvenanceV3,
    candidate_capacity: usize,
    summary_required: bool,
) -> CheckOutput {
    let facts = source.source_facts();
    let settings_partial = matches!(
        provenance.settings().clip_coverage().state(),
        animsmith_core::ResolvedEngineSettingsCoverageStateV2::Partial
    );
    let raw_partial = facts.clips().coverage().state() != SourceSetCoverageStateV1::Complete;
    let mut scopes = Vec::with_capacity(candidate_capacity);
    let mut facets = Vec::with_capacity(candidate_capacity + usize::from(summary_required));

    if raw_partial || settings_partial {
        if candidate_capacity != 0 {
            let mut reasons = Vec::new();
            if raw_partial {
                reasons.push(animsmith_core::PredictionUnavailableReasonV2::RawSourceIncomplete);
            }
            if settings_partial {
                reasons
                    .push(animsmith_core::PredictionUnavailableReasonV2::ResolvedSettingsOverflow);
            }
            facets.push(
                EnginePredictionFacetV3::required_unavailable(
                    EvaluationScope::new(EvaluationScopeCode::ANIMATION_ASSET_LABEL_INVENTORY),
                    addressability_basis_v3(facts, None),
                    reasons,
                )
                .expect("static unavailable V3 facet"),
            );
        }
    } else {
        for clip in facts.clips().rows().iter().take(candidate_capacity) {
            let source_index = clip.source_clip_index();
            let label = BevyAnimationAssetLabelV1::new(source_index)
                .expect("loader-valid retained clip indices satisfy the V1 raw-source bound");
            let scope = EvaluationScope::new(EvaluationScopeCode::ANIMATION_ASSET_LABEL)
                .subject(label.as_str().to_owned());
            facets.push(
                EnginePredictionFacetV3::available(
                    scope.clone(),
                    addressability_basis_v3(facts, Some(source_index)),
                )
                .expect("complete rows form V3 facets"),
            );
            scopes.push(scope);
        }
    }

    if summary_required {
        facets.push(
            EnginePredictionFacetV3::required_unavailable(
                EvaluationScope::new(EvaluationScopeCode::custom(
                    "engine-addressability:facet-budget",
                )),
                addressability_basis_v3(facts, None),
                vec![animsmith_core::PredictionUnavailableReasonV2::FacetBudgetExceeded],
            )
            .expect("budget summary V3 facet"),
        );
    }
    if facets.is_empty() {
        return CheckOutput::from_coverage(Vec::new(), Vec::new(), Vec::new());
    }
    CheckOutput::from_coverage(Vec::new(), scopes, Vec::new()).with_engine_prediction_v3(
        EnginePredictionV3::new(provenance.identity().clone(), facets)
            .expect("allocated V3 facets"),
    )
}

fn addressability_basis_v3(
    facts: animsmith_core::SourceFactsViewV1<'_>,
    source_index: Option<usize>,
) -> EnginePredictionBasisV2 {
    let mut references = vec![
        PredictionBasisReferenceV2::v1(
            PredictionBasisReferenceV1::profile_fact("animation_addressability")
                .expect("static fact id is valid"),
        ),
        PredictionBasisReferenceV2::v1(
            PredictionBasisReferenceV1::primary_source(BEVY_ANIMATION_LABEL_SOURCE)
                .expect("static primary-source id is valid"),
        ),
    ];
    if let Some(source_index) = source_index {
        let source_name = RawSourceBasisReferenceV1::from_source(
            RawSourceDomainV1::Clip,
            RawSourceKeyV1::Clip {
                source_clip_index: source_index as u64,
            },
            RawSourceFieldIdV1::new("source_name.state").expect("static field is valid"),
            facts,
        )
        .expect("retained clip rows resolve their raw-source witness");
        references.push(PredictionBasisReferenceV2::v1(
            PredictionBasisReferenceV1::raw_source(source_name),
        ));
    }
    EnginePredictionBasisV2::new(references).expect("static addressability basis is canonical")
}