toha 0.2.0

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
use crate::{
    Dirs,
    cli::{bundled, guidance},
};
use clap::{Args, Subcommand};
use std::{
    fs,
    path::{Path, PathBuf},
};
use toha::{
    Template, config,
    registry::{self, Entry, Layer, Registry, RegistryFile, ResolveError},
    source::{self, Address, RefKind},
};

#[derive(Args)]
pub struct TemplatesArgs {
    #[command(subcommand)]
    command: TemplatesCommand,
}
#[derive(Subcommand)]
enum TemplatesCommand {
    /// Install every template in a repository, or the one template at #<path>.
    Add {
        /// Git address or local folder.
        address: String,
        /// Alias for the template; fails when the address holds more than one template.
        #[arg(short, long)]
        alias: Option<String>,
        /// Approve the added templates' current hooks in the user registry.
        #[arg(long)]
        trust: bool,
    },
    /// List available templates with formal name, short name, aliases, and trust.
    List {
        /// Only templates from the local layer.
        #[arg(short, long, conflicts_with_all=["system", "user"])]
        local: bool,
        /// Only templates from the system layer.
        #[arg(short, long, conflicts_with = "user")]
        system: bool,
        /// Only templates from the user layer.
        #[arg(short, long)]
        user: bool,
        /// Print the list as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Move installed git templates that follow a branch to its newest commit.
    Update {
        /// Template to update; all installed git templates when absent.
        template: Option<String>,
    },
    /// Uninstall a template and delete its entry from the user registry.
    Remove {
        /// Template to uninstall.
        template: String,
    },
    /// Add or remove an alias in the user registry.
    Alias {
        /// Formal or short name of the template.
        #[arg(requires = "alias", required_unless_present = "remove")]
        template: Option<String>,
        /// Alias to add.
        #[arg(requires = "template")]
        alias: Option<String>,
        /// Alias to remove.
        #[arg(short, long, conflicts_with_all=["template", "alias"], value_name = "ALIAS")]
        remove: Option<String>,
    },
    /// Approve the installed hooks of a template so its apply runs them.
    Trust {
        /// Formal, short, or alias name of an installed template.
        template: String,
    },
    /// Revoke approval of a template's hooks.
    Untrust {
        /// Formal, short, or alias name of an installed template.
        template: String,
    },
}
#[derive(Debug)]
pub enum CommandError {
    Error(String),
    Ambiguous { name: String, matches: Vec<String> },
}
impl From<ResolveError> for CommandError {
    fn from(value: ResolveError) -> Self {
        match value {
            ResolveError::NotFound(name) => Self::Error(format!("template not found: {name}")),
            ResolveError::Ambiguous { name, matches } => Self::Ambiguous { name, matches },
        }
    }
}
impl CommandError {
    fn text(message: impl ToString) -> Self {
        Self::Error(message.to_string())
    }
}
struct Context {
    dirs: Dirs,
    config: config::Config,
    system: RegistryFile,
    user: RegistryFile,
    local: RegistryFile,
    registry: Registry,
}
impl Context {
    fn load(dirs: Dirs, cwd: &Path) -> Result<Self, CommandError> {
        let config = config::load(&dirs.config_paths(), cwd).map_err(CommandError::text)?;
        let system = RegistryFile::load(&dirs.system_data.join("templates.yml"), Layer::System)
            .map_err(CommandError::text)?;
        let user = RegistryFile::load(&dirs.user_data.join("templates.yml"), Layer::User)
            .map_err(CommandError::text)?;
        let local = if let Some(root) = config.local_templates_paths.first() {
            RegistryFile::load(&root.join("templates.yml"), Layer::Local)
                .map_err(CommandError::text)?
        } else {
            RegistryFile::default()
        };
        let mut registry = Registry::merge(&system, &user, &local).map_err(CommandError::text)?;
        registry
            .discover(&config.templates_paths, &dirs.user_data)
            .map_err(CommandError::text)?;
        let missing = registry
            .apply_local_aliases(&local)
            .map_err(CommandError::text)?;
        for (alias, formal) in missing {
            eprintln!("warning: local alias {alias} names {formal}, which is not installed");
        }
        Ok(Self {
            dirs,
            config,
            system,
            user,
            local,
            registry,
        })
    }
    fn write(&self, file: &RegistryFile) -> Result<(), CommandError> {
        file.write_atomic(&self.dirs.user_data.join("templates.yml"))
            .map_err(CommandError::text)
    }
    fn resolve_user(&self, name: &str) -> Result<(String, Entry), CommandError> {
        let resolved = self.registry.resolve(name)?;
        self.user
            .templates
            .get(&resolved.formal_name)
            .cloned()
            .map(|entry| (resolved.formal_name, entry))
            .ok_or_else(|| CommandError::text(guidance::not_in_user_registry(name)))
    }
}
fn find_templates(root: &Path, selected: Option<&str>) -> Result<Vec<PathBuf>, CommandError> {
    let root = root.canonicalize().map_err(CommandError::text)?;
    let start = if let Some(path) = selected {
        root.join(path)
    } else {
        root.clone()
    };
    let start = start.canonicalize().map_err(CommandError::text)?;
    if !start.starts_with(&root) {
        return Err(CommandError::text("template path leaves repository"));
    }
    let mut found = Vec::new();
    fn visit(
        dir: &Path,
        root: &Path,
        seen: &mut std::collections::HashSet<PathBuf>,
        found: &mut Vec<PathBuf>,
    ) -> Result<(), CommandError> {
        let canonical = dir.canonicalize().map_err(CommandError::text)?;
        if !canonical.starts_with(root) {
            return Err(CommandError::text("template path leaves repository"));
        }
        if !seen.insert(canonical.clone()) {
            return Ok(());
        }
        if canonical.join("template.yml").is_file() {
            found.push(canonical);
            return Ok(());
        }
        for child in fs::read_dir(&canonical).map_err(CommandError::text)? {
            let child = child.map_err(CommandError::text)?.path();
            if child.file_name().is_some_and(|n| n == ".git") {
                continue;
            }
            if child.is_dir() {
                visit(&child, root, seen, found)?;
            }
        }
        Ok(())
    }
    visit(
        &start,
        &root,
        &mut std::collections::HashSet::new(),
        &mut found,
    )?;
    found.sort();
    if selected.is_some() && found.len() != 1 {
        return Err(CommandError::text("#path must select exactly one template"));
    }
    if found.is_empty() {
        return Err(CommandError::text("no template found"));
    }
    Ok(found)
}
fn clone_sibling(
    address: &Address,
    install: &Path,
) -> Result<(tempfile::TempDir, source::Fetched), CommandError> {
    let parent = install
        .parent()
        .ok_or_else(|| CommandError::text("install path has no parent"))?;
    fs::create_dir_all(parent).map_err(CommandError::text)?;
    let container = tempfile::Builder::new()
        .prefix(".toha-clone-")
        .tempdir_in(parent)
        .map_err(CommandError::text)?;
    let fetched =
        source::fetch(address, &container.path().join("repo")).map_err(CommandError::text)?;
    Ok((container, fetched))
}
struct SwappedClone {
    install: PathBuf,
    backup: Option<tempfile::TempDir>,
}
impl SwappedClone {
    fn rollback(self) -> Result<(), CommandError> {
        fs::remove_dir_all(&self.install).map_err(CommandError::text)?;
        if let Some(backup) = self.backup {
            fs::rename(backup.path().join("repo"), &self.install).map_err(CommandError::text)?;
            backup.close().map_err(CommandError::text)?;
        }
        Ok(())
    }
    fn finish(self) -> Result<(), CommandError> {
        if let Some(backup) = self.backup {
            backup.close().map_err(CommandError::text)?;
        }
        Ok(())
    }
}
fn swap_clone(temp: &Path, install: &Path) -> Result<SwappedClone, CommandError> {
    let backup = if install.exists() {
        let parent = install
            .parent()
            .ok_or_else(|| CommandError::text("install path has no parent"))?;
        let holder = tempfile::Builder::new()
            .prefix(".toha-backup-")
            .tempdir_in(parent)
            .map_err(CommandError::text)?;
        fs::rename(install, holder.path().join("repo")).map_err(CommandError::text)?;
        Some(holder)
    } else {
        None
    };
    if let Err(error) = fs::rename(temp, install) {
        if let Some(holder) = backup.as_ref() {
            fs::rename(holder.path().join("repo"), install).map_err(CommandError::text)?;
        }
        return Err(CommandError::text(error));
    }
    Ok(SwappedClone {
        install: install.into(),
        backup,
    })
}
fn install_staged(
    ctx: &Context,
    staged: &[(tempfile::TempDir, PathBuf)],
    registry: &RegistryFile,
) -> Result<(), CommandError> {
    let mut swapped = Vec::new();
    for (clone, install) in staged {
        match swap_clone(&clone.path().join("repo"), install) {
            Ok(swap) => swapped.push(swap),
            Err(error) => {
                for swap in swapped.into_iter().rev() {
                    swap.rollback()?;
                }
                return Err(error);
            }
        }
    }
    if let Err(error) = ctx.write(registry) {
        for swap in swapped.into_iter().rev() {
            swap.rollback()?;
        }
        return Err(error);
    }
    for swap in swapped {
        swap.finish()?;
    }
    Ok(())
}
fn add(
    ctx: &Context,
    address: &str,
    alias: Option<String>,
    trust: bool,
    cwd: &Path,
) -> Result<Vec<String>, CommandError> {
    if alias.as_deref().is_some_and(|value| !valid_alias(value)) {
        return Err(CommandError::text("invalid alias"));
    }
    let parsed = source::parse(address, &ctx.config.hosts, cwd, &ctx.dirs.home)
        .map_err(CommandError::text)?;
    let (root, clone, commit) = match &parsed {
        Address::Git { .. } => {
            let install = ctx
                .dirs
                .user_data
                .join("repos")
                .join(source::install_key(&parsed.formal_name(&ctx.config.hosts)));
            let (clone, fetched) = clone_sibling(&parsed, &install)?;
            (
                clone.path().join("repo"),
                Some((clone, install)),
                Some(fetched.commit),
            )
        }
        Address::Folder(folder) => (folder.clone(), None, None),
        Address::Name(name) => {
            return Err(CommandError::text(guidance::add_needs_address(
                name,
                cwd.join(name).is_dir(),
            )));
        }
    };
    let root = root.canonicalize().map_err(CommandError::text)?;
    let selected = if let Address::Git { path, .. } = &parsed {
        path.as_deref()
    } else {
        None
    };
    let folders = find_templates(&root, selected)?;
    if let Some(name) = alias.as_deref().filter(|_| folders.len() != 1) {
        let addresses: Vec<String> = folders
            .iter()
            .map(|folder| match &parsed {
                Address::Git { .. } => {
                    let base = address.split_once('#').map_or(address, |(base, _)| base);
                    let path = folder.strip_prefix(&root).unwrap_or(folder);
                    format!("{base}#{}", path.to_string_lossy().replace('\\', "/"))
                }
                _ => guidance::formal_for("templates add", &folder.to_string_lossy()).to_string(),
            })
            .collect();
        return Err(CommandError::text(guidance::alias_needs_one_template(
            name, &addresses,
        )));
    }
    let mut additions = Vec::new();
    let mut names = Vec::new();
    for folder in folders {
        let loaded = Template::load(&folder).map_err(CommandError::text)?;
        let name = loaded.name.clone();
        // `--trust` approves the template's current executable surface; the
        // digest authorizes its hooks only while the installed content matches.
        let approval = if trust {
            Some(
                toha::HookSurface::of(&loaded)
                    .map_err(CommandError::text)?
                    .digest(),
            )
        } else {
            None
        };
        let formal = if matches!(parsed, Address::Folder(_)) {
            folder.to_string_lossy().into_owned()
        } else {
            let base = Address::Git {
                repo: match &parsed {
                    Address::Git { repo, .. } => repo.clone(),
                    _ => unreachable!(),
                },
                reference: match &parsed {
                    Address::Git { reference, .. } => reference.clone(),
                    _ => unreachable!(),
                },
                path: None,
            }
            .formal_name(&ctx.config.hosts);
            let relative = folder.strip_prefix(&root).map_err(CommandError::text)?;
            if relative.as_os_str().is_empty() {
                base
            } else {
                format!("{base}#{}", relative.to_string_lossy().replace('\\', "/"))
            }
        };
        let path = if let Some((_, install)) = &clone {
            install.join(folder.strip_prefix(&root).map_err(CommandError::text)?)
        } else {
            folder.clone()
        };
        let entry = Entry {
            name: name.clone(),
            source: match &parsed {
                Address::Git { repo, .. } => source::without_userinfo(repo),
                Address::Folder(folder) => folder.to_string_lossy().into_owned(),
                _ => unreachable!(),
            },
            reference: match &parsed {
                Address::Git { reference, .. } => reference.clone(),
                _ => None,
            },
            commit: commit.clone(),
            path,
            aliases: alias.clone().into_iter().collect(),
            approval,
            denied: false,
        };
        additions.push((formal.clone(), entry));
        names.push((formal, name));
    }
    let mut next = ctx.user.add(additions);
    if let (Some((_, install)), Some(commit)) = (&clone, &commit) {
        let keys: Vec<_> = next
            .templates
            .iter()
            .filter(|(_, entry)| entry.path.starts_with(install))
            .map(|(formal, _)| formal.clone())
            .collect();
        for formal in keys {
            next = next
                .set_commit(&formal, commit.clone())
                .map_err(CommandError::text)?;
        }
    }
    let mut merged = ctx.registry.clone();
    for (formal, entry) in &next.templates {
        merged.entries.insert(
            formal.clone(),
            registry::Listed {
                formal_name: formal.clone(),
                entry: entry.clone(),
                layer: Layer::User,
                approval: entry.approval.clone(),
            },
        );
    }
    merged.check_aliases().map_err(CommandError::text)?;
    let mut lines = Vec::new();
    for (formal, name) in &names {
        let matching: Vec<_> = merged
            .entries
            .values()
            .filter(|e| e.entry.name == *name)
            .collect();
        if matching.len() > 1 {
            for entry in matching {
                lines.push(format!(
                    "shared short name {name}: toha templates alias {} <alias>",
                    entry.formal_name
                ));
            }
        }
        lines.push(format!("added {formal}"));
    }
    install_staged(ctx, &clone.into_iter().collect::<Vec<_>>(), &next)?;
    Ok(lines)
}
/// Whether an entry's stored approval still matches its installed executable
/// surface. An entry with no approval, or one whose installed template cannot
/// be loaded or read, is not trusted.
fn effective_trust(listed: &registry::Listed) -> bool {
    let Some(approval) = listed.approval.as_ref() else {
        return false;
    };
    let Ok(template) = Template::load(&listed.entry.path) else {
        return false;
    };
    let Ok(surface) = toha::HookSurface::of(&template) else {
        return false;
    };
    matches!(
        toha::evaluate_trust(Some(approval), &surface.digest()),
        toha::Trust::Trusted
    )
}
fn list(ctx: &Context, filter: Option<Layer>, json: bool) -> Result<Vec<String>, CommandError> {
    let entries: Vec<registry::Listed> = match filter {
        None => ctx.registry.entries.values().cloned().collect(),
        Some(Layer::System) | Some(Layer::User) => {
            let layer = filter.unwrap();
            let file = if layer == Layer::System {
                &ctx.system
            } else {
                &ctx.user
            };
            file.templates
                .iter()
                .map(|(formal, entry)| registry::Listed {
                    formal_name: formal.clone(),
                    entry: entry.clone(),
                    layer,
                    approval: entry.approval.clone(),
                })
                .collect()
        }
        Some(Layer::Local) => {
            let mut result: Vec<_> = ctx
                .local
                .templates
                .keys()
                .filter_map(|formal| ctx.registry.entries.get(formal))
                .cloned()
                .collect();
            result.extend(
                ctx.registry
                    .entries
                    .values()
                    .filter(|entry| {
                        entry.layer == Layer::Discovered
                            && !ctx.local.templates.contains_key(&entry.formal_name)
                            && ctx
                                .config
                                .local_templates_paths
                                .iter()
                                .any(|root| entry.entry.path.starts_with(root))
                    })
                    .cloned(),
            );
            result
        }
        Some(Layer::Discovered) => Vec::new(),
    };
    // D3: the unfiltered listing carries one read-only descriptor for the
    // bundled demo, in both formats, but only when no registry entry occupies the
    // reserved name — that is exactly when the fallback would resolve. It is
    // presentation only: no persisted entry and no resolution source, marked
    // `bundled` in `--json` with no registry layer, source, ref, or path, and
    // resolution never consults it.
    let show_bundled = filter.is_none()
        && matches!(
            ctx.registry.resolve(bundled::RESERVED),
            Err(ResolveError::NotFound(_))
        );
    let row = bundled::listing_row();
    if json {
        let mut values: Vec<_> = entries.iter().map(|e| serde_json::json!({ "formal_name": e.formal_name, "name": e.entry.name, "aliases": e.entry.aliases, "trusted": effective_trust(e), "layer": e.layer, "source": e.entry.source, "ref": e.entry.reference, "commit": e.entry.commit, "path": e.entry.path })).collect();
        if show_bundled {
            values.push(serde_json::json!({ "formal_name": row.formal, "name": row.short, "aliases": [], "trusted": row.trusted, "commit": bundled::commit(), "bundled": true }));
        }
        return Ok(vec![
            serde_json::to_string(&values).map_err(CommandError::text)?,
        ]);
    }
    let mut lines = vec!["FORMAL NAME\tSHORT NAME\tALIASES\tTRUSTED".into()];
    lines.extend(entries.iter().map(|e| {
        format!(
            "{}\t{}\t{}\t{}",
            e.formal_name,
            e.entry.name,
            e.entry.aliases.join(","),
            effective_trust(e)
        )
    }));
    if show_bundled {
        lines.push(format!("{}\t{}\t\t{}", row.formal, row.short, row.trusted));
    }
    Ok(lines)
}
fn update(ctx: &Context, template: Option<String>) -> Result<Vec<String>, CommandError> {
    let selected: Vec<_> = if let Some(name) = template {
        vec![ctx.resolve_user(&name)?]
    } else {
        ctx.user
            .templates
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect()
    };
    if selected.is_empty()
        || !selected
            .iter()
            .any(|(_, entry)| entry.source.contains("://") || entry.source.starts_with("git@"))
    {
        return Err(CommandError::text("no installed git template matches"));
    }
    let mut next = ctx.user.clone();
    let mut lines = Vec::new();
    let mut updated = Vec::new();
    let mut fetched = std::collections::HashSet::new();
    let mut staged = Vec::new();
    for (formal, entry) in selected {
        if !entry.source.contains("://") && !entry.source.starts_with("git@") {
            continue;
        }
        let install = ctx
            .dirs
            .user_data
            .join("repos")
            .join(source::install_key(&formal));
        let address = Address::Git {
            repo: entry.source.clone(),
            reference: entry.reference.clone(),
            path: None,
        };
        if fetched.contains(&install) {
            continue;
        }
        let (clone, result) = clone_sibling(&address, &install)?;
        if matches!(result.reference_kind, RefKind::Tag | RefKind::Commit) {
            lines.push(format!("pinned {formal}"));
            continue;
        }
        let commit = result.commit;
        fetched.insert(install.clone());
        staged.push((clone, install.clone()));
        let keys: Vec<_> = next
            .templates
            .iter()
            .filter(|(_, entry)| entry.path.starts_with(&install))
            .map(|(formal, _)| formal.clone())
            .collect();
        for key in keys {
            next = next
                .set_commit(&key, commit.clone())
                .map_err(CommandError::text)?;
            lines.push(format!("updated {key}"));
            updated.push(key);
        }
    }
    install_staged(ctx, &staged, &next)?;
    // Effective trust is always the live compare, so the stored approval is
    // never rewritten here. An update that changes a template's executable
    // surface lapses its approval; the next apply lists the change and exits 3.
    for formal in &updated {
        let Some(entry) = next.templates.get(formal) else {
            continue;
        };
        let Some(approval) = entry.approval.as_ref() else {
            continue;
        };
        let listed = registry::Listed {
            formal_name: formal.clone(),
            entry: entry.clone(),
            layer: Layer::User,
            approval: Some(approval.clone()),
        };
        if !effective_trust(&listed) {
            lines.push(format!("{formal} (hooks changed; approval lapsed)"));
        }
    }
    Ok(lines)
}
fn remove(ctx: &Context, template: &str) -> Result<Vec<String>, CommandError> {
    let (formal, entry) = ctx.resolve_user(template)?;
    let next = ctx.user.remove(&formal).map_err(CommandError::text)?;
    ctx.write(&next)?;
    if entry.source.contains("://") || entry.source.starts_with("git@") {
        let install = ctx
            .dirs
            .user_data
            .join("repos")
            .join(source::install_key(&formal));
        if !next
            .templates
            .values()
            .any(|e| e.path.starts_with(&install))
            && install.exists()
        {
            fs::remove_dir_all(install).map_err(CommandError::text)?;
        }
    }
    Ok(vec![format!("removed {formal}")])
}
/// Approve the current installed executable surface of an installed template.
/// Reads only the installed folder — never fetches, reclones, or moves the
/// commit — and writes the approval to the user registry alone.
fn trust(ctx: &Context, name: &str) -> Result<Vec<String>, CommandError> {
    let (formal, entry) = ctx.resolve_user(name)?;
    let template = Template::load(&entry.path).map_err(CommandError::text)?;
    let surface = toha::HookSurface::of(&template)
        .map_err(|error| CommandError::text(guidance::surface_unreadable(&formal, &error)))?;
    let live = surface.digest();
    // Idempotency is defined through the one trust rule: a surface that changed
    // since approval is not "already trusted"; the command holds no `==`. A
    // denial (a hand-edited/legacy `trusted: false` beside a matching approval)
    // makes the entry effectively untrusted, so the grant runs to clear it
    // rather than reporting "already trusted".
    if !entry.denied
        && matches!(
            toha::evaluate_trust(entry.approval.as_ref(), &live),
            toha::Trust::Trusted
        )
    {
        return Ok(vec![format!("already trusted {formal}")]);
    }
    let next = ctx
        .user
        .set_approval(&formal, Some(live))
        .map_err(CommandError::text)?;
    ctx.write(&next)?;
    eprintln!("{}", guidance::approved_surface(&surface));
    Ok(vec![format!("trusted {formal}")])
}
/// Revoke approval of an installed template's hooks. Reads nothing on disk, so
/// it cannot fail on the installed surface; it clears the approval and persists
/// a denial so a lower registry layer's approval cannot reappear.
fn untrust(ctx: &Context, name: &str) -> Result<Vec<String>, CommandError> {
    let (formal, entry) = ctx.resolve_user(name)?;
    if entry.approval.is_none() && entry.denied {
        return Ok(vec![format!("already untrusted {formal}")]);
    }
    let next = ctx
        .user
        .set_approval(&formal, None)
        .map_err(CommandError::text)?;
    ctx.write(&next)?;
    Ok(vec![format!("untrusted {formal}")])
}
fn valid_alias(alias: &str) -> bool {
    !alias.is_empty()
        && alias.split('-').all(|p| {
            !p.is_empty()
                && p.bytes()
                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
        })
}
fn alias(
    ctx: &Context,
    template: Option<String>,
    name: Option<String>,
    remove: Option<String>,
) -> Result<Vec<String>, CommandError> {
    if let Some(alias) = remove {
        if template.is_some() || name.is_some() {
            return Err(CommandError::text(
                "-r cannot be combined with a template or alias",
            ));
        }
        let next = ctx.user.remove_alias(&alias).map_err(CommandError::text)?;
        ctx.write(&next)?;
        return Ok(vec![format!("removed alias {alias}")]);
    }
    let template = template.ok_or_else(|| CommandError::text("template and alias are required"))?;
    let alias = name.ok_or_else(|| CommandError::text("template and alias are required"))?;
    if !valid_alias(&alias) {
        return Err(CommandError::text("invalid alias"));
    }
    let (formal, _) = ctx.resolve_user(&template)?;
    if ctx.registry.entries.contains_key(&alias)
        || ctx
            .registry
            .entries
            .values()
            .any(|e| e.entry.aliases.contains(&alias))
    {
        let removable = ctx
            .user
            .templates
            .values()
            .any(|entry| entry.aliases.contains(&alias));
        return Err(CommandError::text(guidance::alias_in_use(
            &template, &alias, removable,
        )));
    }
    let next = ctx
        .user
        .add_alias(&formal, &alias)
        .map_err(CommandError::text)?;
    let warning = ctx
        .registry
        .entries
        .values()
        .any(|e| e.formal_name != formal && e.entry.name == alias);
    // The user layer is the only writable layer.
    ctx.write(&next)?;
    let mut lines = Vec::new();
    if warning {
        lines.push(format!(
            "warning: alias {alias} is another template's short name"
        ));
    }
    lines.push(format!("added alias {alias} for {formal}"));
    Ok(lines)
}
/// The same `templates` command with a formal name in place of an ambiguous
/// template name.
pub fn retry(args: &TemplatesArgs) -> impl Fn(&str) -> String + use<> {
    let (command, alias) = match &args.command {
        TemplatesCommand::Update { .. } => ("templates update", None),
        TemplatesCommand::Remove { .. } => ("templates remove", None),
        TemplatesCommand::Alias { alias, .. } => ("templates alias", alias.clone()),
        TemplatesCommand::Trust { .. } => ("templates trust", None),
        TemplatesCommand::Untrust { .. } => ("templates untrust", None),
        TemplatesCommand::Add { .. } | TemplatesCommand::List { .. } => ("templates list", None),
    };
    move |formal| {
        let mut operands = vec![guidance::value(guidance::formal_for(command, formal))];
        operands.extend(alias.as_deref().map(guidance::value));
        guidance::toha(command, &[], &operands)
    }
}
pub fn run(args: TemplatesArgs, dirs: Dirs, cwd: &Path) -> Result<Vec<String>, CommandError> {
    let ctx = Context::load(dirs, cwd)?;
    match args.command {
        TemplatesCommand::Add {
            address,
            alias,
            trust,
        } => add(&ctx, &address, alias, trust, cwd),
        TemplatesCommand::List {
            local,
            system,
            user,
            json,
        } => list(
            &ctx,
            if local {
                Some(Layer::Local)
            } else if system {
                Some(Layer::System)
            } else if user {
                Some(Layer::User)
            } else {
                None
            },
            json,
        ),
        TemplatesCommand::Update { template } => update(&ctx, template),
        TemplatesCommand::Remove { template } => remove(&ctx, &template),
        TemplatesCommand::Alias {
            template,
            alias: name,
            remove,
        } => alias(&ctx, template, name, remove),
        TemplatesCommand::Trust { template } => trust(&ctx, &template),
        TemplatesCommand::Untrust { template } => untrust(&ctx, &template),
    }
}