kshana 0.28.0

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
// 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>]
   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;
    let mut study_name: Option<String> = None;
    let mut study_suite_path: Option<PathBuf> = None;
    let mut validate_path: Option<PathBuf> = None;
    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);
                    }
                }
            }
            "--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;
    }
    // `--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;
        }
    };

    // `--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;
            }
        };
        match kshana::api::inject_eop(&src, &body) {
            Ok(merged) => src = merged,
            Err(e) => {
                eprintln!("error: --eop: {e}");
                return ExitCode::FAILURE;
            }
        }
    }
    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) => {
            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(),
    };

    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;
    }
    let html_path = output_base.with_extension("report.html");
    if let Err(e) = std::fs::write(&html_path, out.html_report()) {
        eprintln!("error: cannot write {}: {e}", html_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(),
            csv_path.display()
        );
    } else {
        println!(
            "wrote {}, {}, and {}",
            json_path.display(),
            svg_path.display(),
            html_path.display()
        );
    }

    // 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;
            }
        }
    }
    ExitCode::SUCCESS
}

/// `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(),
    }
}