toha 0.4.2

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

/// Whether a staged interview has questions remaining, when that is known.
#[derive(Clone, Copy)]
pub enum Progress {
    Incomplete,
    Complete,
    /// A flow `stop`/`abort` ended the interview: no questions remain and there
    /// is nothing to apply. The only way forward is to start over.
    Ended,
    Unknown,
}

/// The shell a suggested command is written for.
#[derive(Clone, Copy)]
enum Shell {
    /// A POSIX shell such as sh, bash, or zsh.
    Posix,
    /// cmd.exe or PowerShell.
    Windows,
}
const SHELL: Shell = if cfg!(windows) {
    Shell::Windows
} else {
    Shell::Posix
};

/// A formal name as a command operand. A local folder's formal name on
/// Windows is an extended path (`\\?\D:\...`), which a `<TEMPLATE>` argument
/// reads as a name; its drive path names the same folder.
pub fn plain_formal(formal: &str) -> &str {
    match formal.strip_prefix(r"\\?\") {
        Some(rest)
            if rest.as_bytes().get(0..3).is_some_and(|prefix| {
                prefix[0].is_ascii_alphabetic() && prefix[1] == b':' && prefix[2] == b'\\'
            }) =>
        {
            rest
        }
        _ => formal,
    }
}

/// The form of a formal name that `command` accepts. `stage`, `apply`, and
/// `templates add` read a `<TEMPLATE>` or address argument, so a folder is
/// named by its drive path; `templates remove`, `update`, `alias`, `trust`, and
/// `untrust` look up the formal name as the registry stores it.
pub fn formal_for<'a>(command: &str, formal: &'a str) -> &'a str {
    match command {
        "templates remove" | "templates update" | "templates alias" | "templates trust"
        | "templates untrust" => formal,
        _ => plain_formal(formal),
    }
}

/// A path value without trailing separators, so that no suggested path ends
/// in a separator before a closing quote. A root (`/`, `\`, `C:\`, `C:/`)
/// is kept whole.
fn path_value(value: &str, shell: Shell) -> &str {
    let separators: &[char] = match shell {
        Shell::Posix => &['/'],
        Shell::Windows => &['/', '\\'],
    };
    let trimmed = value.trim_end_matches(separators);
    let drive = trimmed.strip_prefix(r"\\?\").unwrap_or(trimmed);
    let drive = matches!(shell, Shell::Windows)
        && drive.len() == 2
        && drive.as_bytes()[0].is_ascii_alphabetic()
        && drive.as_bytes()[1] == b':';
    let root = trimmed.is_empty() || drive;
    if root && trimmed.len() < value.len() {
        // Keep one separator: `/`, `\`, `C:\`, `\\?\C:\`.
        &value[..trimmed.len() + 1]
    } else {
        trimmed
    }
}

/// `value` as one shell word for the shell of this platform.
pub fn word(value: &str) -> String {
    word_for(value, SHELL)
}

fn word_for(value: &str, shell: Shell) -> String {
    match shell {
        Shell::Posix => posix_word(value),
        Shell::Windows => windows_word(value),
    }
}

/// A POSIX shell leaves these characters unchanged anywhere in a word, and
/// `=` after the first character. Any other word is single-quoted, which a
/// POSIX shell passes through unchanged.
fn posix_word(value: &str) -> String {
    let plain = !value.is_empty()
        && !value.starts_with('=')
        && value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "_@%+=:,./-".contains(c));
    if plain {
        value.into()
    } else {
        format!("'{}'", value.replace('\'', r"'\''"))
    }
}

/// Paths keep `\`, `:`, and `~` plain, as cmd.exe and PowerShell do; `~` and
/// `=` only after the first character. Any other word is double-quoted, the
/// form both shells accept, with an embedded `"` written as `""`.
///
/// A word's trailing backslashes are written after the closing quote
/// (`"C:\my dir"\`, `"\\?\C:"\`); the command-line rules of the Universal
/// CRT (as `CommandLineToArgvW`) and PowerShell argument mode both read that
/// as one argument that ends in those backslashes.
///
/// What holds: cmd.exe and PowerShell both pass a double-quoted word with
/// spaces, `&`, `|`, `<`, `>`, `(`, `)`, `;`, `,` and `#` as one argument, and
/// toha reads `""` inside it as `"` through the Universal CRT command-line
/// rules; PowerShell reads `""` as `"` too. A backslash is literal unless it
/// precedes a `"`; trailing backslashes follow the closing quote and Windows
/// paths cannot contain `"`, so no backslash precedes a quote in a suggested
/// path.
///
/// Limits: `%` stays plain, because cmd.exe expands `%NAME%` inside double
/// quotes as well as outside. PowerShell expands `$` and backtick escapes
/// inside double quotes. A word with those characters is quoted but not
/// protected from expansion in every shell.
fn windows_word(value: &str) -> String {
    let plain = !value.is_empty()
        && !value.starts_with(['=', '~'])
        && value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "_@%+=:,./-\\~".contains(c));
    if plain {
        return value.into();
    }
    // A backslash before the closing quote would escape it, so the trailing
    // backslashes follow the closing quote.
    let body = value.trim_end_matches('\\');
    let trailing = &value[body.len()..];
    format!("\"{}\"{trailing}", body.replace('"', "\"\""))
}

fn target(path: &Path) -> String {
    word(path_value(&path.to_string_lossy(), SHELL))
}

/// One operand of a suggested command: its value and how it is written.
pub struct Operand {
    value: String,
    written: String,
}
pub fn value(value: &str) -> Operand {
    Operand {
        value: value.into(),
        written: word(value),
    }
}
fn path_operand(path: &Path) -> Operand {
    file_operand(&path.to_string_lossy())
}
/// A file or folder operand, without trailing separators.
fn file_operand(path: &str) -> Operand {
    value(path_value(path, SHELL))
}
/// A placeholder such as `<TEMPLATE>`, written as is.
pub fn placeholder(name: &str) -> Operand {
    Operand {
        value: name.into(),
        written: name.into(),
    }
}
/// Whether operands must follow `--` to be read as operands.
fn needs_separator(operands: &[Operand]) -> bool {
    operands
        .iter()
        .any(|operand| operand.value.starts_with('-'))
}
/// `toha <command> <options> [--] <operands>`.
pub fn toha(command: &str, options: &[String], operands: &[Operand]) -> String {
    let mut words = vec!["toha".to_string(), command.to_string()];
    words.extend(options.iter().cloned());
    if needs_separator(operands) {
        words.push("--".into());
    }
    words.extend(operands.iter().map(|operand| operand.written.clone()));
    words.join(" ")
}
/// A value in a suggested command: one the caller gave, or a placeholder
/// such as `<TEMPLATE>` for one the caller chooses.
#[derive(Clone, Copy)]
pub enum Arg<'a> {
    Given(&'a str),
    Placeholder(&'static str),
}
impl Arg<'_> {
    fn operand(self) -> Operand {
        match self {
            Self::Given(given) => value(given),
            Self::Placeholder(name) => placeholder(name),
        }
    }
}
fn option_value(flag: &str, value: Arg) -> String {
    match value {
        Arg::Placeholder(name) => format!("{flag} {name}"),
        Arg::Given(value) if value.starts_with('-') && value != "-" => {
            format!("{flag}={}", word(path_value(value, SHELL)))
        }
        Arg::Given(value) => format!("{flag} {}", word(path_value(value, SHELL))),
    }
}

/// The parsed `stage` or `apply` request, from which suggested commands are
/// built.
#[derive(Clone, Copy)]
pub enum Invocation<'a> {
    Stage {
        template: Arg<'a>,
        path: &'a Path,
        output: Option<Option<&'a str>>,
    },
    Apply {
        template: Option<Arg<'a>>,
        path: &'a Path,
        answers: Option<Arg<'a>>,
        force: bool,
        dry_run: bool,
        trust: bool,
    },
}
impl<'a> Invocation<'a> {
    fn verb(&self) -> &'static str {
        match self {
            Self::Stage { .. } => "stage",
            Self::Apply { .. } => "apply",
        }
    }
    fn template(&self) -> Option<&str> {
        match self {
            Self::Stage {
                template: Arg::Given(template),
                ..
            }
            | Self::Apply {
                template: Some(Arg::Given(template)),
                ..
            } => Some(template),
            _ => None,
        }
    }
    fn without_dry_run(mut self) -> Self {
        if let Self::Apply { dry_run, .. } = &mut self {
            *dry_run = false;
        }
        self
    }
    /// The request in canonical form: options first, in long form.
    pub fn command(&self) -> String {
        self.command_with_options(&[])
    }
    fn command_with_options(&self, extra_options: &[String]) -> String {
        match *self {
            Self::Stage {
                template,
                path,
                output,
            } => {
                let operands = [template.operand(), path_operand(path)];
                let option = output.map(|file| match file {
                    Some(file) => format!("--async={}", word(file)),
                    None => "--async".to_string(),
                });
                match option {
                    // `--async` takes an optional value, so it follows the
                    // operands unless they need `--`.
                    Some(option) if !needs_separator(&operands) => {
                        format!("{} {option}", toha("stage", &[], &operands))
                    }
                    option => toha("stage", &option.into_iter().collect::<Vec<_>>(), &operands),
                }
            }
            Self::Apply {
                template,
                path,
                answers,
                force,
                dry_run,
                trust,
            } => {
                let mut options = extra_options.to_vec();
                if let Some(answers) = answers {
                    options.push(option_value("--answers", answers));
                }
                for (set, flag) in [
                    (force, "--force"),
                    (trust, "--trust"),
                    (dry_run, "--dry-run"),
                ] {
                    if set {
                        options.push(flag.to_string());
                    }
                }
                let operands: Vec<Operand> = template
                    .map(Arg::operand)
                    .into_iter()
                    .chain([path_operand(path)])
                    .collect();
                toha("apply", &options, &operands)
            }
        }
    }
}

fn abort(path: &Path) -> String {
    toha("abort", &[], &[path_operand(path)])
}
fn apply_staged(path: &Path) -> String {
    toha("apply", &[], &[path_operand(path)])
}
fn continue_prompting(path: &Path) -> String {
    toha("continue", &[], &[path_operand(path)])
}
fn continue_answers(path: &Path) -> String {
    toha(
        "continue",
        &[],
        &[path_operand(path), placeholder("<ANSWERS>")],
    )
}
fn apply_dry_run(path: &Path) -> String {
    toha("apply", &["--dry-run".to_string()], &[path_operand(path)])
}

/// The template hint line of an answers document, with the formal name quoted as
/// JSON.
fn answers_hint(template: &str) -> String {
    format!(
        "  {{\"template\": {}, \"answers\": {{ ... }}}}",
        serde_json::to_string(template).expect("template string")
    )
}

/// The agent instruction that follows a question batch: answer it with an
/// answers document that names the template, through `continue PATH FILE`.
pub fn answer_batch(path: &Path, template: &str) -> String {
    [
        "answer these questions with an answers document:".to_string(),
        answers_hint(template),
        format!(
            "then run: {} (- reads standard input)",
            continue_answers(path)
        ),
    ]
    .join("\n")
}

/// `apply PATH` found the staged interview incomplete. It names `continue PATH
/// FILE` for an answers document and `continue PATH` for a terminal, then
/// `apply PATH` to write the files.
pub fn apply_incomplete_agent(path: &Path, template: &str) -> String {
    [
        format!("the interview at {} has questions remaining", target(path)),
        "answer these questions with an answers document:".to_string(),
        answers_hint(template),
        format!(
            "to answer the current batch: {} (- reads standard input)",
            continue_answers(path)
        ),
        format!(
            "to answer in a terminal instead: {}",
            continue_prompting(path)
        ),
        format!("then write its files: {}", apply_staged(path)),
    ]
    .join("\n")
}

/// `continue PATH FILE` completed the interview: the instructions name
/// `apply PATH --dry-run` to preview and `apply PATH` to write. No batch follows.
pub fn continue_complete(path: &Path) -> String {
    [
        format!("the interview at {} is complete", target(path)),
        format!("to see the files it will write: {}", apply_dry_run(path)),
        format!("to write them: {}", apply_staged(path)),
    ]
    .join("\n")
}

fn finish(path: &Path, progress: Progress) -> String {
    let apply = apply_staged(path);
    let resume = continue_prompting(path);
    match progress {
        Progress::Complete => format!("to finish the staged interview: {apply}"),
        Progress::Incomplete => {
            format!("to finish the staged interview: {resume}, then {apply}")
        }
        Progress::Ended => {
            format!(
                "the staged interview was ended by a flow node; to start over: {}",
                abort(path)
            )
        }
        Progress::Unknown => {
            format!("to finish the staged interview: {resume} if questions remain, then {apply}")
        }
    }
}

fn remaining(path: &Path) -> String {
    format!(
        "to answer them: {} in a terminal, or {} with an answers document (- reads standard input)",
        continue_prompting(path),
        continue_answers(path)
    )
}

/// `stage` or `apply` named a template other than the staged one.
pub fn other_template(
    invocation: &Invocation,
    path: &Path,
    staged: &str,
    formal: &str,
    progress: Progress,
) -> String {
    let arg = invocation.template().unwrap_or(formal);
    let named = if arg == formal {
        arg.to_string()
    } else {
        format!("{arg} ({formal})")
    };
    [
        format!(
            "an interview for {staged} is staged at {}; {named} is a different template",
            target(path)
        ),
        format!(
            "to {} {} instead: {}, then {}",
            invocation.verb(),
            word(arg),
            abort(path),
            invocation.command()
        ),
        finish(path, progress),
    ]
    .join("\n")
}

/// `stage` named the template whose interview is already staged.
pub fn already_staged(
    invocation: &Invocation,
    path: &Path,
    staged: &str,
    progress: Progress,
) -> String {
    let p = target(path);
    let mut lines = match progress {
        Progress::Complete => vec![
            format!("an interview for {staged} is already staged at {p} and is complete"),
            format!("to write its files: {}", apply_staged(path)),
        ],
        Progress::Incomplete => vec![
            format!(
                "an interview for {staged} is already staged at {p} and has questions remaining"
            ),
            remaining(path),
            format!("then write its files: {}", apply_staged(path)),
        ],
        Progress::Ended => vec![format!(
            "an interview for {staged} staged at {p} was ended by a flow node"
        )],
        Progress::Unknown => vec![
            format!("an interview for {staged} is already staged at {p}"),
            finish(path, progress),
        ],
    };
    lines.push(format!(
        "to start it again: {}, then {}",
        abort(path),
        invocation.command()
    ));
    lines.join("\n")
}

/// A flow `stop`/`abort` ended the interview. The notice names what did not
/// happen, and for an abort that the staged interview was discarded.
pub fn flow_ended(ended: &toha::Ended) -> String {
    let (verb, tail) = match ended.kind() {
        toha::EndKind::Stop => ("stopped", "no files were written and no hooks ran"),
        toha::EndKind::Abort => (
            "aborted",
            "no files were written, no hooks ran, and the staged interview was discarded",
        ),
    };
    match ended.label() {
        Some(label) => format!("{verb}: {label} — {tail}"),
        None => format!("{verb} — {tail}"),
    }
}

/// `continue` found the staged interview complete.
pub fn complete(path: &Path) -> String {
    format!(
        "the interview at {} is complete; to write its files: {}",
        target(path),
        apply_staged(path)
    )
}

/// `continue PATH FILE` was given for a complete staged interview. It refuses
/// before reading the document and names `apply PATH --dry-run` and `apply PATH`.
pub fn complete_answers_unused(path: &Path) -> String {
    [
        format!(
            "the interview at {} is complete, so the answers document is not used",
            target(path)
        ),
        format!("to preview the files: {}", apply_dry_run(path)),
        format!("to write them: {}", apply_staged(path)),
    ]
    .join("\n")
}

/// An answers document was given for a staged interview a flow node already
/// ended. Behavior 23: a submission after a terminal interview is refused.
pub fn ended_answers_unused(path: &Path, staged: &str, kind: toha::EndKind) -> String {
    let restage = Invocation::Stage {
        template: Arg::Given(formal_for("stage", staged)),
        path,
        output: None,
    };
    let verb = match kind {
        toha::EndKind::Stop => "was stopped by a flow node",
        toha::EndKind::Abort => "was aborted by a flow node",
    };
    [
        format!(
            "the interview at {} {verb}, so the answers document is not used",
            target(path)
        ),
        format!("to start over: {}, then {}", abort(path), restage.command()),
    ]
    .join("\n")
}

/// A staged record at `path` that no longer replays against its template, and
/// the commands that start the interview over.
pub fn replay_failed(path: &Path, staged: &str, error: &str) -> String {
    let restage = Invocation::Stage {
        template: Arg::Given(formal_for("stage", staged)),
        path,
        output: None,
    };
    [
        format!(
            "the staged interview at {} cannot be resumed: {error}",
            target(path)
        ),
        format!("to start over: {}, then {}", abort(path), restage.command()),
    ]
    .join("\n")
}

/// The rejections of an answers document for the interview at `path`, each
/// rejection of a different answer for an answered question followed by the
/// commands that change it.
pub fn explain_rejections(
    rejections: &toha::Rejections,
    path: &Path,
    staged: &str,
) -> toha::Rejections {
    let restage = Invocation::Stage {
        template: Arg::Given(formal_for("stage", staged)),
        path,
        output: Some(None),
    };
    rejections
        .iter()
        .cloned()
        .map(|mut rejection| {
            if rejection.kind == toha::RejectionKind::Answered {
                rejection.message = format!(
                    "{}; to change it: {}, then {}",
                    rejection.message,
                    abort(path),
                    restage.command()
                );
            }
            rejection
        })
        .collect()
}

/// The commands a scripted `staged` refusal lists: answer the staged interview
/// with an answers document, write it, or discard it.
pub fn staged_commands(path: &Path) -> Vec<String> {
    vec![continue_answers(path), apply_staged(path), abort(path)]
}

/// `continue` without an answers document has no terminal to prompt in.
pub fn continue_no_terminal(path: &Path) -> String {
    [
        format!(
            "no terminal to prompt in for the interview at {}",
            target(path)
        ),
        format!(
            "to answer the current batch: {} with an answers document (- reads standard input)",
            continue_answers(path)
        ),
    ]
    .join("\n")
}

/// `continue`, `apply`, or `abort` found no staged interview.
pub fn nothing_staged(path: &Path) -> String {
    let template = placeholder("<TEMPLATE>");
    [
        format!("no interview is staged at {}", target(path)),
        format!(
            "to start one: {}",
            toha(
                "stage",
                &[],
                &[placeholder("<TEMPLATE>"), path_operand(path)]
            )
        ),
        format!(
            "to start one and write its files: {}",
            toha("apply", &[], &[template, path_operand(path)])
        ),
    ]
    .join("\n")
}

/// `stage` or `apply` with a template has no terminal to prompt in.
pub fn no_terminal(template: &str, path: &Path) -> String {
    let stage = Invocation::Stage {
        template: Arg::Given(template),
        path,
        output: Some(None),
    };
    let apply = Invocation::Apply {
        template: Some(Arg::Given(template)),
        path,
        answers: Some(Arg::Placeholder("<FILE>")),
        force: false,
        dry_run: false,
        trust: false,
    };
    [
        "no terminal to prompt in".to_string(),
        format!(
            "to stage the interview and emit its question batch: {}",
            stage.command()
        ),
        format!(
            "to answer from an answers document and write the files: {}",
            apply.command()
        ),
    ]
    .join("\n")
}

/// `apply <path> --answers <file>` names no template.
pub fn answers_without_template(
    path: &Path,
    answers: &str,
    staged: Option<(&str, Progress)>,
) -> String {
    let apply_new = |template| Invocation::Apply {
        template: Some(template),
        path,
        answers: Some(Arg::Given(answers)),
        force: false,
        dry_run: false,
        trust: false,
    };
    let mut lines = vec!["--answers requires a template".to_string()];
    match staged {
        Some((_, Progress::Complete)) => lines.push(format!(
            "the staged interview at {} is complete; to write its files: {}",
            target(path),
            apply_staged(path)
        )),
        Some((staged, Progress::Ended)) => {
            lines.push(format!(
                "the staged interview at {} was ended by a flow node; to start over: {}, then {}",
                target(path),
                abort(path),
                Invocation::Stage {
                    template: Arg::Given(formal_for("stage", staged)),
                    path,
                    output: None,
                }
                .command()
            ));
        }
        Some((staged, _)) => {
            lines.push(format!(
                "to answer the staged interview: {}, then {}",
                toha(
                    "continue",
                    &[],
                    &[path_operand(path), file_operand(answers)]
                ),
                apply_staged(path)
            ));
            lines.push(format!(
                "to answer it and write its files in one command: {}",
                apply_new(Arg::Given(formal_for("apply", staged))).command()
            ));
        }
        None => lines.push(format!(
            "to answer a new interview and write its files: {}",
            apply_new(Arg::Placeholder("<TEMPLATE>")).command()
        )),
    }
    lines.join("\n")
}

/// `apply` did not run hooks of an untrusted template. `changed` marks a
/// template whose stored approval no longer matches its hooks.
pub fn needs_trust(invocation: &Invocation, installed: Option<&str>, changed: bool) -> String {
    trust_lines(
        "hooks will not run without --trust\nto run them this time: ",
        invocation,
        installed,
        changed,
    )
}

/// `apply --dry-run` planned hooks of an untrusted template, which the same
/// command without `--dry-run` refuses to run. `changed` marks a template
/// whose stored approval no longer matches its hooks.
pub fn dry_run_needs_trust(
    invocation: &Invocation,
    installed: Option<&str>,
    changed: bool,
) -> String {
    trust_lines(
        "hooks need trust; to run them: ",
        &invocation.without_dry_run(),
        installed,
        changed,
    )
}

/// `lead` followed by the command with `--trust`, and the `templates trust`
/// command that approves an installed template for every run. When `changed`, a
/// leading line states that the hooks changed since approval.
fn trust_lines(
    lead: &str,
    invocation: &Invocation,
    installed: Option<&str>,
    changed: bool,
) -> String {
    let mut trusted = *invocation;
    if let Invocation::Apply { trust, .. } = &mut trusted {
        *trust = true;
    }
    let mut lines = Vec::new();
    if changed {
        lines.push("hooks changed since approval".to_string());
    }
    lines.push(format!("{lead}{}", trusted.command()));
    if let Some(formal) = installed {
        lines.push(format!(
            "to trust {formal} for every run: {}",
            toha(
                "templates trust",
                &[],
                &[value(formal_for("templates trust", formal))]
            )
        ));
    }
    lines.join("\n")
}

/// `templates trust` could not read the installed executable surface of
/// `formal`, so it cannot be approved.
pub fn surface_unreadable(formal: &str, error: &toha::ReviewError) -> String {
    format!("cannot read the installed hooks of {formal}: {error}")
}

/// The installed hooks a `templates trust` grant approved, echoed on standard
/// error as an audit of what was approved. Presentation only: it compares
/// nothing and does not decide trust.
pub fn approved_surface(surface: &toha::HookSurface) -> String {
    let mut lines = vec!["approved surface:".to_string()];
    for (index, view) in surface.views().iter().enumerate() {
        // An interview hook node wraps its command in `hook`; a top-level hook
        // is the command itself.
        let command = view.node.get("hook").unwrap_or(&view.node);
        let mut parts = Vec::new();
        if let Some(script) = command.get("script").and_then(serde_json::Value::as_str) {
            parts.push(format!("script: {script}"));
        }
        if let Some(run) = command.get("run") {
            parts.push(format!("run: {run}"));
        }
        if let Some(args) = command.get("args") {
            parts.push(format!("args: {args}"));
        }
        let detail = if parts.is_empty() {
            command.to_string()
        } else {
            parts.join("  ")
        };
        lines.push(format!("  hook {}  {detail}", index + 1));
    }
    lines.join("\n")
}

/// `apply` found target files that exist.
pub fn conflicts(invocation: &Invocation) -> String {
    let mut forced = *invocation;
    if let Invocation::Apply { force, .. } = &mut forced {
        *force = true;
    }
    format!("to overwrite them: {}", forced.command())
}

/// A one-shot update must retain its mode and render inputs on a force retry.
pub fn update_drift(
    invocation: &Invocation,
    baseline: bool,
    reanswer: bool,
    input: &[std::path::PathBuf],
    parts: &toha::parts::Selection,
) -> String {
    let mut options = vec![if baseline { "--baseline" } else { "--update" }.into()];
    if reanswer {
        options.push("--reanswer".into());
    }
    for path in input {
        options.push(option_value("--input", Arg::Given(&path.to_string_lossy())));
    }
    for (flag, values) in [("--with", &parts.with), ("--without", &parts.without)] {
        for value in values {
            options.push(format!("{flag} {}", word(value)));
        }
    }
    let mut forced = *invocation;
    if let Invocation::Apply { force, .. } = &mut forced {
        *force = true;
    }
    format!(
        "to overwrite them: {}",
        forced.command_with_options(&options)
    )
}

/// Region force cannot authorize an edit-to-whole transition's outside bytes.
pub fn update_outside_conflict() -> &'static str {
    "edit and commit the listed project files so their content outside previously owned edits \
     matches the planned whole-file content outside its owned edits, then retry the same apply command; \
     --force cannot resolve this conflict"
}

/// `templates add` was given a name, which is not an address.
pub fn add_needs_address(name: &str, folder_exists: bool) -> String {
    let mut lines = vec![
        "add requires a git address or folder".to_string(),
        format!(
            "to see installed templates: {}",
            toha("templates list", &[], &[])
        ),
    ];
    if folder_exists {
        lines.push(format!(
            "to add the folder {name}: {}",
            toha("templates add", &[], &[value(&format!("./{name}"))])
        ));
    }
    lines.push(format!(
        "to add from a git address or folder: {}",
        toha("templates add", &[], &[placeholder("<ADDRESS>")])
    ));
    lines.join("\n")
}

/// `templates add --alias` found more than one template at the address.
pub fn alias_needs_one_template(alias: &str, addresses: &[String]) -> String {
    let options = [format!("--alias {}", word(alias))];
    std::iter::once("--alias requires exactly one template".to_string())
        .chain(addresses.iter().map(|address| {
            format!(
                "to add {address} as {alias}: {}",
                toha("templates add", &options, &[value(address)])
            )
        }))
        .collect::<Vec<_>>()
        .join("\n")
}

/// `templates alias` was given an alias that names another template.
pub fn alias_in_use(template: &str, alias: &str, removable: bool) -> String {
    let mut lines = vec!["alias is in use".to_string()];
    if removable {
        lines.push(format!(
            "to move it to {template}: {}, then {}",
            toha(
                "templates alias",
                &[format!("--remove {}", word(alias))],
                &[]
            ),
            toha("templates alias", &[], &[value(template), value(alias)])
        ));
    }
    lines.push(format!(
        "to choose another alias: {}",
        toha(
            "templates alias",
            &[],
            &[value(template), placeholder("<ALIAS>")]
        )
    ));
    lines.join("\n")
}

/// A `templates` command that changes the user registry named a template from
/// another layer.
pub fn not_in_user_registry(name: &str) -> String {
    [
        format!("not installed in user registry: {name}"),
        format!(
            "to see the layer of each template: {}",
            toha("templates list", &["--json".into()], &[])
        ),
    ]
    .join("\n")
}

/// A template name matched more than one installed template.
pub fn ambiguous(name: &str, matches: &[String], retry: &[String]) -> String {
    let mut lines = vec![format!("ambiguous template name: {name}")];
    for (index, formal) in matches.iter().enumerate() {
        if let Some(command) = retry.get(index) {
            lines.push(format!("to use {formal}: {command}"));
        }
        lines.push(format!(
            "to give {formal} an alias: {}",
            toha(
                "templates alias",
                &[],
                &[
                    value(formal_for("templates alias", formal)),
                    placeholder("<ALIAS>")
                ]
            )
        ));
    }
    lines.join("\n")
}

#[cfg(test)]
mod tests {
    use super::{Shell, formal_for, path_value, plain_formal, surface_unreadable, word_for};

    #[test]
    fn surface_unreadable_names_the_template_and_the_error() {
        let error = toha::ReviewError::Escape(std::path::PathBuf::from("/outside/x.sh"));
        let message = surface_unreadable("acme", &error);
        assert!(
            message.starts_with("cannot read the installed hooks of acme:"),
            "{message}"
        );
        assert!(message.contains("escapes the template root"), "{message}");
    }

    #[test]
    fn each_command_gets_the_formal_name_form_it_accepts() {
        let extended = r"\\?\D:\a\template";
        for command in ["stage", "apply", "templates add"] {
            assert_eq!(formal_for(command, extended), r"D:\a\template", "{command}");
        }
        for command in [
            "templates remove",
            "templates update",
            "templates alias",
            "templates trust",
            "templates untrust",
        ] {
            assert_eq!(formal_for(command, extended), extended, "{command}");
        }
        assert_eq!(
            word_for(formal_for("templates remove", extended), Shell::Windows),
            r#""\\?\D:\a\template""#
        );
    }

    #[test]
    fn path_values_end_without_a_separator_except_a_root() {
        assert_eq!(path_value(r"C:\my dir\", Shell::Windows), r"C:\my dir");
        assert_eq!(path_value("C:/my dir/", Shell::Windows), "C:/my dir");
        assert_eq!(path_value(r"C:\", Shell::Windows), r"C:\");
        assert_eq!(path_value("C:/", Shell::Windows), "C:/");
        assert_eq!(path_value(r"\", Shell::Windows), r"\");
        assert_eq!(path_value("notes/", Shell::Posix), "notes");
        assert_eq!(path_value("/", Shell::Posix), "/");
        assert_eq!(path_value(r"a\", Shell::Posix), r"a\");
        assert_eq!(
            word_for(path_value(r"C:\my dir\", Shell::Windows), Shell::Windows),
            r#""C:\my dir""#
        );
        assert_eq!(
            word_for(path_value(r"C:\", Shell::Windows), Shell::Windows),
            r"C:\"
        );
        assert_eq!(path_value("", Shell::Windows), "");
        assert_eq!(path_value("", Shell::Posix), "");
        assert_eq!(path_value(r"\\?\C:\", Shell::Windows), r"\\?\C:\");
        assert_eq!(path_value(r"\\?\C:\dir\", Shell::Windows), r"\\?\C:\dir");
        assert_eq!(path_value(r"\\?\C:\\", Shell::Windows), r"\\?\C:\");
    }

    #[test]
    fn windows_quoted_words_keep_trailing_backslashes_outside_the_quotes() {
        assert_eq!(word_for(r"\\?\C:\", Shell::Windows), r#""\\?\C:"\"#);
        assert_eq!(word_for(r"C:\my dir\", Shell::Windows), r#""C:\my dir"\"#);
        assert_eq!(word_for(r"C:\my dir\\", Shell::Windows), r#""C:\my dir"\\"#);
        assert_eq!(word_for(r"C:\my dir", Shell::Windows), r#""C:\my dir""#);
        assert_eq!(word_for("", Shell::Windows), r#""""#);
    }

    #[test]
    fn extended_drive_paths_are_named_by_their_drive_path() {
        assert_eq!(plain_formal(r"\\?\D:\a\template"), r"D:\a\template");
        for kept in [
            r"\\?\UNC\server\share",
            r"\\server\share",
            "/srv/template",
            "gh:org/repo#one",
        ] {
            assert_eq!(plain_formal(kept), kept);
        }
    }

    const SPECIAL: [&str; 19] = [
        "", "#x", "$x", "`x`", "a*", "a?", "[a]", "a!", "a&b", "a;b", "a|b", "<a>", "(a)", "{a}",
        "a'b", "a\"b", "=x", "a b", "~/x",
    ];

    #[test]
    fn posix_words_a_shell_would_change_are_single_quoted() {
        for plain in [
            "notes",
            "a/b.json",
            "x=y",
            "gh:org/repo@main",
            "-",
            "a,b%c+d",
        ] {
            assert_eq!(word_for(plain, Shell::Posix), plain);
        }
        for special in SPECIAL.into_iter().chain([r"a\b", "a~b"]) {
            let quoted = word_for(special, Shell::Posix);
            assert!(
                quoted.starts_with('\'') && quoted.ends_with('\''),
                "{special}: {quoted}"
            );
        }
        assert_eq!(word_for("a'b", Shell::Posix), r"'a'\''b'");
    }

    #[test]
    fn windows_words_keep_paths_plain_and_double_quote_the_rest() {
        for plain in [
            r"C:\work",
            r"C:\Users\RUNNER~1\AppData\Local\Temp\.tmpA1",
            r"D:\a\toha\tests\fixtures\text-basic\template",
            "file:///C:/Users/x/remote",
            "notes",
            "a/b.json",
            "x=y",
            "-",
        ] {
            assert_eq!(word_for(plain, Shell::Windows), plain);
        }
        for special in SPECIAL {
            let quoted = word_for(special, Shell::Windows);
            assert!(
                quoted.starts_with('"') && quoted.ends_with('"'),
                "{special}: {quoted}"
            );
        }
        assert_eq!(word_for(r"C:\my dir", Shell::Windows), r#""C:\my dir""#);
        assert_eq!(word_for(r#"a"b"#, Shell::Windows), r#""a""b""#);
    }
}