opi 0.5.3

Operations Interface — a project control center for your terminal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
//! `opi` — Operations Interface.
//!
//! A project control center for the terminal. `opi` lists a project's scripts
//! and runs the one you pick; `opi <script>` skips the list entirely.

#[cfg(not(unix))]
compile_error!(
    "opi is Unix-only: it runs a script by replacing its own process with exec, \
     and its interactive list drives termios directly."
);

mod audit;
mod cargo;
mod check;
mod clean;
mod cli;
mod manifest;
mod outdated;
mod project;
mod run;
mod task;
mod workflow;
mod workspace;

use std::io::{self, IsTerminal, Write};
use std::path::Path;
use std::process::ExitCode;

use runemark::{
    ColorMode, Console, DetailLevel, ErrorBlock, Finding, FindingGroup, Group, Hint, Item, Menu,
    Metric, NextStep, Outcome, Report, SelectMode, Tone, Verdict,
};

use crate::cli::Invocation;
use crate::manifest::{Manifest, ManifestError};
use crate::project::Project;
use crate::task::{Task, by_group, find, suggestions};

const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Lines of a failing tool's output health prints before pointing at the tool.
const OUTPUT_LINES: usize = 20;

fn main() -> ExitCode {
    let invocation = cli::parse(std::env::args().skip(1));

    match &invocation {
        Invocation::Help => {
            println!("{}", cli::help(VERSION));
            return ExitCode::SUCCESS;
        }
        Invocation::Version => {
            println!("opi {VERSION}");
            return ExitCode::SUCCESS;
        }
        _ => {}
    }

    let directory = match std::env::current_dir() {
        Ok(directory) => directory,
        Err(error) => {
            let console = Console::stderr(ColorMode::Auto);
            eprintln!(
                "{}",
                console.paint(
                    Tone::Error,
                    format!("Cannot read the current directory: {error}")
                )
            );
            return ExitCode::FAILURE;
        }
    };

    // A repository may be more than one kind of project at once — twelve of
    // the ones measured carry both a package.json and a Cargo.toml — so both
    // are looked for and neither is allowed to win.
    let npm = Manifest::discover(&directory);
    let rust = cargo::discover(&directory);

    if let (Err(error), None) = (&npm, &rust) {
        report_error(error);
        return ExitCode::FAILURE;
    }

    let (manifest, root) = match npm {
        Ok((manifest, root)) => (manifest, root),
        // A Rust-only project still needs somewhere to stand and something to
        // read; an empty manifest answers both without a special case below.
        Err(_) => (
            Manifest::default(),
            rust.as_ref()
                .map_or_else(|| directory.clone(), |(_, root)| root.clone()),
        ),
    };

    let project = Project::detect(&manifest, &root)
        .or_named(rust.as_ref().and_then(|(rust, _)| rust.name.clone()));
    let members = workspace::members(&root, &manifest);
    let mut tasks = Task::from_workspace(&manifest, &members);
    if let Some((rust, _)) = &rust {
        tasks.extend(task::from_cargo(rust));
    }
    task::arrange(&mut tasks);

    let rust_root = rust.as_ref().map(|(_, root)| root.clone());

    match invocation {
        Invocation::List => list(
            &manifest,
            &members,
            rust_root.as_deref(),
            &project,
            &tasks,
            &root,
        ),
        Invocation::Health => health(&manifest, &members, rust_root.as_deref(), &project, &root),
        Invocation::Clean => clean(&manifest, &members, rust_root.as_deref(), &project, &root),
        Invocation::Security => security(&manifest, &members, &project, &root),
        Invocation::Updates => updates(&project, &root),
        Invocation::Workflow(name) => run_workflow(
            &name,
            &manifest,
            &members,
            rust_root.as_deref(),
            &project,
            &root,
        ),
        Invocation::Run {
            name,
            args,
            confirmed,
        } => start(&project, &tasks, &name, &args, confirmed),
        // An unknown flag is only reported once a project is present, so the
        // missing-package.json message wins where both are true — that is the
        // problem the user has to fix first.
        Invocation::UnknownFlag(flag) => {
            let console = Console::stderr(ColorMode::Auto);
            let block = ErrorBlock::new(format!("Unknown option {flag}"))
                .with_remedy("Run opi --help to see the available options.");
            write_block(&block, console);
            ExitCode::FAILURE
        }
        Invocation::Help | Invocation::Version => unreachable!("handled above"),
    }
}

/// Shows the project's scripts and runs whichever one is chosen.
fn list(
    manifest: &Manifest,
    members: &[workspace::Member],
    rust_root: Option<&Path>,
    project: &Project,
    tasks: &[Task],
    directory: &Path,
) -> ExitCode {
    let manager = project.package_manager;

    if tasks.is_empty() {
        let console = Console::stdout(ColorMode::Auto);
        println!(
            "{}  {}",
            console.paint(Tone::Title, project.display_name(directory)),
            console.paint(Tone::Muted, manager.manager)
        );
        println!(
            "{}",
            console.paint(Tone::Muted, "This project defines no scripts.")
        );
        return ExitCode::SUCCESS;
    }

    // Only worth saying where something would actually be run with it: a
    // Rust-only project has no use for a package manager and no reason to hear
    // that one was guessed.
    let runs_scripts = tasks
        .iter()
        .any(|task| matches!(task.exec, task::Exec::Script));
    if !manager.is_certain() && runs_scripts {
        let console = Console::stderr(ColorMode::Auto);
        eprintln!(
            "{}",
            console.paint(
                Tone::Warning,
                format!(
                    "No lockfile and no packageManager field — assuming {}.",
                    manager.manager
                ),
            )
        );
    }

    let mut menu = build_menu(project, tasks, directory);
    // Offered only where it would do something; a key that answers "nothing
    // applies" is worse than no key.
    let checks = check::Check::detect_all(manifest, members, rust_root, directory);
    if !checks.is_empty() {
        menu = menu.add_hint(Hint::new('H', "Health"));
    }
    menu = menu
        .add_hint(Hint::new('C', "Clean"))
        .add_hint(Hint::new('S', "Security"))
        .add_hint(Hint::new('U', "Updates"));

    // Both streams have to be terminals. stdout decides whether the list is
    // being captured rather than read, and the menu draws its frames on
    // stderr, so a redirect on either one means plain text is what is wanted.
    let interactive = io::stdout().is_terminal() && io::stderr().is_terminal();

    let outcome = match menu.run(
        Console::stderr(ColorMode::Auto),
        SelectMode::Auto,
        interactive,
    ) {
        Ok(outcome) => outcome,
        Err(error) => {
            let block = ErrorBlock::new("Cannot open the terminal")
                .with_explanation(format!("{error}"))
                .with_remedy("Run opi <script> to start a script without the list.");
            write_block(&block, Console::stderr(ColorMode::Auto));
            return ExitCode::FAILURE;
        }
    };

    match outcome {
        Outcome::Selected(id) => start(project, tasks, &id, &[], false),
        // Nothing was chosen; that is not a failure.
        Outcome::Cancelled => ExitCode::SUCCESS,
        Outcome::Hotkey('H') => health(manifest, members, rust_root, project, directory),
        Outcome::Hotkey('C') => clean(manifest, members, rust_root, project, directory),
        Outcome::Hotkey('S') => security(manifest, members, project, directory),
        Outcome::Hotkey('U') => updates(project, directory),
        Outcome::Hotkey(_) => ExitCode::SUCCESS,
        Outcome::Unavailable => {
            print!("{}", menu.render(Console::stdout(ColorMode::Auto)));
            ExitCode::SUCCESS
        }
    }
}

/// What the header says the project is built with.
///
/// A repository carrying both manifests says both. Naming only one would make
/// the other half of its list look like it arrived from nowhere.
fn toolchains(tasks: &[Task], project: &Project) -> String {
    let mut names = Vec::new();
    if tasks
        .iter()
        .any(|task| matches!(task.exec, task::Exec::Script))
    {
        names.push(project.package_manager.manager.to_string());
    }
    if tasks
        .iter()
        .any(|task| matches!(&task.exec, task::Exec::Direct { program, .. } if program == "cargo"))
    {
        names.push("cargo".to_owned());
    }
    if names.is_empty() {
        names.push(project.package_manager.manager.to_string());
    }
    names.join(" · ")
}

/// Turns the task list into a menu.
///
/// The item id is the script name, so a selection is ready to run as-is.
fn build_menu(project: &Project, tasks: &[Task], directory: &Path) -> Menu {
    let mut menu = Menu::new()
        .with_heading(project.display_name(directory))
        .with_note(toolchains(tasks, project));

    for (group, section) in by_group(tasks) {
        let mut rendered = Group::new(group.label());
        for task in section {
            // The id has to disambiguate: root and member scripts share names
            // in every workspace repository measured.
            let id = match &task.workspace {
                Some(member) => format!("{member}/{}", task.name),
                None => task.name.clone(),
            };
            let mut item = Item::new(id, &task.name);
            if let Some(description) = &task.description {
                item = item.with_description(description);
            }
            rendered = rendered.add_item(item);
        }
        menu = menu.add_group(rendered);
    }

    menu
}

/// Runs `name`, or explains why it cannot.
///
/// Returns only on failure: a started script replaces this process.
fn start(
    project: &Project,
    tasks: &[Task],
    name: &str,
    args: &[String],
    confirmed: bool,
) -> ExitCode {
    let Some(task) = find(tasks, name) else {
        let console = Console::stderr(ColorMode::Auto);
        let mut block = ErrorBlock::new(format!("No script named {name}"));

        let close = suggestions(tasks, name);
        block = if close.is_empty() {
            block.with_remedy("Run opi to see the project's scripts.")
        } else {
            block.with_explanation(format!("Did you mean {}?", close.join(", ")))
        };
        for candidate in close {
            block = block.add_command(format!("opi {candidate}"));
        }

        write_block(&block, console);
        return ExitCode::FAILURE;
    };

    if task.confirm && !confirmed && !confirm(task) {
        return ExitCode::FAILURE;
    }

    let manager = project.package_manager;
    let error = run::execute(task, manager.manager, args);

    let console = Console::stderr(ColorMode::Auto);
    let block = ErrorBlock::new(format!("Cannot run {}", manager.manager))
        .with_explanation(format!("{error}"))
        .with_remedy(if manager.is_certain() {
            format!(
                "Check that {} is installed and on your PATH.",
                manager.manager
            )
        } else {
            format!(
                "No lockfile or packageManager field names a package manager, so {} was assumed.",
                manager.manager
            )
        });
    write_block(&block, console);
    ExitCode::FAILURE
}

/// Asks before running a task the project marked as needing it.
///
/// Without a terminal this refuses rather than assuming yes. Skipping the
/// question where it cannot be asked would remove the protection in exactly
/// the case it exists for — a script, a hook, CI — so `--yes` has to be said
/// out loud there.
fn confirm(task: &Task) -> bool {
    let console = Console::stderr(ColorMode::Auto);
    let interactive = io::stdout().is_terminal() && io::stderr().is_terminal();

    if !interactive {
        let block = ErrorBlock::new(format!("{} needs confirming", task.name))
            .with_explanation("This project marked it as needing a confirmation, and there is no terminal to ask in.")
            .with_remedy("Run it again with --yes if that is what you mean.")
            .add_command(format!("opi --yes {}", task.name));
        write_block(&block, console);
        return false;
    }

    let menu = Menu::new()
        .with_heading(format!("Run {}?", task.name))
        .with_note(&task.command)
        .add_group(
            Group::new("Confirm")
                .add_item(Item::new("no", "Cancel"))
                .add_item(Item::new("yes", format!("Run {}", task.name))),
        );

    // Cancel first, so the cursor starts on the harmless answer.
    matches!(
        menu.run(console, SelectMode::Auto, true),
        Ok(Outcome::Selected(choice)) if choice == "yes"
    )
}

/// Writes an error block to stderr, ignoring a broken pipe.
fn write_block(block: &ErrorBlock, console: Console) {
    let mut stderr = io::stderr().lock();
    let _ = block.write_to(console, &mut stderr);
    let _ = stderr.flush();
}

fn report_error(error: &ManifestError) {
    let console = Console::stderr(ColorMode::Auto);
    let block = match error {
        ManifestError::Missing { directory } => ErrorBlock::new("No package.json found")
            .with_explanation(format!(
                "Searched {} and every directory above it.",
                directory.display()
            ))
            .with_remedy("Change into a project directory and run opi again."),
        ManifestError::Unreadable { path, error } => ErrorBlock::new("package.json is unreadable")
            .with_explanation(format!("{}: {error}", path.display()))
            .with_remedy("Check the file permissions."),
        ManifestError::Malformed { path, error } => {
            ErrorBlock::new("package.json is not valid JSON")
                .with_explanation(format!("{}: {error}", path.display()))
                .with_remedy("Fix the syntax error and run opi again.")
        }
    };

    write_block(&block, console);
}

/// Runs the project's checks and reports what each tool said.
fn health(
    manifest: &Manifest,
    members: &[workspace::Member],
    rust_root: Option<&Path>,
    project: &Project,
    root: &Path,
) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);
    let checks = check::Check::detect_all(manifest, members, rust_root, root);

    println!(
        "{}  {}",
        console.paint(Tone::Title, project.display_name(root)),
        console.paint(Tone::Muted, "health")
    );
    println!();

    if checks.is_empty() {
        println!(
            "{}",
            console.paint(
                Tone::Muted,
                "No checks apply: this project depends on none of the tools opi knows."
            )
        );
        return ExitCode::SUCCESS;
    }

    // Results print as they arrive rather than after the slowest one, so a
    // long test run does not look like a hang.
    let width = checks
        .iter()
        .map(|check| check.label().chars().count())
        .max()
        .unwrap_or(0);
    let reports = check::run_all(checks, |report| {
        let (tone, mark) = match report {
            report if report.passed() => (Tone::Success, ""),
            report if report.unusable() => (Tone::Warning, "!"),
            _ => (Tone::Error, ""),
        };
        println!(
            "{} {}  {}  {}",
            console.paint(tone, mark),
            console.paint(tone, format!("{:width$}", report.check.label())),
            console.paint(
                Tone::Muted,
                format!("{:>6.1}s", report.duration.as_secs_f64())
            ),
            console.paint(Tone::Muted, report.check.tool),
        );
    });

    let failed: Vec<&check::Report> = reports.iter().filter(|report| !report.passed()).collect();
    let unusable = failed.iter().filter(|report| report.unusable()).count();

    // No score. A composite number stops meaning anything within weeks; what a
    // failing tool actually said does not.
    for report in &failed {
        println!();
        let tone = if report.unusable() {
            Tone::Warning
        } else {
            Tone::Error
        };
        println!(
            "{}",
            console.paint(
                tone,
                format!("{}{}", report.check.label(), report.check.tool)
            )
        );
        // Capped: one failing scanner produced 49 lines on a real project, and
        // several at once bury the summary that says what to do next.
        let lines: Vec<&str> = report.output.lines().collect();
        for line in lines.iter().take(OUTPUT_LINES) {
            println!("  {line}");
        }
        if let Some(hidden) = lines.len().checked_sub(OUTPUT_LINES).filter(|n| *n > 0) {
            println!(
                "  {}",
                console.paint(
                    Tone::Muted,
                    format!(
                        "{hidden} more lines — run `{}` in {} to see them all",
                        report.check.command_line(),
                        report.check.scope.as_deref().unwrap_or("the project root"),
                    )
                )
            );
        }
    }

    println!();
    if failed.is_empty() {
        println!(
            "{}",
            console.paint(Tone::Success, format!("{} checks passed.", reports.len()))
        );
        ExitCode::SUCCESS
    } else {
        let note = if unusable > 0 {
            format!(
                "{} of {} checks failed, {unusable} could not run.",
                failed.len(),
                reports.len()
            )
        } else {
            format!("{} of {} checks failed.", failed.len(), reports.len())
        };
        println!("{}", console.paint(Tone::Error, note));
        ExitCode::FAILURE
    }
}

/// Shows what can be removed, and removes what is chosen.
fn clean(
    manifest: &Manifest,
    members: &[workspace::Member],
    rust_root: Option<&Path>,
    project: &Project,
    root: &Path,
) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);
    let candidates = clean::candidates(manifest, members, rust_root, root);

    println!(
        "{}  {}",
        console.paint(Tone::Title, project.display_name(root)),
        console.paint(Tone::Muted, "clean")
    );
    println!();

    if candidates.is_empty() {
        println!(
            "{}",
            console.paint(Tone::Muted, "Nothing to remove; the project is clean.")
        );
        return ExitCode::SUCCESS;
    }

    let width = candidates
        .iter()
        .map(|candidate| candidate.display.chars().count())
        .max()
        .unwrap_or(0);
    for candidate in &candidates {
        println!(
            "  {}  {}",
            console.paint(
                if candidate.heavy {
                    Tone::Warning
                } else {
                    Tone::Info
                },
                format!("{:width$}", candidate.display)
            ),
            console.paint(Tone::Muted, clean::human(candidate.bytes)),
        );
    }
    println!();

    let artefacts: Vec<&clean::Candidate> =
        candidates.iter().filter(|entry| !entry.heavy).collect();
    let everything: Vec<&clean::Candidate> = candidates.iter().collect();
    let artefact_bytes: u64 = artefacts.iter().map(|entry| entry.bytes).sum();
    let total_bytes: u64 = everything.iter().map(|entry| entry.bytes).sum();

    // Concrete choices rather than per-entry ticking. The distinction that
    // matters is node_modules against the rest: it is the largest item and the
    // most expensive to rebuild, so it never rides along with a build artefact.
    let mut menu = Menu::new().add_group({
        let mut group = Group::new("Remove");
        if !artefacts.is_empty() {
            group = group.add_item(
                Item::new("artefacts", "Build artefacts")
                    .with_description(clean::human(artefact_bytes)),
            );
        }
        if artefacts.len() != everything.len() {
            group = group.add_item(
                Item::new("everything", "Everything, including node_modules")
                    .with_description(clean::human(total_bytes)),
            );
        }
        group.add_item(Item::new("cancel", "Cancel"))
    });
    menu = menu.with_note(format!("{} removable", clean::human(total_bytes)));

    let interactive = io::stdout().is_terminal() && io::stderr().is_terminal();
    let chosen = match menu.run(
        Console::stderr(ColorMode::Auto),
        SelectMode::Auto,
        interactive,
    ) {
        Ok(Outcome::Selected(id)) => id,
        Ok(Outcome::Unavailable) => {
            // Nothing is removed without someone choosing it, so a pipe gets
            // the inventory and stops there.
            println!(
                "{}",
                console.paint(
                    Tone::Muted,
                    "Run opi --clean in a terminal to remove any of it."
                )
            );
            return ExitCode::SUCCESS;
        }
        Ok(_) => return ExitCode::SUCCESS,
        Err(error) => {
            let block =
                ErrorBlock::new("Cannot open the terminal").with_explanation(format!("{error}"));
            write_block(&block, Console::stderr(ColorMode::Auto));
            return ExitCode::FAILURE;
        }
    };

    let selected: &[&clean::Candidate] = match chosen.as_str() {
        "artefacts" => &artefacts,
        "everything" => &everything,
        _ => return ExitCode::SUCCESS,
    };

    let started = std::time::Instant::now();
    let (freed, failures) = clean::remove(selected);

    println!(
        "{}",
        console.paint(
            Tone::Success,
            format!(
                "Removed {} in {:.1}s",
                clean::human(freed),
                started.elapsed().as_secs_f64()
            )
        )
    );
    for (path, error) in &failures {
        println!(
            "{}",
            console.paint(Tone::Error, format!("Could not remove {path}: {error}"))
        );
    }

    if failures.is_empty() {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    }
}

/// Scans the repository for secrets and its dependencies for vulnerabilities.
fn security(
    manifest: &Manifest,
    members: &[workspace::Member],
    project: &Project,
    root: &Path,
) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);
    println!(
        "{}  {}",
        console.paint(Tone::Title, project.display_name(root)),
        console.paint(Tone::Muted, "security")
    );
    println!();

    let mut clean = true;

    // Secrets is a check like any other; this only makes it reachable without
    // waiting for the tests to finish.
    // Secrets scanning is about the repository, not a toolchain, so the Rust
    // side contributes nothing here.
    let scans: Vec<check::Check> = check::Check::detect_all(manifest, members, None, root)
        .into_iter()
        .filter(|check| check.name == "Secrets")
        .collect();

    if scans.is_empty() {
        println!(
            "{}",
            console.paint(
                Tone::Muted,
                "No secret scanner: this project depends on none that opi knows."
            )
        );
    } else {
        let reports = check::run_all(scans, |_| {});
        for report in &reports {
            if report.passed() {
                println!(
                    "{} {}",
                    console.paint(Tone::Success, ""),
                    console.paint(Tone::Success, format!("Secrets — {}", report.check.tool))
                );
            } else {
                clean = false;
                println!(
                    "{} {}",
                    console.paint(Tone::Error, ""),
                    console.paint(Tone::Error, format!("Secrets — {}", report.check.tool))
                );
                // Locations, not values: this output lands in scrollback, CI
                // logs and screenshots.
                let lines: Vec<&str> = report.output.lines().collect();
                for line in lines.iter().take(OUTPUT_LINES) {
                    println!("  {line}");
                }
                if let Some(rest) = lines.len().checked_sub(OUTPUT_LINES).filter(|n| *n > 0) {
                    println!(
                        "  {}",
                        console.paint(
                            Tone::Muted,
                            format!(
                                "{rest} more lines — run `{}`",
                                report.check.command_line()
                            )
                        )
                    );
                }
            }
        }
    }

    println!();
    match audit::run(project.package_manager.manager, root) {
        Ok(found) if found.is_empty() => println!(
            "{} {}",
            console.paint(Tone::Success, ""),
            console.paint(Tone::Success, "Dependencies — no known vulnerabilities")
        ),
        Ok(found) => {
            let serious = found
                .advisories
                .iter()
                .any(|advisory| advisory.severity.serious());
            clean = clean && !serious;

            // Parsed rather than relayed, so this is where a report earns its
            // keep: severity counts as metrics, each advisory with the version
            // range that fixes it as its remedy.
            let mut report = Report::new(
                "Dependencies",
                if serious {
                    Verdict::Failed
                } else {
                    Verdict::Warning
                },
            )
            .with_detail_level(DetailLevel::Detailed);

            // A verdict rather than a tone: this is read in pipes and in CI,
            // where a tone is nothing at all.
            for (severity, count) in found.counts() {
                report = report.add_metric(
                    Metric::new(severity.label(), count.to_string()).with_verdict(
                        if severity.serious() {
                            Verdict::Failed
                        } else {
                            Verdict::Warning
                        },
                    ),
                );
            }

            let mut group = FindingGroup::new("Vulnerable dependencies");
            for advisory in &found.advisories {
                let mut finding = Finding::new(
                    if advisory.severity.serious() {
                        Tone::Error
                    } else {
                        Tone::Warning
                    },
                    &advisory.module,
                )
                .with_rule_id(advisory.severity.label());
                if let Some(patched) = &advisory.patched {
                    finding = finding.with_remedy(format!("update to {patched}"));
                }
                group = group.add_finding(finding);
            }
            report = report.add_group(group);

            print!("{}", report.render(console));
        }
        Err(error) => println!(
            "{} {}",
            console.paint(Tone::Muted, ""),
            console.paint(Tone::Muted, format!("Dependencies — {error}"))
        ),
    }

    println!();
    if clean {
        println!("{}", console.paint(Tone::Success, "Nothing to act on."));
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    }
}

/// Runs a named workflow: the repository questions, then the checks.
fn run_workflow(
    name: &str,
    manifest: &Manifest,
    members: &[workspace::Member],
    rust_root: Option<&Path>,
    project: &Project,
    root: &Path,
) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);

    let Some(workflow) = workflow::Workflow::parse(name) else {
        let block = ErrorBlock::new(format!("No workflow named {name}"))
            .with_remedy("Known workflows: commit, release.");
        write_block(&block, Console::stderr(ColorMode::Auto));
        return ExitCode::FAILURE;
    };

    println!(
        "{}  {}",
        console.paint(Tone::Title, project.display_name(root)),
        console.paint(Tone::Muted, workflow.label())
    );
    println!();

    let mut blocked = false;

    // The repository questions come first: a release from a dirty tree is
    // settled before spending a minute on its tests.
    for gate in workflow.gates() {
        let result = gate.check(root, manifest.version.as_deref());
        let (tone, mark) = match result.verdict {
            runemark::Verdict::Passed => (Tone::Success, ""),
            runemark::Verdict::Skipped => (Tone::Muted, ""),
            _ => {
                blocked = true;
                (Tone::Error, "")
            }
        };
        let detail = result
            .detail
            .map_or_else(String::new, |detail| format!("  {detail}"));
        println!(
            "{} {}{}",
            console.paint(tone, mark),
            console.paint(tone, gate.name()),
            console.paint(Tone::Muted, detail)
        );
    }

    let checks: Vec<check::Check> = check::Check::detect_all(manifest, members, rust_root, root)
        .into_iter()
        .filter(|check| workflow.includes(check.name))
        .collect();

    if checks.is_empty() {
        println!(
            "{}",
            console.paint(Tone::Muted, "No checks apply to this project.")
        );
    }

    let width = checks
        .iter()
        .map(|check| check.label().chars().count())
        .max()
        .unwrap_or(0);
    let reports = check::run_all(checks, |report| {
        let (tone, mark) = match report {
            report if report.passed() => (Tone::Success, ""),
            report if report.unusable() => (Tone::Warning, "!"),
            _ => (Tone::Error, ""),
        };
        println!(
            "{} {}  {}",
            console.paint(tone, mark),
            console.paint(tone, format!("{:width$}", report.check.label())),
            console.paint(Tone::Muted, report.check.tool),
        );
    });

    let failed = reports.iter().filter(|report| !report.passed()).count();
    println!();

    if blocked || failed > 0 {
        // Which step and why, rather than a count on its own.
        for report in reports.iter().filter(|report| !report.passed()) {
            println!(
                "{}",
                console.paint(
                    Tone::Error,
                    format!("{}{}", report.check.label(), report.check.tool)
                )
            );
            for line in report.output.lines().take(OUTPUT_LINES) {
                println!("  {line}");
            }
        }
        println!();
        println!(
            "{}",
            console.paint(Tone::Error, format!("Not ready to {name}."))
        );
        ExitCode::FAILURE
    } else {
        println!(
            "{}",
            console.paint(Tone::Success, format!("Ready to {name}."))
        );
        ExitCode::SUCCESS
    }
}

/// Shows which dependencies have moved on, separated by how far.
///
/// Rendered as a runemark `Report` rather than a hand-set table: the split
/// between safe and breaking is the whole value of this screen, and a report's
/// groups make it structural instead of a sentence underneath a list.
fn updates(project: &Project, root: &Path) -> ExitCode {
    let console = Console::stdout(ColorMode::Auto);
    let manager = project.package_manager.manager;

    let found = match outdated::run(manager, root) {
        Ok(found) => found,
        Err(error) => {
            let block = ErrorBlock::new("Cannot list outdated dependencies")
                .with_explanation(format!("{error}"));
            write_block(&block, Console::stderr(ColorMode::Auto));
            return ExitCode::FAILURE;
        }
    };

    if found.is_empty() {
        println!(
            "{}  {}",
            console.paint(Tone::Title, project.display_name(root)),
            console.paint(Tone::Success, "everything is current")
        );
        return ExitCode::SUCCESS;
    }

    let (breaking, safe): (Vec<_>, Vec<_>) =
        found.iter().partition(|update| update.jump.breaking());

    let mut report = Report::new(
        project.display_name(root),
        if breaking.is_empty() {
            Verdict::Info
        } else {
            Verdict::Warning
        },
    )
    .with_detail_level(DetailLevel::Detailed);

    if !safe.is_empty() {
        report = report.add_metric(Metric::new("safe", safe.len().to_string()));
    }
    if !breaking.is_empty() {
        report = report
            .add_metric(Metric::new("major", breaking.len().to_string()).with_tone(Tone::Warning));
    }

    for (title, tone, group) in [
        ("Safe to take", Tone::Muted, &safe),
        ("A decision each", Tone::Warning, &breaking),
    ] {
        if group.is_empty() {
            continue;
        }
        let mut findings = FindingGroup::new(title);
        for update in group.iter() {
            findings = findings.add_finding(
                Finding::new(
                    tone,
                    format!("{} {}{}", update.name, update.current, update.latest),
                )
                .with_rule_id(update.jump.label()),
            );
        }
        report = report.add_group(findings);
    }

    if !safe.is_empty() {
        report = report.add_next_step(
            NextStep::new("Take the safe ones").with_command(format!("{manager} update")),
        );
    }

    // No width hint: two metrics read better side by side than stacked, and
    // the findings wrap on their own.
    print!("{}", report.render(console));
    ExitCode::SUCCESS
}