tftio-prompter 4.0.0

A CLI tool for composing reusable prompt snippets from a library using TOML profiles
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
//! Profile resolution, dependency trees, and listing.
use crate::config::Config;
use crate::config::load_bundle;
use crate::{
    ProfileDef, PrompterError, home_dir, parse_config_file, read_config_with_path, unescape,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::collections::HashSet;
use std::ffi::OsStr;
use std::fs;
use std::io;
use std::io::Write;
use std::path::{Component, Path, PathBuf};
use std::str::FromStr;
use tftio_cli_common::{JsonOutput, render_response};

/// A model-family directory name used for fragment substitution.
///
/// Family names are restricted to one non-empty path component so callers
/// cannot escape a fragment's `families/` directory.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FamilyName(String);

impl FamilyName {
    /// Parse and validate a family name.
    ///
    /// # Errors
    /// Returns [`InvalidFamilyName`] when `value` is empty, absolute, or contains
    /// path separators or traversal components.
    pub fn new(value: impl Into<String>) -> Result<Self, InvalidFamilyName> {
        let value = value.into();
        let mut components = Path::new(&value).components();
        let is_single_component = matches!(
            components.next(),
            Some(Component::Normal(component)) if component == OsStr::new(&value)
        ) && components.next().is_none();

        if is_single_component {
            Ok(Self(value))
        } else {
            Err(InvalidFamilyName(value))
        }
    }

    /// Return the validated directory name.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for FamilyName {
    type Err = InvalidFamilyName;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl std::fmt::Display for FamilyName {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Error returned when a family name is not a single safe path component.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("family name must be one non-empty path component: {0}")]
pub struct InvalidFamilyName(String);

pub(crate) fn collect_profiles(
    prefix: &str,
    value: &toml::Value,
    out: &mut HashMap<String, Vec<String>>,
) -> Result<(), PrompterError> {
    let Some(table) = value.as_table() else {
        return Ok(());
    };

    if let Some(deps_value) = table.get("depends_on") {
        let arr = deps_value.as_array().ok_or_else(|| {
            PrompterError::ConfigField(format!(
                "`depends_on` for [{prefix}] must be an array of strings"
            ))
        })?;
        let mut deps = Vec::with_capacity(arr.len());
        for entry in arr {
            let s = entry.as_str().ok_or_else(|| {
                PrompterError::ConfigField(format!(
                    "`depends_on` entries for [{prefix}] must be strings"
                ))
            })?;
            deps.push(s.to_string());
        }
        if out.insert(prefix.to_string(), deps).is_some() {
            return Err(PrompterError::DuplicateProfile(format!(
                "Duplicate profile definition: [{prefix}]"
            )));
        }
    }

    for (sub_key, sub_val) in table {
        if sub_key == "depends_on" {
            continue;
        }
        let new_prefix = if prefix.is_empty() {
            sub_key.clone()
        } else {
            format!("{prefix}.{sub_key}")
        };
        collect_profiles(&new_prefix, sub_val, out)?;
    }
    Ok(())
}

/// Expand a leading `~` or `~/` to the home directory.
///
/// Paths without a leading `~` are returned unchanged.
pub(crate) fn expand_tilde(s: &str) -> Result<PathBuf, PrompterError> {
    if let Some(rest) = s.strip_prefix("~/") {
        Ok(home_dir()?.join(rest))
    } else if s == "~" {
        home_dir()
    } else {
        Ok(PathBuf::from(s))
    }
}

/// Resolve an `import = [...]` entry against the importing config's directory.
///
/// Absolute paths are returned as-is (after `~` expansion); relative paths
/// are joined onto `importer_dir`.
fn resolve_import_path(importer_dir: &Path, import_str: &str) -> Result<PathBuf, PrompterError> {
    let p = expand_tilde(import_str)?;
    if p.is_absolute() {
        Ok(p)
    } else {
        Ok(importer_dir.join(p))
    }
}

/// Determine the library root for a loaded config file.
///
/// * If the config has an explicit `library = "..."` key, expand tilde and
///   resolve it relative to the config file's directory.
/// * Otherwise, if `default_library` is provided (only the primary config
///   with no `-c` override gets this), use that.
/// * Otherwise, default to `<config-dir>/library`.
fn library_root_for(
    config_path: &Path,
    raw_library: Option<&str>,
    default_library: Option<&Path>,
) -> Result<PathBuf, PrompterError> {
    let config_dir = config_path
        .parent()
        .ok_or_else(|| PrompterError::NoParentDir(config_path.to_path_buf()))?;

    if let Some(lib_str) = raw_library {
        let p = expand_tilde(lib_str)?;
        return Ok(if p.is_absolute() {
            p
        } else {
            config_dir.join(p)
        });
    }

    if let Some(default) = default_library {
        return Ok(default.to_path_buf());
    }

    Ok(config_dir.join("library"))
}

/// Load a primary config file plus all of its transitive imports and merge them.
///
/// Invariants enforced:
/// * Profile names must be unique across the entire merged bundle (hard error).
/// * Import cycles are detected and reported.
/// * Only the primary file's `post_prompt` is kept; imports' are ignored.
///
/// `primary_default_library` is the library root to use for the primary
/// config when it does not declare `library = "..."`. Pass
/// `Some(~/.local/prompter/library)` when loading the default config, or
/// `None` when the user supplied `-c FILE` (in which case the primary falls
/// back to `<FILE-dir>/library`).
///
/// # Errors
/// Returns an error on I/O failure, TOML parse failure, unresolved import
/// paths, import cycles, or duplicate profile names.
pub fn load_config_bundle(
    primary_path: &Path,
    primary_default_library: Option<&Path>,
) -> Result<Config, PrompterError> {
    let mut profiles: HashMap<String, ProfileDef> = HashMap::new();
    let mut visited: HashSet<PathBuf> = HashSet::new();
    let mut post_prompt: Option<String> = None;

    load_one(
        primary_path,
        primary_default_library,
        true,
        &mut profiles,
        &mut visited,
        &mut post_prompt,
    )?;

    Ok(Config {
        profiles,
        post_prompt,
    })
}

fn load_one(
    path: &Path,
    default_library: Option<&Path>,
    is_primary: bool,
    profiles: &mut HashMap<String, ProfileDef>,
    visited: &mut HashSet<PathBuf>,
    post_prompt: &mut Option<String>,
) -> Result<(), PrompterError> {
    let text = read_config_with_path(path)?;
    let canonical = fs::canonicalize(path).map_err(|source| PrompterError::Io {
        path: path.to_path_buf(),
        source,
    })?;

    if !visited.insert(canonical.clone()) {
        return Err(PrompterError::ImportCycle(canonical));
    }

    let raw = parse_config_file(&text)?;

    let library_root = library_root_for(&canonical, raw.library.as_deref(), default_library)?;

    for (name, deps) in raw.profiles {
        if let Some(existing) = profiles.get(&name) {
            return Err(PrompterError::DuplicateProfile(format!(
                "Duplicate profile `{}` defined in both {} and {}",
                name,
                existing.library_root.display(),
                library_root.display()
            )));
        }
        profiles.insert(
            name,
            ProfileDef {
                deps,
                library_root: library_root.clone(),
            },
        );
    }

    if is_primary {
        *post_prompt = raw.post_prompt.map(|s| unescape(&s));
    }

    let importer_dir = canonical
        .parent()
        .ok_or_else(|| PrompterError::NoParentDir(canonical.clone()))?
        .to_path_buf();
    for import_str in raw.imports {
        let import_path = resolve_import_path(&importer_dir, &import_str)?;
        // Imported configs never use the primary default library; they always
        // resolve their library via `library = "..."` or `<their-dir>/library`.
        load_one(&import_path, None, false, profiles, visited, post_prompt)?;
    }

    Ok(())
}

/// Errors that can occur during profile resolution.
///
/// These errors represent various failure modes when resolving
/// profile dependencies and validating file references.
#[derive(thiserror::Error, Debug, PartialEq, Eq)]
pub enum ResolveError {
    /// Referenced profile name does not exist in configuration
    #[error("Unknown profile: {0}")]
    UnknownProfile(String),
    /// Circular dependency detected in profile references
    #[error("Cycle detected: {}", .0.join(" -> "))]
    Cycle(Vec<String>),
    /// Referenced markdown file does not exist
    #[error("Missing file: {path} (referenced by [{referenced_by}])", path = .0.display(), referenced_by = .1)]
    MissingFile(PathBuf, String), // (path, referenced_by)
}

/// Node type in the dependency tree
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TreeNodeType {
    /// Profile node
    Profile,
    /// Fragment (markdown file) node
    Fragment,
}

/// Tree node representing a profile or fragment in the dependency tree
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TreeNode {
    /// Type of node (profile or fragment)
    #[serde(rename = "type")]
    pub node_type: TreeNodeType,
    /// Name of profile or path of fragment
    pub name: String,
    /// Children of this node
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub children: Vec<TreeNode>,
}

/// Complete tree structure for JSON output
#[derive(Debug, Serialize, Deserialize)]
pub struct TreeOutput {
    /// List of root trees (top-level profiles)
    pub trees: Vec<TreeNode>,
}

/// Recursively resolve a profile's dependencies into a list of
/// `(fragment_path, owning_library_root)` pairs.
///
/// Each `.md` dep is resolved against the owning profile's `library_root`,
/// so profiles imported from different bundles still find their fragments.
/// Profile-to-profile refs are looked up by name in the merged map.
///
/// Cycle detection and fragment deduplication (by absolute path) are
/// performed across the full traversal.
///
/// # Errors
/// Returns an error if:
/// - Profile name is not found in configuration
/// - Circular dependency is detected
/// - Referenced markdown file does not exist
#[allow(
    clippy::implicit_hasher,
    reason = "public resolver API intentionally fixes the std default HashMap hasher rather than exposing a hasher type parameter"
)]
pub fn resolve_profile(
    name: &str,
    cfg: &Config,
    seen_files: &mut HashSet<PathBuf>,
    stack: &mut Vec<String>,
    out: &mut Vec<(PathBuf, PathBuf)>,
) -> Result<(), ResolveError> {
    resolve_profile_for_family(name, cfg, None, seen_files, stack, out)
}

pub(crate) fn resolve_profile_for_family(
    name: &str,
    cfg: &Config,
    family: Option<&FamilyName>,
    seen_files: &mut HashSet<PathBuf>,
    stack: &mut Vec<String>,
    out: &mut Vec<(PathBuf, PathBuf)>,
) -> Result<(), ResolveError> {
    if stack.contains(&name.to_string()) {
        let mut cycle = stack.clone();
        cycle.push(name.to_string());
        return Err(ResolveError::Cycle(cycle));
    }
    let profile = cfg
        .profiles
        .get(name)
        .ok_or_else(|| ResolveError::UnknownProfile(name.to_string()))?;
    stack.push(name.to_string());
    for dep in &profile.deps {
        if std::path::Path::new(dep)
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
        {
            let path = profile.library_root.join(dep);
            if !path.exists() {
                return Err(ResolveError::MissingFile(path, name.to_string()));
            }
            if seen_files.insert(path.clone()) {
                let rendered_path = family.map_or_else(
                    || path.clone(),
                    |family| {
                        let variant = path.parent().map_or_else(
                            || path.clone(),
                            |parent| {
                                parent
                                    .join("families")
                                    .join(family.as_str())
                                    .join(path.file_name().unwrap_or_default())
                            },
                        );
                        if variant.is_file() {
                            variant
                        } else {
                            path.clone()
                        }
                    },
                );
                out.push((rendered_path, profile.library_root.clone()));
            }
        } else {
            resolve_profile_for_family(dep, cfg, family, seen_files, stack, out)?;
        }
    }
    stack.pop();
    Ok(())
}

/// JSON output structure for list command.
#[derive(Debug, Serialize)]
struct ListOutput {
    profiles: Vec<ProfileInfo>,
    libraries: Vec<LibraryOutput>,
}

/// Profile information for JSON output.
#[derive(Debug, Serialize)]
struct ProfileInfo {
    name: String,
    dependencies: Vec<String>,
    library_root: String,
}

/// One library directory plus the fragment paths it contains.
#[derive(Debug, Serialize)]
struct LibraryOutput {
    path: String,
    fragments: Vec<String>,
}

/// List all available profiles to a writer.
///
/// Text mode: one profile name per line, sorted alphabetically.
///
/// JSON mode: emits profiles (each tagged with the library root it was loaded
/// against) plus a `libraries` array, one entry per unique library root seen
/// across the merged bundle.
///
/// # Errors
/// Returns an error if writing to the output fails or a library directory
/// cannot be read.
pub fn list_profiles(
    cfg: &Config,
    output: JsonOutput,
    mut w: impl Write,
) -> Result<(), PrompterError> {
    if output.is_json() {
        // Gather unique library roots from all loaded profiles.
        let mut unique_roots: Vec<PathBuf> = Vec::new();
        for profile in cfg.profiles.values() {
            if !unique_roots.contains(&profile.library_root) {
                unique_roots.push(profile.library_root.clone());
            }
        }
        unique_roots.sort();

        let mut libraries = Vec::with_capacity(unique_roots.len());
        for root in &unique_roots {
            let mut fragments = Vec::new();
            if root.exists() {
                collect_fragments(root, root, &mut fragments)?;
            }
            fragments.sort();
            libraries.push(LibraryOutput {
                path: root.display().to_string(),
                fragments,
            });
        }

        let mut profiles: Vec<ProfileInfo> = cfg
            .profiles
            .iter()
            .map(|(name, def)| ProfileInfo {
                name: name.clone(),
                dependencies: def.deps.clone(),
                library_root: def.library_root.display().to_string(),
            })
            .collect();
        profiles.sort_by(|a, b| a.name.cmp(&b.name));

        let data = serde_json::to_value(ListOutput {
            profiles,
            libraries,
        })?;
        writeln!(
            &mut w,
            "{}",
            render_response("list", JsonOutput::Json, data, String::new())
        )
        .map_err(PrompterError::Write)?;
    } else {
        let mut names: Vec<_> = cfg.profiles.keys().cloned().collect();
        names.sort();
        for n in names {
            writeln!(&mut w, "{n}").map_err(PrompterError::Write)?;
        }
    }
    Ok(())
}

/// Recursively collect all .md files from a directory
fn collect_fragments(
    root: &Path,
    dir: &Path,
    fragments: &mut Vec<String>,
) -> Result<(), PrompterError> {
    let entries = fs::read_dir(dir).map_err(|source| PrompterError::Io {
        path: dir.to_path_buf(),
        source,
    })?;

    for entry in entries {
        let entry = entry.map_err(|source| PrompterError::Io {
            path: dir.to_path_buf(),
            source,
        })?;
        let path = entry.path();

        if path.is_dir() {
            collect_fragments(root, &path, fragments)?;
        } else if path
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
        {
            if let Ok(rel_path) = path.strip_prefix(root) {
                fragments.push(rel_path.display().to_string());
            }
        }
    }

    Ok(())
}

fn inspect_family_variants(
    directory: &Path,
    families: &mut HashSet<FamilyName>,
    errors: &mut Vec<String>,
) -> Result<(), PrompterError> {
    let entries = fs::read_dir(directory).map_err(|source| PrompterError::Io {
        path: directory.to_path_buf(),
        source,
    })?;

    for entry in entries {
        let entry = entry.map_err(|source| PrompterError::Io {
            path: directory.to_path_buf(),
            source,
        })?;
        let path = entry.path();
        let file_type = entry.file_type().map_err(|source| PrompterError::Io {
            path: path.clone(),
            source,
        })?;
        if !file_type.is_dir() {
            continue;
        }

        if entry.file_name() == OsStr::new("families") {
            inspect_families_directory(directory, &path, families, errors)?;
        } else {
            inspect_family_variants(&path, families, errors)?;
        }
    }

    Ok(())
}

fn inspect_families_directory(
    fragment_directory: &Path,
    families_directory: &Path,
    families: &mut HashSet<FamilyName>,
    errors: &mut Vec<String>,
) -> Result<(), PrompterError> {
    let entries = fs::read_dir(families_directory).map_err(|source| PrompterError::Io {
        path: families_directory.to_path_buf(),
        source,
    })?;

    for entry in entries {
        let entry = entry.map_err(|source| PrompterError::Io {
            path: families_directory.to_path_buf(),
            source,
        })?;
        let family_directory = entry.path();
        let file_type = entry.file_type().map_err(|source| PrompterError::Io {
            path: family_directory.clone(),
            source,
        })?;
        if !file_type.is_dir() {
            continue;
        }

        let family_os = entry.file_name();
        let Some(family_text) = family_os.to_str() else {
            errors.push(format!(
                "Invalid non-UTF-8 family directory: {}",
                family_directory.display()
            ));
            continue;
        };
        let family = match FamilyName::new(family_text) {
            Ok(family) => family,
            Err(error) => {
                errors.push(format!("{error}: {}", family_directory.display()));
                continue;
            }
        };
        families.insert(family);

        let variants = fs::read_dir(&family_directory).map_err(|source| PrompterError::Io {
            path: family_directory.clone(),
            source,
        })?;
        for variant in variants {
            let variant = variant.map_err(|source| PrompterError::Io {
                path: family_directory.clone(),
                source,
            })?;
            let variant_path = variant.path();
            let variant_type = variant.file_type().map_err(|source| PrompterError::Io {
                path: variant_path.clone(),
                source,
            })?;
            if !variant_type.is_file()
                || !variant_path
                    .extension()
                    .is_some_and(|extension| extension.eq_ignore_ascii_case("md"))
            {
                continue;
            }

            let neutral_path = fragment_directory.join(variant.file_name());
            if !neutral_path.is_file() {
                errors.push(format!(
                    "Orphan family variant: {} does not shadow neutral fragment {}",
                    variant_path.display(),
                    neutral_path.display()
                ));
            }
        }
    }

    Ok(())
}

/// Validate configuration and library file references.
///
/// Checks that all profile dependencies are valid, including:
/// - Referenced profiles exist in configuration
/// - Referenced markdown files exist in their owning library root
/// - No circular dependencies exist
///
/// # Errors
/// Returns an error if:
/// - Referenced profiles don't exist
/// - Referenced files don't exist
/// - Circular dependencies are detected
pub fn validate(cfg: &Config) -> Result<(), PrompterError> {
    let mut errors: Vec<String> = Vec::new();

    for (profile_name, profile) in &cfg.profiles {
        for dep in &profile.deps {
            if std::path::Path::new(dep)
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
            {
                let path = profile.library_root.join(dep);
                if !path.exists() {
                    errors.push(format!(
                        "Missing file: {} (referenced by [{}])",
                        path.display(),
                        profile_name
                    ));
                }
            } else if !cfg.profiles.contains_key(dep) {
                errors.push(format!(
                    "Unknown profile: {dep} (referenced by [{profile_name}])"
                ));
            }
        }
    }

    let mut family_set = HashSet::new();
    for library_root in cfg.library_roots() {
        inspect_family_variants(&library_root, &mut family_set, &mut errors)?;
    }
    let mut families: Vec<_> = family_set.into_iter().collect();
    families.sort();

    for name in cfg.profiles.keys() {
        for family in std::iter::once(None).chain(families.iter().map(Some)) {
            let mut seen_files = HashSet::new();
            let mut stack = Vec::new();
            let mut out = Vec::new();
            if let Err(error) =
                resolve_profile_for_family(name, cfg, family, &mut seen_files, &mut stack, &mut out)
            {
                let message = error.to_string();
                if !errors.contains(&message) {
                    errors.push(message);
                }
            }
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(PrompterError::Validation(errors.join("\n")))
    }
}

/// Build a tree node for a profile or fragment
fn build_tree_node(name: &str, cfg: &Config) -> TreeNode {
    // Check if it's a fragment (ends with .md)
    if std::path::Path::new(name)
        .extension()
        .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
    {
        return TreeNode {
            node_type: TreeNodeType::Fragment,
            name: name.to_string(),
            children: Vec::new(),
        };
    }

    // It's a profile - recursively build children
    let children = cfg
        .profiles
        .get(name)
        .map(|def| {
            def.deps
                .iter()
                .map(|dep| build_tree_node(dep, cfg))
                .collect()
        })
        .unwrap_or_default();

    TreeNode {
        node_type: TreeNodeType::Profile,
        name: name.to_string(),
        children,
    }
}

/// Find root profiles (profiles that are not referenced by any other profile)
fn find_root_profiles(cfg: &Config) -> Vec<String> {
    let mut referenced = HashSet::new();

    // Collect all profiles that are referenced by others
    for profile in cfg.profiles.values() {
        for dep in &profile.deps {
            // Only track profile references (not .md files)
            if !std::path::Path::new(dep)
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
            {
                referenced.insert(dep.clone());
            }
        }
    }

    // Find profiles that are never referenced
    let mut roots: Vec<String> = cfg
        .profiles
        .keys()
        .filter(|profile| !referenced.contains(*profile))
        .cloned()
        .collect();

    roots.sort();
    roots
}

/// Build complete tree structure for all root profiles
fn build_trees(cfg: &Config) -> TreeOutput {
    let root_profiles = find_root_profiles(cfg);
    let trees = root_profiles
        .iter()
        .map(|profile| build_tree_node(profile, cfg))
        .collect();

    TreeOutput { trees }
}

/// Print tree structure in traditional tree format
fn print_tree(node: &TreeNode, prefix: &str, is_last: bool, w: &mut impl Write) -> io::Result<()> {
    // Print current node with appropriate connector
    let connector = if is_last { "└── " } else { "├── " };
    writeln!(w, "{prefix}{connector}{}", node.name)?;

    // Prepare prefix for children
    let child_prefix = format!("{}{}", prefix, if is_last { "    " } else { "" });

    // Print children
    for (i, child) in node.children.iter().enumerate() {
        let is_last_child = i == node.children.len() - 1;
        print_tree(child, &child_prefix, is_last_child, w)?;
    }

    Ok(())
}

/// Show tree structure for all profiles
pub fn show_tree(cfg: &Config, output: JsonOutput, mut w: impl Write) -> Result<(), PrompterError> {
    let trees = build_trees(cfg);

    if output.is_json() {
        let data = serde_json::to_value(&trees)?;
        writeln!(
            &mut w,
            "{}",
            render_response("tree", JsonOutput::Json, data, String::new())
        )
        .map_err(PrompterError::Write)?;
    } else {
        for (i, tree) in trees.trees.iter().enumerate() {
            // Print root profile name
            writeln!(&mut w, "{}", tree.name).map_err(PrompterError::Write)?;

            // Print children with tree structure
            for (j, child) in tree.children.iter().enumerate() {
                let is_last = j == tree.children.len() - 1;
                print_tree(child, "", is_last, &mut w).map_err(PrompterError::Write)?;
            }

            // Add blank line between trees (except after last one)
            if i < trees.trees.len() - 1 {
                writeln!(&mut w).map_err(PrompterError::Write)?;
            }
        }
    }

    Ok(())
}

/// Show tree structure to stdout
pub fn run_tree_stdout(
    config_override: Option<&Path>,
    output: JsonOutput,
) -> Result<(), PrompterError> {
    let (_cfg_path, cfg) = load_bundle(config_override)?;
    show_tree(&cfg, output, io::stdout())
}