rustmotion 0.7.0

A CLI tool that renders motion design videos from JSON scenarios. No browser, no Node.js — just a single Rust binary.
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
use rustmotion::error::{Result, RustmotionError};
use rustmotion::schema::ResolvedScenario;
use std::path::{Path, PathBuf};

use super::geometry::{GeometryViolation, ViolationKind};
use super::validation::{self, ValidationReport, ValidationSource, VarOverrides};

/// #128 item 4: the duration `validate` announces must match what `render`
/// actually produces frame-for-frame. Summing `scene.duration` directly
/// (the old behaviour) over-counts: a transition *overlaps* two adjacent
/// scenes rather than adding sequential time — `encode/video/tasks.rs`'s
/// frame scheduler subtracts each transition's frames from the receiving
/// scene's own budget (`build_slide_view_tasks`'s `incoming_transition_frames`),
/// while a *view*-level transition (`build_frame_tasks`'s `ViewTransition`)
/// is genuinely additive on top of both views' own scenes. Re-deriving that
/// arithmetic here would be a second implementation the frame scheduler
/// doesn't know about and can drift from (that file belongs to a different
/// workstream — read, not edited, here). Instead, reuse the exact frame
/// count `render` itself schedules via `build_frame_tasks` and divide by
/// fps: this is definitionally identical to the rendered duration, not an
/// approximation of it.
fn announced_duration(scenario: &ResolvedScenario) -> f64 {
    let fps = scenario.video.fps as f64;
    if fps <= 0.0 {
        return 0.0;
    }
    rustmotion::encode::build_frame_tasks(scenario).len() as f64 / fps
}

/// Why `--fix` must not write over this input.
///
/// `--fix` serialises `LoadedScenario::raw`, which is the document *after*
/// variable substitution, `for-each`/`use` expansion, and `include` resolution
/// — not the document on disk. For a plain JSON scenario the two coincide and
/// writing back is faithful. For anything templated they do not, and the write
/// silently replaces the source with its own expansion: the `config` block and
/// every `$var` disappear, includes get inlined into the parent, `for-each`/
/// `use` get inlined into their repeated/instantiated output, and an HTML
/// input is replaced by JSON outright.
///
/// One rule covers all four: only write back a source `--fix` can reproduce.
#[derive(Debug, PartialEq, Eq)]
enum FixRefusal {
    HtmlSource,
    Templated,
    UsesInclude,
    UsesTemplateDirectives,
}

impl FixRefusal {
    fn explain(&self, path: &Path) -> String {
        let p = path.display();
        match self {
            Self::HtmlSource => format!(
                "--fix cannot rewrite {p}: it is an HTML source, and the fixer only knows how to \
                 emit JSON — applying it would replace your markup with the transpiled scenario. \
                 Apply the fix to the HTML by hand, or transpile first and fix the JSON."
            ),
            Self::Templated => format!(
                "--fix cannot rewrite {p}: it declares `config` or uses `$variables`, and the \
                 fixer would write back the substituted scenario — dropping the template and \
                 making `--var` a silent no-op. Fix the template by hand."
            ),
            Self::UsesInclude => format!(
                "--fix cannot rewrite {p}: it uses `include`, and the fixer would write back the \
                 resolved tree — inlining the included files into the parent and patching by a \
                 path that no longer means the same node. Fix the included file directly."
            ),
            Self::UsesTemplateDirectives => format!(
                "--fix cannot rewrite {p}: it uses `for-each`/`use` (or declares `components`), \
                 and the fixer would write back the expanded tree — inlining every repeated \
                 instance and patching by a path that no longer means the same source node, \
                 exactly like `include`. Fix the `components` definition or the `for-each` \
                 template directly."
            ),
        }
    }
}

/// `None` when `--fix` may write over `input`.
fn refuse_fix(input: &Path, raw_source: &str) -> Option<FixRefusal> {
    if rustmotion::loader::is_html_path(input) {
        return Some(FixRefusal::HtmlSource);
    }
    // Inspect the bytes on disk, not the loaded tree: by then substitution has
    // already erased the very markers that make the write unfaithful.
    let source: serde_json::Value = match serde_json::from_str(raw_source) {
        Ok(v) => v,
        // Unparseable source is not something we should be overwriting either.
        Err(_) => return Some(FixRefusal::Templated),
    };
    if source.get("config").is_some() || raw_source.contains("$") {
        return Some(FixRefusal::Templated);
    }
    if raw_source.contains("\"include\"") {
        return Some(FixRefusal::UsesInclude);
    }
    // Same conservative, raw-substring detection as `UsesInclude` above (not
    // a full walk of the tree): `components`/`for-each`/`use` can appear at
    // any depth, and `--fix` must refuse before it ever gets far enough to
    // find out whether they're actually reachable.
    if source.get("components").is_some()
        || raw_source.contains("\"for-each\"")
        || raw_source.contains("\"use\"")
    {
        return Some(FixRefusal::UsesTemplateDirectives);
    }
    None
}

pub fn cmd_validate(
    input: &PathBuf,
    report: Option<&Path>,
    fix: bool,
    strict_anim: bool,
    strict_attrs: bool,
    lenient: bool,
    overrides: Option<&VarOverrides>,
) -> Result<()> {
    let loaded = match validation::load_with_vars(ValidationSource::File(input), overrides) {
        Ok(l) => l,
        Err(e) => {
            eprintln!("Error: {}", e);
            std::process::exit(1);
        }
    };

    let mut report_out = validation::run_checks(&loaded, strict_anim);
    if strict_attrs {
        validation::warn_strict_attrs_is_now_default();
        report_out.promote_attr_warnings();
    }

    if let Some(report_path) = report {
        write_report(report_path, &report_out)?;
        eprintln!("Wrote report: {}", report_path.display());
    }

    let mut applied_fixes = 0usize;
    if fix && !report_out.geom_violations.is_empty() {
        let raw_source = std::fs::read_to_string(input).unwrap_or_default();
        if let Some(refusal) = refuse_fix(input, &raw_source) {
            return Err(RustmotionError::Generic(refusal.explain(input)));
        }
        let mut json_value = loaded.raw.clone();
        applied_fixes = apply_fixes(&mut json_value, &report_out.geom_violations);
        if applied_fixes > 0 {
            let pretty = serde_json::to_string_pretty(&json_value)
                .map_err(|e| RustmotionError::Generic(format!("serialize fixes: {}", e)))?;
            std::fs::write(input, pretty).map_err(|e| RustmotionError::FileRead {
                path: input.display().to_string(),
                source: e,
            })?;
            eprintln!(
                "Applied {} auto-fix(es) to {}",
                applied_fixes,
                input.display()
            );

            // Re-run checks after the fixes so the rest of the function reflects
            // the on-disk state.
            let reloaded = validation::load_with_vars(ValidationSource::File(input), overrides)?;
            report_out = validation::run_checks(&reloaded, strict_anim);
            if strict_attrs {
                report_out.promote_attr_warnings();
            }
        }
    }

    let all_scenes: Vec<_> = loaded.scenario.all_scenes().collect();
    let total_duration = announced_duration(&loaded.scenario);

    validation::print_report(&report_out, &input.display().to_string());

    let blocking = !report_out.schema_errors.is_empty()
        || (!report_out.geom_violations.is_empty() && !lenient);
    if blocking {
        if applied_fixes > 0 {
            eprintln!("Some fixes applied — re-run validate to confirm.");
        }
        std::process::exit(1);
    }

    eprintln!(
        "Valid scenario: {} scene(s) in {} view(s)",
        all_scenes.len(),
        loaded.scenario.views.len()
    );
    eprintln!(
        "  Resolution: {}x{} @ {}fps",
        loaded.scenario.video.width, loaded.scenario.video.height, loaded.scenario.video.fps
    );
    eprintln!("  Duration: {:.1}s", total_duration);
    if !report_out.geom_violations.is_empty() {
        eprintln!("  Geometry warnings: {}", report_out.geom_violations.len());
    }
    Ok(())
}

fn write_report(path: &Path, report: &ValidationReport) -> Result<()> {
    let json = serde_json::json!({
        "schema_errors": report.schema_errors,
        "geometry_violations": report.geom_violations,
        "unresolved_vars": report.unresolved_vars,
        "warnings": report.warnings,
        "attr_warnings": report.attr_warnings,
    });
    let pretty = serde_json::to_string_pretty(&json)
        .map_err(|e| RustmotionError::Generic(format!("serialize report: {}", e)))?;
    std::fs::write(path, pretty).map_err(|e| RustmotionError::FileRead {
        path: path.display().to_string(),
        source: e,
    })?;
    Ok(())
}

/// Apply safe auto-fixes directly in the raw JSON. Returns the number of
/// successful mutations.
fn apply_fixes(root: &mut serde_json::Value, violations: &[GeometryViolation]) -> usize {
    let mut applied = 0;
    for v in violations {
        let target = match navigate(root, &v.path) {
            Some(t) => t,
            None => continue,
        };
        match v.kind {
            ViolationKind::UnwrappableTextOverflow => {
                // `wrap` is not a `CssStyle` field — `CssStyle` is
                // `deny_unknown_fields`, so writing it silently drops the
                // whole component at the next parse (C1). The real property
                // is `white-space`; removing `nowrap`/`pre` falls back to
                // the schema default (`normal`, i.e. wrapping), which is
                // always a valid, non-destructive mutation.
                if let Some(style_obj) = target.get_mut("style").and_then(|s| s.as_object_mut()) {
                    if style_obj.remove("white-space").is_some() {
                        applied += 1;
                    }
                }
            }
            ViolationKind::AutoScrollDisabledOverflow => {
                if let Some(obj) = target.as_object_mut() {
                    obj.insert("auto_scroll".into(), serde_json::Value::Bool(true));
                    applied += 1;
                }
            }
            ViolationKind::ContentOverflowsBox => {
                // Growing the box, shrinking the font and shortening the copy
                // are all legitimate answers with very different visual
                // outcomes, so this arm used to do nothing rather than pick
                // one. `style.text-autofit` removed that dilemma for the two
                // components whose painters implement it: it declares the
                // author's intent ("this must fit") without touching the
                // declared box or the content, so nothing the author wrote is
                // overwritten or lost — the same risk category as the two
                // fixes above, both of which also change the render.
                //
                // Scoped to `text`/`gradient_text` deliberately. Every other
                // component ignores the field, so writing it there would be a
                // no-op the author could reasonably read as a fix, which is
                // worse than leaving the violation to them.
                let kind = target.get("type").and_then(|t| t.as_str());
                if matches!(kind, Some("text") | Some("gradient_text")) {
                    if let Some(style) = target
                        .as_object_mut()
                        .and_then(|o| o.get_mut("style"))
                        .and_then(|s| s.as_object_mut())
                    {
                        if !style.contains_key("text-autofit") {
                            style.insert("text-autofit".into(), serde_json::Value::Bool(true));
                            applied += 1;
                        }
                    }
                }
            }
            ViolationKind::ViewportOverflow
            | ViolationKind::AnimatedTextOverflow
            | ViolationKind::ContentOverflowsCard => {
                // Position/size clamping is too risky to auto-fix without
                // losing intent — leave it for the user.
            }
        }
    }
    applied
}

/// Walk a path like `views[0].scenes[1].children[2].children[0]` against the
/// raw JSON, transparently handling the legacy `scenes` and `composition` shapes.
fn navigate<'a>(root: &'a mut serde_json::Value, path: &str) -> Option<&'a mut serde_json::Value> {
    let segments = parse_segments(path);
    let mut cursor: &mut serde_json::Value = root;
    let mut idx = 0;
    while idx < segments.len() {
        let (name, n) = &segments[idx];
        cursor = match name.as_str() {
            "views" => {
                if cursor.get("views").is_some() {
                    cursor.get_mut("views")?.get_mut(*n)?
                } else if cursor.get("composition").is_some() {
                    cursor.get_mut("composition")?.get_mut(*n)?
                } else if *n == 0 {
                    // Implicit single-slide view: stay on root.
                    cursor
                } else {
                    return None;
                }
            }
            "scenes" => cursor.get_mut("scenes")?.get_mut(*n)?,
            "children" => cursor.get_mut("children")?.get_mut(*n)?,
            _ => return None,
        };
        idx += 1;
    }
    Some(cursor)
}

fn parse_segments(path: &str) -> Vec<(String, usize)> {
    let mut out = Vec::new();
    for part in path.split('.') {
        if let Some(open) = part.find('[') {
            let close = part.find(']').unwrap_or(part.len());
            let name = &part[..open];
            if let Ok(n) = part[open + 1..close].parse::<usize>() {
                out.push((name.to_string(), n));
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::super::geometry::{validate_geometry, Axis, BBox};
    use super::*;
    use rustmotion::components::Component;
    use rustmotion::engine::render;
    use rustmotion::loader::load_scenario_from_source;

    const NARROW_CARD_JSON: &str = r##"{
        "video": { "width": 1920, "height": 1080 },
        "scenes": [{
            "duration": 1.0,
            "children": [{
                "type": "card",
                "x": 100, "y": 100,
                "style": { "width": "200px", "height": "200px", "background": "#222244" },
                "children": [{
                    "type": "text",
                    "content": "this string is too long to fit",
                    "style": { "color": "#ffffff", "font-size": "96px", "white-space": "nowrap" }
                }]
            }]
        }]
    }"##;

    fn unwrappable_violation(path: &str) -> GeometryViolation {
        GeometryViolation {
            view_index: 0,
            scene_index: 0,
            path: path.to_string(),
            component: "text".to_string(),
            axis: Axis::X,
            kind: ViolationKind::UnwrappableTextOverflow,
            bbox: BBox {
                x: 0.0,
                y: 0.0,
                w: 200.0,
                h: 40.0,
            },
            viewport: (1920, 1080),
            hint: String::new(),
        }
    }

    fn overflow_box_violation(path: &str) -> GeometryViolation {
        GeometryViolation {
            kind: ViolationKind::ContentOverflowsBox,
            ..unwrappable_violation(path)
        }
    }

    /// `ContentOverflowsBox` had no fix because growing the box, shrinking
    /// the font and shortening the copy are all legitimate and pick
    /// different outcomes. `text-autofit` states the intent instead, without
    /// overwriting anything the author declared.
    #[test]
    fn fix_declares_text_autofit_on_an_overflowing_text() {
        let mut json: serde_json::Value = serde_json::from_str(NARROW_CARD_JSON).unwrap();
        let path = "views[0].scenes[0].children[0].children[0]";
        let applied = apply_fixes(&mut json, &[overflow_box_violation(path)]);
        assert_eq!(applied, 1, "expected exactly one fix applied");

        let target = navigate(&mut json, path).expect("path resolves");
        assert_eq!(
            target.get("style").and_then(|s| s.get("text-autofit")),
            Some(&serde_json::Value::Bool(true))
        );
        // The declared box and the content are what the author wrote; a fix
        // that rewrote either would be picking one of the outcomes this arm
        // exists to avoid picking.
        assert!(
            target.get("content").is_some(),
            "content must be untouched: {target}"
        );
    }

    /// Every component other than `text`/`gradient_text` ignores the field.
    /// Writing it there would look like a fix while changing nothing, which
    /// is worse than leaving the violation visible.
    #[test]
    fn fix_leaves_overflowing_components_that_cannot_autofit_alone() {
        let json_src = r##"{
            "video": { "width": 1920, "height": 1080 },
            "scenes": [{ "duration": 1.0, "children": [
                { "type": "table", "headers": ["a"], "rows": [["b"]],
                  "style": { "width": "40px", "font-size": 40 } }
            ]}]
        }"##;
        let mut json: serde_json::Value = serde_json::from_str(json_src).unwrap();
        let path = "views[0].scenes[0].children[0]";
        assert_eq!(
            apply_fixes(&mut json, &[overflow_box_violation(path)]),
            0,
            "a table cannot autofit, so nothing should be claimed as fixed"
        );
        let target = navigate(&mut json, path).expect("path resolves");
        assert!(
            target
                .get("style")
                .and_then(|s| s.get("text-autofit"))
                .is_none(),
            "must not write a field this painter ignores: {target}"
        );
    }

    /// C1: `apply_fixes` must never write `style.wrap` (not a `CssStyle`
    /// field — writing it drops the whole component at the next parse
    /// because `CssStyle` is `deny_unknown_fields`). It must instead remove
    /// `white-space: nowrap`, and the fixed file must still parse with the
    /// text component intact.
    #[test]
    fn fix_removes_white_space_and_never_writes_the_nonexistent_wrap_field() {
        let mut json: serde_json::Value = serde_json::from_str(NARROW_CARD_JSON).unwrap();
        let violations = vec![unwrappable_violation(
            "views[0].scenes[0].children[0].children[0]",
        )];
        let applied = apply_fixes(&mut json, &violations);
        assert_eq!(applied, 1);

        let style = &json["scenes"][0]["children"][0]["children"][0]["style"];
        assert!(
            style.get("wrap").is_none(),
            "must never write the nonexistent CssStyle::wrap field: {}",
            style
        );
        assert!(
            style.get("white-space").is_none(),
            "white-space: nowrap must be removed, not left in place: {}",
            style
        );

        // The fixed file must still parse, and the text must still be
        // present — a `deny_unknown_fields` rejection would have silently
        // dropped it (C1's original failure mode).
        let pretty = serde_json::to_string(&json).unwrap();
        let scenario =
            load_scenario_from_source(None, Some(&pretty)).expect("fixed scenario still parses");
        let top_children = render::deserialize_children(&scenario.views[0].scenes[0]);
        assert_eq!(top_children.len(), 1, "card must survive the fix");
        let text_survived = match &top_children[0].component {
            Component::Card(c) => c.children.len() == 1,
            _ => false,
        };
        assert!(
            text_survived,
            "text child must survive the fix, not be dropped"
        );

        // The fix must also clear the geometry violation it targeted.
        let after = validate_geometry(&scenario);
        assert!(
            after
                .iter()
                .all(|v| v.kind != ViolationKind::UnwrappableTextOverflow),
            "fix must clear the violation: {:?}",
            after
        );
    }

    /// H3: the violation path (produced by geometry.rs's raw-index-preserving
    /// walker) must reference the RAW JSON position of the offending node,
    /// so `navigate()`/`apply_fixes` mutate the right sibling even when an
    /// earlier child never became a `ChildComponent`.
    #[test]
    fn fix_patches_the_raw_json_sibling_even_when_an_earlier_child_failed_to_deserialize() {
        let raw = r##"{
            "video": { "width": 1920, "height": 1080 },
            "scenes": [{
                "duration": 1.0,
                "children": [
                    { "type": "not_a_real_component_kind" },
                    {
                        "type": "card",
                        "x": 100, "y": 100,
                        "style": { "width": "200px", "height": "200px", "background": "#222244" },
                        "children": [{
                            "type": "text",
                            "content": "this string is too long to fit",
                            "style": { "color": "#ffffff", "font-size": "96px", "white-space": "nowrap" }
                        }]
                    }
                ]
            }]
        }"##;
        let mut json: serde_json::Value = serde_json::from_str(raw).unwrap();
        let violations = vec![unwrappable_violation(
            "views[0].scenes[0].children[1].children[0]",
        )];
        let applied = apply_fixes(&mut json, &violations);
        assert_eq!(applied, 1);

        // children[0] (the broken sibling) must be untouched.
        assert_eq!(
            json["scenes"][0]["children"][0]["type"],
            "not_a_real_component_kind"
        );
        // children[1] (the card) is the one that got fixed.
        let style = &json["scenes"][0]["children"][1]["children"][0]["style"];
        assert!(style.get("white-space").is_none());
        assert!(style.get("wrap").is_none());
    }

    #[test]
    fn navigate_resolves_implicit_single_slide_view_at_index_zero() {
        let mut json: serde_json::Value = serde_json::from_str(NARROW_CARD_JSON).unwrap();
        let target = navigate(&mut json, "views[0].scenes[0].children[0].children[0]");
        assert!(target.is_some(), "must resolve into the implicit view 0");
        assert_eq!(target.unwrap()["type"], "text");
    }

    // ─── #128 item 4: announced duration matches the rendered one ────────────

    #[test]
    fn announced_duration_subtracts_the_overlapping_transition_instead_of_summing_scene_durations()
    {
        // Two 2.0s scenes at 30fps with a 0.5s transition entering the
        // second one: naively summing `scene.duration` gives 4.0s (the old,
        // wrong behaviour — reproduces #128 item 4's "22% wrong" report).
        // The transition *overlaps* the two scenes rather than adding
        // sequential time: scene 0 contributes 60 frames minus the 15 frames
        // it hands off to the transition (45), the transition itself
        // contributes 15, and scene 1 contributes 60 minus the 15 incoming
        // frames it doesn't repeat (45) — 45 + 15 + 45 = 105 frames = 3.5s.
        let json = r##"{
            "video": { "width": 640, "height": 360, "fps": 30 },
            "scenes": [
                { "duration": 2.0, "children": [] },
                {
                    "duration": 2.0,
                    "transition": { "type": "fade", "duration": 0.5 },
                    "children": []
                }
            ]
        }"##;
        let scenario = load_scenario_from_source(None, Some(json)).expect("scenario parses");

        let naive_sum: f64 = scenario.all_scenes().map(|s| s.duration).sum();
        assert_eq!(
            naive_sum, 4.0,
            "sanity check: naive summing must reproduce the old 4.0s (over-)estimate"
        );

        let duration = announced_duration(&scenario);
        assert!(
            (duration - 3.5).abs() < 1e-9,
            "expected the transition-overlap-corrected 3.5s, got {duration}"
        );

        // The value must be definitionally the rendered frame count, not a
        // hand-derived approximation of it.
        let expected_from_frame_count =
            rustmotion::encode::build_frame_tasks(&scenario).len() as f64 / 30.0;
        assert_eq!(duration, expected_from_frame_count);
    }

    #[test]
    fn announced_duration_matches_scene_duration_sum_when_there_are_no_transitions() {
        // No transitions at all: the corrected formula must degrade back to
        // exactly the naive sum — this is a regression guard, not a special
        // case the fix is allowed to get wrong.
        let json = r##"{
            "video": { "width": 640, "height": 360, "fps": 30 },
            "scenes": [
                { "duration": 1.0, "children": [] },
                { "duration": 2.0, "children": [] }
            ]
        }"##;
        let scenario = load_scenario_from_source(None, Some(json)).expect("scenario parses");
        let duration = announced_duration(&scenario);
        assert!(
            (duration - 3.0).abs() < 1e-6,
            "expected 3.0s with no transitions, got {duration}"
        );
    }

    /// `--fix` writes back the *resolved* tree. Anything the resolution erased is
    /// erased on disk too, so these inputs must be refused rather than
    /// silently rewritten.
    mod fix_refusals {
        use super::super::{refuse_fix, FixRefusal};
        use std::path::Path;

        const PLAIN: &str = r#"{"video":{"width":320,"height":240,"fps":30},
            "scenes":[{"duration":1.0,"children":[]}]}"#;

        #[test]
        fn a_plain_json_scenario_is_writable() {
            assert_eq!(refuse_fix(Path::new("s.json"), PLAIN), None);
        }

        #[test]
        fn an_html_source_is_refused() {
            // Writing here replaces the author's markup with transpiled JSON.
            assert_eq!(
                refuse_fix(Path::new("s.html"), "<rustmotion></rustmotion>"),
                Some(FixRefusal::HtmlSource)
            );
        }

        #[test]
        fn a_templated_scenario_is_refused() {
            // The write would bake in the substitution and make --var a no-op.
            let with_config = r#"{"config":{"title":"hi"},"video":{"width":320,"height":240,
                "fps":30},"scenes":[{"duration":1.0,"children":[]}]}"#;
            assert_eq!(
                refuse_fix(Path::new("s.json"), with_config),
                Some(FixRefusal::Templated)
            );

            let with_var = r#"{"video":{"width":320,"height":240,"fps":30},
                "scenes":[{"duration":1.0,"children":[
                {"type":"text","content":"$title"}]}]}"#;
            assert_eq!(
                refuse_fix(Path::new("s.json"), with_var),
                Some(FixRefusal::Templated)
            );
        }

        #[test]
        fn a_scenario_using_include_is_refused() {
            // The resolved tree inlines the include, so a path-based patch lands on
            // a node the source file does not contain.
            let with_include = r#"{"video":{"width":320,"height":240,"fps":30},
                "scenes":[{"include":"part.json"}]}"#;
            assert_eq!(
                refuse_fix(Path::new("s.json"), with_include),
                Some(FixRefusal::UsesInclude)
            );
        }

        #[test]
        fn a_scenario_using_for_each_is_refused() {
            // No `$` anywhere in this fixture on purpose — proves the
            // detection is driven by the `for-each` marker itself, not by
            // piggybacking on the pre-existing `$`-content check.
            let with_for_each = r##"{"video":{"width":320,"height":240,"fps":30},
                "scenes":[{"duration":1.0,"children":[
                {"for-each":[1,2],"template":{"type":"text","content":"static"}}
                ]}]}"##;
            assert_eq!(
                refuse_fix(Path::new("s.json"), with_for_each),
                Some(FixRefusal::UsesTemplateDirectives)
            );
        }

        #[test]
        fn a_scenario_declaring_components_is_refused_even_with_no_use_site_yet() {
            let with_components = r##"{"video":{"width":320,"height":240,"fps":30},
                "components":{"card":{"params":{},"template":{"type":"text","content":"hi"}}},
                "scenes":[{"duration":1.0,"children":[]}]}"##;
            assert_eq!(
                refuse_fix(Path::new("s.json"), with_components),
                Some(FixRefusal::UsesTemplateDirectives)
            );
        }

        #[test]
        fn every_refusal_names_the_file_and_says_what_to_do_instead() {
            let p = Path::new("scenes/hero.json");
            for r in [
                FixRefusal::HtmlSource,
                FixRefusal::Templated,
                FixRefusal::UsesInclude,
                FixRefusal::UsesTemplateDirectives,
            ] {
                let msg = r.explain(p);
                assert!(msg.contains("scenes/hero.json"), "{msg}");
                assert!(msg.contains("by hand") || msg.contains("directly"), "{msg}");
            }
        }
    }

    /// Round 4 audit, constat 1: PR #145 introduced `refuse_fix`, gated on
    /// the raw bytes on disk (not `loaded.raw`), and `apply_fixes`/`navigate`
    /// already walk raw-preserving indices (H3, see
    /// `geometry.rs::deserialize_children_indexed`'s doc comment). This
    /// workstream's job is not to redo that fix — it's to prove, end to
    /// end through `cmd_validate` (not just unit-testing `refuse_fix` in
    /// isolation, as `fix_refusals` above does), that the refusal actually
    /// engages for the two concrete failure modes constat 1 names:
    /// - validate.rs:60 — `--fix` would otherwise serialise the
    ///   *post-substitution* document, dropping `config` and baking in
    ///   `$var` resolutions, silently destroying the template.
    /// - validate.rs:198 — a violation path carries the *resolved* scene
    ///   index (post `include::resolve_entries` inlining), which does not
    ///   line up with the RAW `scenes` array `navigate` walks as soon as an
    ///   `include` expands to a scene count that shifts later positions.
    ///
    /// Both are already covered by the existing `refuse_fix` gate (a
    /// `Templated`/`UsesInclude` scenario is refused outright, before
    /// `apply_fixes` ever runs) — these two tests are the proof, not a new
    /// fix. No RED phase: this constat is "verify existing behaviour", not
    /// "here is a bug"; both tests pass on first run.
    mod fix_refusals_end_to_end {
        use super::super::cmd_validate;

        #[test]
        fn cmd_validate_fix_refuses_to_overwrite_a_templated_scenario_and_leaves_the_file_untouched(
        ) {
            let path = std::env::temp_dir().join(format!(
                "rm_validate_fix_templated_{}.json",
                std::process::id()
            ));
            // `config` + a whole-string `$title` reference, plus a real
            // geometry violation (nowrap text far too wide for its card) so
            // `--fix` actually attempts to write.
            let original = r##"{
                "config": { "title": { "type": "string", "default": "hi" } },
                "video": { "width": 1920, "height": 1080 },
                "scenes": [{
                    "duration": 1.0,
                    "children": [{
                        "type": "card",
                        "x": 100, "y": 100,
                        "style": { "width": "200px", "height": "200px", "background": "#222244" },
                        "children": [{
                            "type": "text",
                            "content": "$title but also this string is too long to fit",
                            "style": { "color": "#ffffff", "font-size": "96px", "white-space": "nowrap" }
                        }]
                    }]
                }]
            }"##;
            std::fs::write(&path, original).expect("write fixture");

            let result = cmd_validate(&path, None, /*fix=*/ true, false, false, false, None);

            let after = std::fs::read_to_string(&path).expect("read back fixture");
            std::fs::remove_file(&path).ok();

            assert!(
                result.is_err(),
                "--fix on a templated scenario with a real violation must be refused, \
                 not silently applied"
            );
            assert_eq!(
                after, original,
                "the file must be byte-identical after a refused --fix — writing \
                 loaded.raw here would have dropped `config` and baked in the \
                 substituted $title"
            );
        }

        #[test]
        fn cmd_validate_fix_refuses_to_overwrite_a_scenario_using_include_and_leaves_files_untouched(
        ) {
            let dir = std::env::temp_dir()
                .join(format!("rm_validate_fix_include_{}", std::process::id()));
            std::fs::create_dir_all(&dir).expect("mkdir");
            let part_path = dir.join("part.json");
            let parent_path = dir.join("parent.json");

            // The included file resolves to TWO scenes; the offending
            // narrow-card/nowrap-text violation lives in the SECOND one, so
            // its *resolved* scene index (1) does not correspond to any
            // scene in the parent's own RAW `scenes` array (which has a
            // single entry: the include directive) — the concrete index
            // skew constat 1 names.
            let part = r##"{
                "video": { "width": 1920, "height": 1080 },
                "scenes": [
                    { "duration": 1.0, "children": [] },
                    {
                        "duration": 1.0,
                        "children": [{
                            "type": "card",
                            "x": 100, "y": 100,
                            "style": { "width": "200px", "height": "200px", "background": "#222244" },
                            "children": [{
                                "type": "text",
                                "content": "this string is too long to fit",
                                "style": { "color": "#ffffff", "font-size": "96px", "white-space": "nowrap" }
                            }]
                        }]
                    }
                ]
            }"##;
            let parent = r##"{
                "video": { "width": 1920, "height": 1080 },
                "scenes": [{ "include": "part.json" }]
            }"##;
            std::fs::write(&part_path, part).expect("write part fixture");
            std::fs::write(&parent_path, parent).expect("write parent fixture");

            let result = cmd_validate(
                &parent_path,
                None,
                /*fix=*/ true,
                false,
                false,
                false,
                None,
            );

            let parent_after = std::fs::read_to_string(&parent_path).expect("read back parent");
            let part_after = std::fs::read_to_string(&part_path).expect("read back part");
            std::fs::remove_dir_all(&dir).ok();

            assert!(
                result.is_err(),
                "--fix on an include-using scenario with a real violation must be refused"
            );
            assert_eq!(
                parent_after, parent,
                "parent file must be byte-identical after a refused --fix"
            );
            assert_eq!(part_after, part, "included file must be untouched too");
        }

        /// Same failure mode as `include`, for the sibling mechanism: `for-each`
        /// expanding to more than one node shifts every later `children[N]`
        /// index, so a path-based `--fix` patch would land on the wrong
        /// (or a nonexistent) sibling if it were allowed to write back the
        /// expanded tree. It must be refused outright instead.
        #[test]
        fn cmd_validate_fix_refuses_to_overwrite_a_scenario_using_for_each_and_leaves_the_file_untouched(
        ) {
            let path = std::env::temp_dir().join(format!(
                "rm_validate_fix_for_each_{}.json",
                std::process::id()
            ));
            let original = r##"{
                "video": { "width": 1920, "height": 1080 },
                "scenes": [{
                    "duration": 1.0,
                    "children": [{
                        "for-each": [
                            { "label": "short" },
                            { "label": "this string is too long to fit in its card" }
                        ],
                        "template": {
                            "type": "card",
                            "x": 100, "y": 100,
                            "style": { "width": "200px", "height": "200px", "background": "#222244" },
                            "children": [{
                                "type": "text",
                                "content": "$label",
                                "style": { "color": "#ffffff", "font-size": "96px", "white-space": "nowrap" }
                            }]
                        }
                    }]
                }]
            }"##;
            std::fs::write(&path, original).expect("write fixture");

            let result = cmd_validate(&path, None, /*fix=*/ true, false, false, false, None);

            let after = std::fs::read_to_string(&path).expect("read back fixture");
            std::fs::remove_file(&path).ok();

            assert!(
                result.is_err(),
                "--fix on a for-each-using scenario with a real violation must be refused"
            );
            assert_eq!(
                after, original,
                "the file must be byte-identical after a refused --fix — the two `for-each` \
                 iterations expand into two card siblings, so a path-based patch would not even \
                 land on the right one"
            );
        }
    }
}