kshana 0.29.1

Open, reproducible PNT-resilience simulator with quantum-sensor performance models
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
// SPDX-License-Identifier: AGPL-3.0-only
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::{SystemTime, UNIX_EPOCH};

mod bundled_scenarios;

/// The one usage text. Both the no-argument path and `--help` print this, so the two
/// cannot drift apart (they were two separate copies before, one of them a comment).
/// `.github/workflows/release.yml` greps the first line on the no-argument path, so
/// that line stays verbatim.
const USAGE: &str = "usage: kshana <scenario.toml> [--study-name <s>] [--eop <finals2000A>] [--export-sp3 <out.sp3>] [--export-omm <out.omm>] [--export-oem <out.oem>] [--export <czml|kml|geojson|stk|sigmf|all|list>]... [--import-route <route.geojson>]
   or: kshana <scenario.toml> --animate <svg|html|frames|all> [--animate-fps <n>] [--animate-duration <s>]
   or: kshana --study <suite.toml>
   or: kshana --validate <scenario.toml>
   or: kshana kinds [--json]
   or: kshana example [<name>]
   or: kshana --help | --version";

/// Format the current system time as a UTC ISO-8601 second-precision stamp
/// (e.g. `2026-06-23T14:05:09Z`). This is the ONLY clock read in the whole crate:
/// the library/engine/api stay pure and deterministic, and the timestamp is passed
/// in to them as data. Implemented with `std` only (no chrono) via a civil-date
/// conversion of the Unix epoch seconds.
fn utc_iso8601_now() -> String {
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let days = (secs / 86_400) as i64;
    let tod = secs % 86_400;
    let (hour, min, sec) = (tod / 3600, (tod % 3600) / 60, tod % 60);
    let (year, month, day) = civil_from_days(days);
    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}Z")
}

/// Convert days since the Unix epoch (1970-01-01) to a proleptic-Gregorian
/// (year, month, day). Howard Hinnant's well-known `civil_from_days` algorithm.
fn civil_from_days(z: i64) -> (i64, u32, u32) {
    let z = z + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = (z - era * 146_097) as u64; // [0, 146096]
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
    let mp = (5 * doy + 2) / 153; // [0, 11]
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32; // [1, 31]
    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; // [1, 12]
    (if m <= 2 { y + 1 } else { y }, m, d)
}

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().collect();
    // `kshana kinds [--json]` is a terminal subcommand, resolved before the flag loop
    // because that loop's positional arm would otherwise read `kinds` as a scenario
    // path. The engine's unknown-kind error tells the user "`kshana kinds` lists all N
    // built-in kinds", so the CLI has to be able to answer it. The cost is that a file
    // literally named `kinds` can no longer be run by that bare name; `./kinds` can.
    if args.get(1).map(String::as_str) == Some("kinds") {
        return print_kinds(&args[2..]);
    }
    // `kshana example [<name>]` is terminal for the same reason: a registry install has
    // no scenarios/ directory, so this is how its user gets a scenario to run.
    if args.get(1).map(String::as_str) == Some("example") {
        return print_example(&args[2..]);
    }
    let mut positional: Option<String> = None;
    let mut export_sp3_path: Option<PathBuf> = None;
    let mut export_omm_path: Option<PathBuf> = None;
    let mut export_oem_path: Option<PathBuf> = None;
    let mut eop_path: Option<PathBuf> = None;
    // `--export <fmt>` may be given more than once; `all` asks for every format that
    // applies and `list` only reports which apply.
    let mut exports: Vec<String> = Vec::new();
    let mut route_path: Option<PathBuf> = None;
    let mut study_name: Option<String> = None;
    let mut study_suite_path: Option<PathBuf> = None;
    let mut validate_path: Option<PathBuf> = None;
    let mut animate_formats: Vec<kshana::animation::AnimationFormat> = Vec::new();
    let mut animate_opts = kshana::animation::AnimationOptions::default();
    let mut animate_tuned = false;
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            // Help and version are the first two things typed at a newly installed
            // binary. Before these arms they fell through to the positional catch-all
            // and came back as `error: cannot read --help: No such file or directory`.
            "--help" | "-h" | "help" => {
                println!("{USAGE}");
                return ExitCode::SUCCESS;
            }
            // `--version` is how a result file gets tied back to the engine build that
            // wrote it: not every result JSON carries an engine_version of its own.
            "--version" | "-V" => {
                println!("kshana {}", env!("CARGO_PKG_VERSION"));
                return ExitCode::SUCCESS;
            }
            "--validate" => {
                i += 1;
                match args.get(i) {
                    Some(p) => validate_path = Some(PathBuf::from(p)),
                    None => {
                        eprintln!("error: --validate needs a scenario path");
                        return ExitCode::from(2);
                    }
                }
            }
            "--study" => {
                i += 1;
                match args.get(i) {
                    Some(p) => study_suite_path = Some(PathBuf::from(p)),
                    None => {
                        eprintln!("error: --study needs a suite manifest path");
                        return ExitCode::from(2);
                    }
                }
            }
            "--study-name" => {
                i += 1;
                match args.get(i) {
                    Some(s) => study_name = Some(s.to_string()),
                    None => {
                        eprintln!("error: --study-name needs a value");
                        return ExitCode::from(2);
                    }
                }
            }
            "--export-sp3" => {
                i += 1;
                match args.get(i) {
                    Some(p) => export_sp3_path = Some(PathBuf::from(p)),
                    None => {
                        eprintln!("error: --export-sp3 needs a path");
                        return ExitCode::from(2);
                    }
                }
            }
            "--export-omm" => {
                i += 1;
                match args.get(i) {
                    Some(p) => export_omm_path = Some(PathBuf::from(p)),
                    None => {
                        eprintln!("error: --export-omm needs a path");
                        return ExitCode::from(2);
                    }
                }
            }
            "--export-oem" => {
                i += 1;
                match args.get(i) {
                    Some(p) => export_oem_path = Some(PathBuf::from(p)),
                    None => {
                        eprintln!("error: --export-oem needs a path");
                        return ExitCode::from(2);
                    }
                }
            }
            // `--animate <svg|html|frames|all>`: also export the run's time series as an
            // animation. Repeatable, and a comma list works (`--animate svg,html`).
            "--animate" => {
                i += 1;
                let Some(v) = args.get(i) else {
                    eprintln!("error: --animate needs a format: svg, html, frames or all");
                    return ExitCode::from(2);
                };
                match kshana::animation::AnimationFormat::parse_list(v) {
                    Ok(list) => {
                        for f in list {
                            if !animate_formats.contains(&f) {
                                animate_formats.push(f);
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("error: --animate: {e}");
                        return ExitCode::from(2);
                    }
                }
            }
            "--animate-fps" => {
                i += 1;
                match args.get(i).and_then(|v| v.parse::<u32>().ok()) {
                    Some(n) => {
                        animate_opts.fps = n;
                        animate_tuned = true;
                    }
                    None => {
                        eprintln!("error: --animate-fps needs a whole number of frames per second");
                        return ExitCode::from(2);
                    }
                }
            }
            "--export" => {
                i += 1;
                match args.get(i) {
                    Some(f) => exports.push(f.to_string()),
                    None => {
                        eprintln!(
                            "error: --export needs a format: czml, kml, geojson, stk, sigmf, all or list"
                        );
                        return ExitCode::from(2);
                    }
                }
            }
            "--animate-duration" => {
                i += 1;
                match args.get(i).and_then(|v| v.parse::<f64>().ok()) {
                    Some(d) => {
                        animate_opts.duration_s = d;
                        animate_tuned = true;
                    }
                    None => {
                        eprintln!("error: --animate-duration needs a length in seconds");
                        return ExitCode::from(2);
                    }
                }
            }
            "--import-route" => {
                i += 1;
                match args.get(i) {
                    Some(p) => route_path = Some(PathBuf::from(p)),
                    None => {
                        eprintln!("error: --import-route needs a GeoJSON file path");
                        return ExitCode::from(2);
                    }
                }
            }
            "--eop" => {
                i += 1;
                match args.get(i) {
                    Some(p) => eop_path = Some(PathBuf::from(p)),
                    None => {
                        eprintln!("error: --eop needs a finals2000A file path");
                        return ExitCode::from(2);
                    }
                }
            }
            // A token starting with '-' that matched no arm above is a misspelled or
            // unsupported option, not a scenario path. Without this arm it became the
            // positional and the NEXT token was blamed, so `--exprot-sp3 out.sp3 s.toml`
            // reported "unexpected argument 'out.sp3'" and pointed away from the typo.
            // Flag VALUES never reach here: each flag arm consumes its own value.
            other if other.starts_with('-') => {
                eprintln!("error: unknown option '{other}'");
                eprintln!("{USAGE}");
                return ExitCode::from(2);
            }
            other if positional.is_none() => positional = Some(other.to_string()),
            other => {
                eprintln!("error: unexpected argument '{other}'; one scenario file per run");
                eprintln!("{USAGE}");
                return ExitCode::from(2);
            }
        }
        i += 1;
    }
    // The animation options are checked before anything runs, so a bad `--animate-fps`
    // costs nothing. Tuning them without `--animate` would do nothing; say so.
    if !animate_formats.is_empty() {
        if let Err(e) = animate_opts.validate() {
            eprintln!("error: {e}");
            return ExitCode::from(2);
        }
    } else if animate_tuned {
        eprintln!("warning: --animate-fps and --animate-duration do nothing without --animate");
    }
    if !animate_formats.is_empty() && (validate_path.is_some() || study_suite_path.is_some()) {
        eprintln!("error: --animate exports one scenario run; it does not combine with --validate or --study");
        return ExitCode::from(2);
    }

    // `--validate <scenario.toml>`: lint a scenario against the crate's own
    // introspection (kind + required fields) and report problems WITHOUT running it,
    // so a user catches a misconfigured scenario before a (possibly long) run. This
    // flag is terminal: each violation is printed to stderr and the process exits 1
    // when there are any, 0 when the scenario lints clean.
    if let Some(validate_file) = validate_path {
        if positional.is_some() {
            eprintln!("error: --validate lints one scenario; do not also pass a scenario file");
            return ExitCode::from(2);
        }
        let src = match std::fs::read_to_string(&validate_file) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("error: cannot read {}: {e}", validate_file.display());
                return ExitCode::FAILURE;
            }
        };
        let violations = kshana::api::validate_scenario(&src);
        if violations.is_empty() {
            // Name what passed AND what was never looked at. The lint resolves the kind
            // and checks that the kind's published required top-level fields are
            // present; it does not check any field's VALUE, so `time.step_s = -10` lints
            // clean here and then fails the run. Silence was the only success signal
            // before, which reads as a full check.
            let kind = kshana::api::ScenarioKind::classify(&src)
                .map(|k| k.as_str())
                .unwrap_or("scenario");
            // For about two thirds of the catalogue the kind publishes NO required field:
            // the pack runs its reference configuration from an empty body. "ok" is true
            // there too, but it must not read as though fields were checked when there were
            // none to check — say which of the two the caller got.
            let n_required = kshana::api::list_scenario_kinds()
                .into_iter()
                .find(|m| m.name == kind)
                .map(|m| m.required_fields.len())
                .unwrap_or(0);
            if n_required == 0 {
                println!(
                    "ok: {kind} — kind resolves; this kind requires no field (an empty body runs its reference configuration), so there was nothing further to check"
                );
            } else {
                println!(
                    "ok: {kind} — kind resolves and all {n_required} of its published required-field entries are satisfied; field values are not checked"
                );
            }
            return ExitCode::SUCCESS;
        }
        for v in &violations {
            eprintln!("{v}");
        }
        return ExitCode::FAILURE;
    }

    // `--study <suite.toml>`: run a named SET of scenarios together into one
    // aggregated, comparable artifact. The manifest is parsed, each scenario is
    // resolved against the manifest's parent directory and run through the same
    // engine the single-scenario path uses, and a `<suite_stem>.study.json` +
    // `<suite_stem>.study.html` pair is written. The library aggregation is pure;
    // only here (the CLI) may a generation timestamp be stamped onto the artifact.
    if let Some(suite_path) = study_suite_path {
        if positional.is_some() {
            eprintln!("error: --study runs a suite; do not also pass a single scenario file");
            return ExitCode::from(2);
        }
        // `--study-name` is a single-scenario flag: it slugs the output name and stamps
        // StudyMeta into the result JSON. A study takes its title from the manifest's
        // `title =` instead, and run_study never reads this variable. Say the flag was
        // dropped rather than dropping it in silence.
        if study_name.is_some() {
            eprintln!(
                "warning: --study-name is ignored with --study; a study is titled by the suite manifest's `title =`"
            );
        }
        return run_study(&suite_path);
    }

    let Some(scenario_arg) = positional else {
        eprintln!("{USAGE}");
        return ExitCode::from(2);
    };
    let path = PathBuf::from(&scenario_arg);
    let mut src = match std::fs::read_to_string(&path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: cannot read {}: {e}", path.display());
            // A registry install has no scenarios/ directory; say where one comes from.
            if e.kind() == std::io::ErrorKind::NotFound {
                eprintln!(
                    "hint: `kshana example` lists the bundled reference scenarios; \
                     `kshana example clock-holdover > clock-holdover.toml` writes one"
                );
            }
            return ExitCode::FAILURE;
        }
    };

    // The scenario file's exact bytes, before any `--eop` injection: the report's
    // reproducibility record digests these, because they are what a reader re-runs.
    let scenario_src = src.clone();
    let mut report_extra_args: Vec<String> = Vec::new();
    let mut report_input_files: Vec<(String, String)> = Vec::new();

    // `--eop <finals2000A>`: inline a real IERS Earth-orientation file into the
    // scenario so the ephemeris ground track is reduced through real UT1/pole rather
    // than the nominal scalars. The data travels in the scenario, keeping the run
    // reproducible from the (now self-contained) TOML alone.
    if let Some(eop_file) = &eop_path {
        let body = match std::fs::read_to_string(eop_file) {
            Ok(b) => b,
            Err(e) => {
                eprintln!("error: cannot read {}: {e}", eop_file.display());
                return ExitCode::FAILURE;
            }
        };
        let eop_arg = eop_file.display().to_string();
        report_extra_args.push("--eop".to_string());
        report_extra_args.push(eop_arg.clone());
        report_input_files.push((
            eop_arg,
            kshana::advanced_report::sha256_hex(body.as_bytes()),
        ));
        match kshana::api::inject_eop(&src, &body) {
            Ok(merged) => src = merged,
            Err(e) => {
                eprintln!("error: --eop: {e}");
                return ExitCode::FAILURE;
            }
        }
    }
    // `--import-route <route.geojson>`: write a GeoJSON LineString into the scenario's
    // straight-track inputs before the run, so the run and every export use it.
    if let Some(route_file) = &route_path {
        let body = match std::fs::read_to_string(route_file) {
            Ok(b) => b,
            Err(e) => {
                eprintln!("error: cannot read {}: {e}", route_file.display());
                return ExitCode::FAILURE;
            }
        };
        match kshana::interop::geojson::apply_route(&src, &body) {
            Ok(merged) => src = merged,
            Err(e) => {
                eprintln!("error: --import-route: {e}");
                return ExitCode::FAILURE;
            }
        }
    }

    // Resolve the `--export` requests before the run, so a misspelt format fails fast.
    let mut export_all = false;
    let mut export_formats: Vec<kshana::interop::Format> = Vec::new();
    for f in &exports {
        match f.to_ascii_lowercase().as_str() {
            "all" => export_all = true,
            "list" => {
                // Terminal: report which formats apply and why the others do not.
                for (fmt, r) in kshana::interop::plan(&src) {
                    match r {
                        Ok(()) => println!("{}: applies", fmt.as_str()),
                        Err(why) => println!("{}: does not apply: {why}", fmt.as_str()),
                    }
                }
                return ExitCode::SUCCESS;
            }
            other => match kshana::interop::Format::parse(other) {
                Ok(fmt) => {
                    if !export_formats.contains(&fmt) {
                        export_formats.push(fmt)
                    }
                }
                Err(e) => {
                    eprintln!("error: --export: {e}");
                    return ExitCode::from(2);
                }
            },
        }
    }

    let mut out = match kshana::api::run_toml(&src) {
        Ok(o) => o,
        Err(e) => {
            eprintln!("error: {e}");
            return ExitCode::FAILURE;
        }
    };

    // `--study-name <s>`: stamp additive study metadata (title + a UTC generation
    // time, the only clock read in the crate) into the result JSON, and name the
    // output files after a slug of the study instead of the scenario path stem. With
    // no `--study-name`, nothing below runs and the output stays byte-identical.
    let output_base: PathBuf = match &study_name {
        Some(name) => {
            report_extra_args.push("--study-name".to_string());
            report_extra_args.push(name.clone());
            let meta = kshana::report::study_meta_with_title(name, &utc_iso8601_now());
            out.json = kshana::api::with_study_meta(&out.json, &meta);
            // Write the study-named outputs in the scenario file's directory.
            let dir = path.parent().unwrap_or_else(|| std::path::Path::new("."));
            dir.join(kshana::report::slugify(name))
        }
        None => path.clone(),
    };

    // `--animate`: render every requested format from the run's own result before
    // anything is written, so a kind with no time series fails without leaving a
    // half-written set of outputs. The result JSON then gains an `animation` block
    // naming what was drawn; without `--animate` it stays byte-identical.
    let mut animations: Vec<(PathBuf, kshana::animation::Animation)> = Vec::new();
    if !animate_formats.is_empty() {
        let kind = kshana::api::ScenarioKind::classify(&src)
            .map(|k| k.as_str().to_string())
            .ok();
        let mut written: Vec<String> = Vec::new();
        for f in &animate_formats {
            match kshana::animation::animate_result(&out.json, kind.as_deref(), *f, &animate_opts) {
                Ok(a) => {
                    let target = match f {
                        kshana::animation::AnimationFormat::Svg => {
                            output_base.with_extension("animation.svg")
                        }
                        kshana::animation::AnimationFormat::Html => {
                            output_base.with_extension("animation.html")
                        }
                        kshana::animation::AnimationFormat::Frames => {
                            output_base.with_extension("frames")
                        }
                    };
                    written.push(
                        target
                            .file_name()
                            .map(|n| n.to_string_lossy().into_owned())
                            .unwrap_or_default(),
                    );
                    animations.push((target, a));
                }
                Err(e) => {
                    eprintln!("error: --animate {}: {e}", f.as_str());
                    return ExitCode::FAILURE;
                }
            }
        }
        match kshana::animation::animation_meta(
            &out.json,
            kind.as_deref(),
            &animate_formats,
            &animate_opts,
            &written,
        ) {
            Ok(meta) => out.json = kshana::animation::with_animation_meta(&out.json, &meta),
            Err(e) => {
                eprintln!("error: --animate: {e}");
                return ExitCode::FAILURE;
            }
        }
    }

    // Interoperability exports (`--export`): CZML, KML, GeoJSON, STK `.e` and SigMF. They
    // are rendered here, before anything is written, so the report and the animation
    // player can name the files; they are written after the other outputs. An explicitly
    // named format that does not apply is an error that names the reason; under `all` it
    // is reported and skipped.
    let mut export_outputs: Vec<(PathBuf, Vec<u8>, String)> = Vec::new();
    let mut export_skipped: Vec<String> = Vec::new();
    let mut export_errors: Vec<String> = Vec::new();
    let requested: Vec<(kshana::interop::Format, bool)> = if export_all {
        kshana::interop::Format::ALL
            .iter()
            .map(|&f| (f, false))
            .collect()
    } else {
        export_formats.iter().map(|&f| (f, true)).collect()
    };
    for (fmt, explicit) in requested {
        match kshana::interop::export(&src, fmt) {
            Ok(files) => {
                for f in files {
                    let target = output_base.with_extension(f.suffix.trim_start_matches('.'));
                    export_outputs.push((target, f.bytes, fmt.as_str().to_string()));
                }
            }
            Err(kshana::interop::ExportError::NotApplicable(why)) if !explicit => {
                export_skipped.push(format!("skipped {}: {why}", fmt.as_str()));
            }
            Err(e) => export_errors.push(format!("error: {} export: {e}", fmt.as_str())),
        }
    }
    let base_name = |p: &std::path::Path| {
        p.file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default()
    };
    let export_files: Vec<(String, String)> = export_outputs
        .iter()
        .map(|(t, _, f)| (f.clone(), base_name(t)))
        .collect();
    let animation_files: Vec<String> = animations.iter().map(|(t, _)| base_name(t)).collect();
    // The HTML player offers the export files written beside it.
    if !export_files.is_empty() {
        for (_, anim) in animations.iter_mut() {
            if anim.format == kshana::animation::AnimationFormat::Html {
                for f in anim.files.iter_mut() {
                    f.content = kshana::animation::with_companion_links(&f.content, &export_files);
                }
            }
        }
    }

    let json_path = output_base.with_extension("result.json");
    if let Err(e) = std::fs::write(&json_path, &out.json) {
        eprintln!("error: cannot write {}: {e}", json_path.display());
        return ExitCode::FAILURE;
    }
    let svg_path = output_base.with_extension("chart.svg");
    if let Err(e) = std::fs::write(&svg_path, &out.svg) {
        eprintln!("error: cannot write {}: {e}", svg_path.display());
        return ExitCode::FAILURE;
    }
    // The advanced report: report.html (printable) and report.json (the same content,
    // machine-readable). Both are pure functions of the run, the scenario bytes and the
    // invocation, so a re-run writes them byte for byte.
    let html_path = output_base.with_extension("report.html");
    let report_json_path = output_base.with_extension("report.json");
    let file_name =
        |p: &std::path::Path| p.file_name().and_then(|n| n.to_str()).map(str::to_string);
    let invocation = kshana::advanced_report::Invocation {
        scenario_arg: scenario_arg.clone(),
        extra_args: report_extra_args,
        input_files: report_input_files,
        result_file: file_name(&json_path),
        chart_file: file_name(&svg_path),
        animation_files,
        export_files,
    };
    let report = match kshana::advanced_report::build(&out, &scenario_src, &invocation) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: cannot build the report: {e}");
            return ExitCode::FAILURE;
        }
    };
    if let Err(e) = std::fs::write(&html_path, report.to_html(&out.svg)) {
        eprintln!("error: cannot write {}: {e}", html_path.display());
        return ExitCode::FAILURE;
    }
    if let Err(e) = std::fs::write(&report_json_path, report.to_json()) {
        eprintln!("error: cannot write {}: {e}", report_json_path.display());
        return ExitCode::FAILURE;
    }
    // CSV reproducibility artifact, when the scenario publishes one (e.g.
    // realtime-frame-eop's P4 Table 1 + Table 2). A plain run now emits the CSV the
    // paper cites, not only the golden-regen test.
    let csv_path = output_base.with_extension("table.csv");
    let wrote_csv = out.csv.is_some();
    match out.write_csv(&csv_path) {
        Ok(_) => {}
        Err(e) => {
            eprintln!("error: cannot write {}: {e}", csv_path.display());
            return ExitCode::FAILURE;
        }
    }
    println!("{}", out.summary);
    if wrote_csv {
        println!(
            "wrote {}, {}, {}, {}, and {}",
            json_path.display(),
            svg_path.display(),
            html_path.display(),
            report_json_path.display(),
            csv_path.display()
        );
    } else {
        println!(
            "wrote {}, {}, {}, and {}",
            json_path.display(),
            svg_path.display(),
            html_path.display(),
            report_json_path.display()
        );
    }

    for (target, anim) in &animations {
        match write_animation(target, anim) {
            Ok(()) => println!("wrote {}", target.display()),
            Err(e) => {
                eprintln!("error: cannot write {}: {e}", target.display());
                return ExitCode::FAILURE;
            }
        }
    }

    // SP3 export: an explicit `--export-sp3 <path>`, or the scenario's `export_sp3`
    // option which auto-writes `<scenario>.sp3`. Both require an orbit scenario.
    let sp3_target = match (&export_sp3_path, kshana::api::auto_export_sp3(&src)) {
        (Some(p), _) => Some((p.clone(), kshana::api::export_sp3(&src))),
        (None, Ok(Some(text))) => Some((path.with_extension("sp3"), Ok(text))),
        (None, Ok(None)) => None,
        (None, Err(e)) => Some((path.with_extension("sp3"), Err(e))),
    };
    if let Some((sp3_path, result)) = sp3_target {
        match result {
            Ok(text) => {
                if let Err(e) = std::fs::write(&sp3_path, text) {
                    eprintln!("error: cannot write {}: {e}", sp3_path.display());
                    return ExitCode::FAILURE;
                }
                println!("wrote {}", sp3_path.display());
            }
            Err(e) => {
                eprintln!("error: SP3 export failed: {e}");
                return ExitCode::FAILURE;
            }
        }
    }

    // OMM export: an explicit `--export-omm <path>`, or the scenario's `export_omm`
    // option which auto-writes `<scenario>.omm`. Both require an orbit scenario with
    // a TLE-defined constellation.
    let omm_target = match (&export_omm_path, kshana::api::auto_export_omm(&src)) {
        (Some(p), _) => Some((p.clone(), kshana::api::export_omm(&src))),
        (None, Ok(Some(text))) => Some((path.with_extension("omm"), Ok(text))),
        (None, Ok(None)) => None,
        (None, Err(e)) => Some((path.with_extension("omm"), Err(e))),
    };
    if let Some((omm_path, result)) = omm_target {
        match result {
            Ok(text) => {
                if let Err(e) = std::fs::write(&omm_path, text) {
                    eprintln!("error: cannot write {}: {e}", omm_path.display());
                    return ExitCode::FAILURE;
                }
                println!("wrote {}", omm_path.display());
            }
            Err(e) => {
                eprintln!("error: OMM export failed: {e}");
                return ExitCode::FAILURE;
            }
        }
    }

    // OEM export: an explicit `--export-oem <path>`, or the scenario's `export_oem`
    // option which auto-writes `<scenario>.oem`. Both require an orbit scenario. OEM
    // carries the full inertial state (position AND velocity), unlike SP3.
    let oem_target = match (&export_oem_path, kshana::api::auto_export_oem(&src)) {
        (Some(p), _) => Some((p.clone(), kshana::api::export_oem(&src))),
        (None, Ok(Some(text))) => Some((path.with_extension("oem"), Ok(text))),
        (None, Ok(None)) => None,
        (None, Err(e)) => Some((path.with_extension("oem"), Err(e))),
    };
    if let Some((oem_path, result)) = oem_target {
        match result {
            Ok(text) => {
                if let Err(e) = std::fs::write(&oem_path, text) {
                    eprintln!("error: cannot write {}: {e}", oem_path.display());
                    return ExitCode::FAILURE;
                }
                println!("wrote {}", oem_path.display());
            }
            Err(e) => {
                eprintln!("error: OEM export failed: {e}");
                return ExitCode::FAILURE;
            }
        }
    }
    // Interoperability exports, rendered above, are written last.
    for (target, bytes, _) in &export_outputs {
        if let Err(e) = std::fs::write(target, bytes) {
            eprintln!("error: cannot write {}: {e}", target.display());
            return ExitCode::FAILURE;
        }
        println!("wrote {}", target.display());
    }
    for m in &export_skipped {
        println!("{m}");
    }
    for m in &export_errors {
        eprintln!("{m}");
    }
    if !export_errors.is_empty() {
        return ExitCode::FAILURE;
    }
    ExitCode::SUCCESS
}

/// Write one animation export: a single file for `svg` and `html`, or a directory of
/// numbered frames plus `manifest.json` for `frames`.
fn write_animation(
    target: &std::path::Path,
    anim: &kshana::animation::Animation,
) -> std::io::Result<()> {
    match anim.format {
        kshana::animation::AnimationFormat::Frames => {
            std::fs::create_dir_all(target)?;
            // A shorter re-export must not leave frames of an earlier one behind: a
            // `frame_%04d.svg` encoder reads on through every contiguous number, so a
            // stale tail would play after the new frames. Only frame files are removed.
            for entry in std::fs::read_dir(target)? {
                let entry = entry?;
                let name = entry.file_name();
                let name = name.to_string_lossy();
                let is_frame = name.len() == "frame_0000.svg".len()
                    && name.starts_with("frame_")
                    && name.ends_with(".svg")
                    && name[6..10].bytes().all(|b| b.is_ascii_digit());
                if is_frame && entry.file_type()?.is_file() {
                    std::fs::remove_file(entry.path())?;
                }
            }
            for f in &anim.files {
                std::fs::write(target.join(&f.name), &f.content)?;
            }
            Ok(())
        }
        _ => match anim.files.first() {
            Some(f) => std::fs::write(target, &f.content),
            None => Ok(()),
        },
    }
}

/// `kshana kinds [--json]`: list the built-in scenario kinds.
///
/// The engine's unknown-kind error has always said "`kshana kinds` lists all N
/// built-in kinds" while no such subcommand existed, so the one remediation the CLI
/// printed could not be followed. Plain output is one kind name per line, which is
/// what that sentence promises and is greppable; `--json` emits the same
/// [`kshana::api::list_scenario_kinds_json`] metadata the Python, WASM and MCP faces
/// already serve, so every surface lists from one source.
fn print_kinds(rest: &[String]) -> ExitCode {
    match rest {
        [] => {
            for meta in kshana::api::list_scenario_kinds() {
                println!("{}", meta.name);
            }
            ExitCode::SUCCESS
        }
        [flag] if flag == "--json" => {
            println!("{}", kshana::api::list_scenario_kinds_json());
            ExitCode::SUCCESS
        }
        [other, ..] => {
            eprintln!(
                "error: unexpected argument '{other}' after `kinds`; only --json is accepted"
            );
            ExitCode::from(2)
        }
    }
}

/// `kshana example [<name>]`: print a bundled reference scenario to stdout, or, with no
/// name, list the bundled names one per line.
///
/// Every quickstart needs a scenario file, and a registry install ships none, so
/// `kshana example clock-holdover > clock-holdover.toml` is the first command a new user
/// types. The listing goes to stdout and its explanatory lines to stderr, so
/// `kshana example | while read n; do …` sees names only.
fn print_example(rest: &[String]) -> ExitCode {
    match rest {
        [] => {
            eprintln!(
                "Bundled reference scenarios ({}). Write one to a file and run it:\n  \
                 kshana example clock-holdover > clock-holdover.toml\n  \
                 kshana clock-holdover.toml",
                bundled_scenarios::BUNDLED.len()
            );
            for (name, _) in bundled_scenarios::BUNDLED {
                println!("{name}");
            }
            for (name, _) in bundled_scenarios::REPO_ONLY {
                eprintln!("(not bundled: {name} — run `kshana example {name}` for why)");
            }
            ExitCode::SUCCESS
        }
        [name] => {
            if let Some(toml) = bundled_scenarios::get(name) {
                print!("{toml}");
                return ExitCode::SUCCESS;
            }
            if let Some(why) = bundled_scenarios::repo_only_reason(name) {
                eprintln!("error: '{name}' is not bundled: it {why}");
                return ExitCode::from(2);
            }
            eprintln!(
                "error: no bundled scenario named '{name}'; `kshana example` lists the {} that are",
                bundled_scenarios::BUNDLED.len()
            );
            ExitCode::from(2)
        }
        [_, extra, ..] => {
            eprintln!(
                "error: unexpected argument '{extra}' after `example <name>`; it takes one name"
            );
            ExitCode::from(2)
        }
    }
}

/// `--study <suite.toml>` handler: parse the suite manifest, run every scenario it
/// names (resolved against the manifest's parent directory) through the same
/// engine the single-scenario path uses, and write a `<suite_stem>.study.json`
/// plus `<suite_stem>.study.html` next to the manifest. The library aggregation
/// ([`kshana::study::run_suite`]) is pure; the CLI is the only place allowed to
/// stamp a generation timestamp, so it injects `generated_utc` into the artifact
/// here (the HTML/JSON the library produced stay byte-deterministic without it).
fn run_study(suite_path: &std::path::Path) -> ExitCode {
    let src = match std::fs::read_to_string(suite_path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: cannot read {}: {e}", suite_path.display());
            return ExitCode::FAILURE;
        }
    };
    let suite = match kshana::suite::parse_suite(&src) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: {e}");
            return ExitCode::FAILURE;
        }
    };
    let base_dir = suite_path
        .parent()
        .unwrap_or_else(|| std::path::Path::new("."));
    let out = match kshana::study::run_suite(&suite, base_dir) {
        Ok(o) => o,
        Err(e) => {
            eprintln!("error: {e}");
            return ExitCode::FAILURE;
        }
    };

    // Stamp a CLI-supplied generation time into the study JSON (the only clock
    // read in the crate). Pure aggregation never reads a clock, so the stamp is
    // added here, after the fact.
    let json = stamp_study_generated(&out.json, &utc_iso8601_now());

    let base = output_base_for_suite(suite_path);
    let json_path = base.with_extension("study.json");
    if let Err(e) = std::fs::write(&json_path, &json) {
        eprintln!("error: cannot write {}: {e}", json_path.display());
        return ExitCode::FAILURE;
    }
    let html_path = base.with_extension("study.html");
    if let Err(e) = std::fs::write(&html_path, &out.html) {
        eprintln!("error: cannot write {}: {e}", html_path.display());
        return ExitCode::FAILURE;
    }
    println!("{}", out.summary);
    println!("wrote {} and {}", json_path.display(), html_path.display());
    ExitCode::SUCCESS
}

/// The output base for a suite manifest: the manifest path with any extension
/// stripped, so `holdover.toml` → `holdover` and the writers append
/// `.study.json` / `.study.html`.
fn output_base_for_suite(suite_path: &std::path::Path) -> PathBuf {
    suite_path.with_extension("")
}

/// Inject a `generated_utc` field into the study artifact JSON. Parses the
/// document, sets the field on the top-level object, and re-serializes; a parse
/// failure (should not happen for our own output) leaves the JSON unchanged so a
/// study is still written.
fn stamp_study_generated(json: &str, stamp: &str) -> String {
    match serde_json::from_str::<serde_json::Value>(json) {
        Ok(mut v) => {
            if let Some(obj) = v.as_object_mut() {
                obj.insert(
                    "generated_utc".to_string(),
                    serde_json::Value::String(stamp.to_string()),
                );
            }
            serde_json::to_string_pretty(&v).unwrap_or_else(|_| json.to_string())
        }
        Err(_) => json.to_string(),
    }
}