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
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
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
#![cfg_attr(
    not(test),
    deny(clippy::unwrap_used, clippy::panic, clippy::indexing_slicing)
)]
#![cfg_attr(test, allow(clippy::disallowed_methods))]
#![allow(
    clippy::empty_line_after_doc_comments,
    reason = "the blank line between the crate-level attribute block and the //! module docs below is intentional"
)]
#![allow(
    clippy::must_use_candidate,
    reason = "prompter has many small value-returning helpers; blanket #[must_use] would add noise without catching real misuse"
)]

//! Prompter: A CLI tool for composing reusable prompt snippets.

//!

//! This library provides functionality for managing and rendering prompt snippets

//! from a structured library using TOML configuration files.

pub mod cli;

pub mod config;
pub mod error;

pub mod profile;

pub mod render;

pub mod completions;
pub mod scaffold;

pub mod doctor;

pub use cli::*;

pub use config::*;

pub use profile::*;

pub use render::*;

pub use error::PrompterError;
pub use scaffold::*;

use serde::Serialize;

use chrono::Local;
use clap::Parser;
use colored::Colorize;
use is_terminal::IsTerminal;
use std::env;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
pub use tftio_cli_common::{AgentSubcommand, MetaCommand};
use tftio_cli_common::{JsonOutput, render_response};

/// A single profile definition: its raw dependency strings plus the library
/// directory that should be used to resolve any `.md` deps it declares.
///
/// The library root is recorded per-profile because a merged bundle can pull
/// profiles from multiple config files, each with its own fragments tree.

#[must_use]
pub fn unescape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            match chars.next() {
                Some('n') => out.push('\n'),
                Some('t') => out.push('\t'),
                Some('r') => out.push('\r'),
                Some('"') => out.push('"'),
                Some('\\') | None => out.push('\\'),
                Some(other) => {
                    out.push('\\');
                    out.push(other);
                }
            }
        } else {
            out.push(c);
        }
    }
    out
}

/// Parse command-line arguments and return the resolved application mode.
///
/// Uses clap to parse raw arguments into a structured [`AppMode`]. The
/// `--help` and `--version` short-circuits clap performs are mapped onto the
/// corresponding modes rather than treated as failures.
///
/// # Errors
/// Returns [`PrompterError::ArgParse`] when clap rejects the arguments
/// (unknown flags, missing required arguments, conflicting options); the
/// payload is clap's formatted usage text, intended for display.
pub fn parse_args_from(args: Vec<String>) -> Result<AppMode, PrompterError> {
    let cli = match Cli::try_parse_from(args) {
        Ok(cli) => cli,
        Err(err) => match err.kind() {
            clap::error::ErrorKind::DisplayHelp => return Ok(AppMode::Help),
            clap::error::ErrorKind::DisplayVersion => return Ok(AppMode::Version { json: false }),
            _ => return Err(PrompterError::ArgParse(err.to_string())),
        },
    };

    Ok(resolve_app_mode(cli))
}

/// Profile rendered as the always-on invariant base by `prompter system`.
///
/// This is the named invariant-base unit; the harness stamps its output into
/// each agent's system-prompt site. Domain layers are selected separately.
pub const SYSTEM_BASE_PROFILE: &str = "core.base";

/// Resolve a parsed [`Cli`] value into the executable [`AppMode`].
///
/// This mapping is total: every [`Cli`] value yields an [`AppMode`], so no
/// `Result` wrapping is needed.
#[must_use]
pub fn resolve_app_mode(cli: Cli) -> AppMode {
    match cli.command {
        Commands::Meta { command } => match command {
            MetaCommand::Version { json } => AppMode::Version { json },
            MetaCommand::License => AppMode::License,
            MetaCommand::Completions { shell } => AppMode::Completions { shell },
            MetaCommand::Doctor { json } => AppMode::Doctor { json },
            MetaCommand::Agent { command } => AppMode::Agent { command },
        },
        Commands::Init => AppMode::Init,
        Commands::List => AppMode::List {
            config: cli.config,
            json: cli.json,
        },
        Commands::Tree => AppMode::Tree {
            config: cli.config,
            json: cli.json,
        },
        Commands::Validate => AppMode::Validate {
            config: cli.config,
            json: cli.json,
        },
        Commands::Run {
            profiles,
            family,
            separator,
            pre_prompt,
            post_prompt,
            bare,
        } => {
            let sep = separator.as_ref().map(|s| unescape(s));
            let pre = pre_prompt.as_ref().map(|s| unescape(s));
            let post = post_prompt.as_ref().map(|s| unescape(s));
            AppMode::Run {
                profiles,
                family,
                separator: sep,
                pre_prompt: pre,
                post_prompt: post,
                framing: Framing::from_bare_flag(bare),
                config: cli.config,
                json: cli.json,
            }
        }
        Commands::System {
            profiles,
            separator,
            pre_prompt,
            post_prompt,
            bare,
        } => {
            let sep = separator.as_ref().map(|s| unescape(s));
            let pre = pre_prompt.as_ref().map(|s| unescape(s));
            let post = post_prompt.as_ref().map(|s| unescape(s));
            let mut all = Vec::with_capacity(profiles.len() + 1);
            all.push(SYSTEM_BASE_PROFILE.to_string());
            all.extend(profiles);
            AppMode::Run {
                profiles: all,
                family: None,
                separator: sep,
                pre_prompt: pre,
                post_prompt: post,
                framing: Framing::from_bare_flag(bare),
                config: cli.config,
                json: cli.json,
            }
        }
    }
}

fn home_dir() -> Result<PathBuf, PrompterError> {
    dirs::home_dir().ok_or(PrompterError::HomeNotSet)
}

fn config_path() -> Result<PathBuf, PrompterError> {
    Ok(home_dir()?.join(".config/prompter/config.toml"))
}

fn library_dir() -> Result<PathBuf, PrompterError> {
    Ok(home_dir()?.join(".local/prompter/library"))
}

fn resolve_primary_config_path(path: &Path) -> Result<PathBuf, PrompterError> {
    if path.is_absolute() {
        Ok(path.to_path_buf())
    } else {
        env::current_dir()
            .map_err(PrompterError::WorkingDir)
            .map(|cwd| cwd.join(path))
    }
}

fn is_terminal() -> bool {
    std::io::stdout().is_terminal()
}

fn default_pre_prompt() -> String {
    "You are an LLM coding agent. Here are invariants that you must adhere to. Please respond with 'Got it' when you have studied these and understand them. At that point, the operator will give you further instructions. You are *not* to do anything to the contents of this directory until you have been explicitly asked to, by the operator.\n\n".to_string()
}

fn default_post_prompt() -> String {
    "Now, read the @AGENTS.md and @CLAUDE.md files in this directory, if they exist.".to_string()
}

fn format_system_prefix() -> String {
    let date = Local::now().format("%Y-%m-%d").to_string();
    let os = env::consts::OS;
    let arch = env::consts::ARCH;

    if is_terminal() {
        format!(
            "🗓️  Today is {}, and you are running on a {}/{} system.\n\n",
            date.bright_cyan(),
            arch.bright_green(),
            os.bright_green()
        )
    } else {
        format!("Today is {date}, and you are running on a {arch}/{os} system.\n\n")
    }
}

fn success_message(msg: &str) -> String {
    if is_terminal() {
        format!("{}", msg.bright_green())
    } else {
        msg.to_string()
    }
}

fn info_message(msg: &str) -> String {
    if is_terminal() {
        format!("ℹ️  {}", msg.bright_blue())
    } else {
        msg.to_string()
    }
}

fn read_config_with_path(path: &Path) -> Result<String, PrompterError> {
    fs::read_to_string(path).map_err(|source| PrompterError::Io {
        path: path.to_path_buf(),
        source,
    })
}

fn resolve_config_path(config_override: Option<&Path>) -> Result<PathBuf, PrompterError> {
    config_override.map_or_else(config_path, resolve_primary_config_path)
}

/// Load the primary config plus its transitive imports, using the default
/// library root (`~/.local/prompter/library`) only when no `-c` override is

pub fn run_list_stdout(
    config_override: Option<&Path>,
    output: JsonOutput,
) -> Result<(), PrompterError> {
    let (_cfg_path, cfg) = load_bundle(config_override)?;
    list_profiles(&cfg, output, io::stdout())?;
    Ok(())
}

/// JSON output for successful validation
#[derive(Debug, Serialize)]
struct ValidateOutput {
    valid: bool,
}

/// Validate configuration and output results to stdout.
///
/// Convenience function that reads configuration and validates it,
/// outputting any errors found.
///
/// # Arguments
/// * `config_override` - Optional configuration file override
/// * `json` - Whether to output in JSON format
///
/// # Errors
/// Returns an error if:
/// - Configuration file cannot be read or parsed
/// - Validation finds missing files or circular dependencies
pub fn run_validate_stdout(
    config_override: Option<&Path>,
    output: JsonOutput,
) -> Result<(), PrompterError> {
    let (_cfg_path, cfg) = load_bundle(config_override)?;
    validate(&cfg)?;

    if output.is_json() {
        let data = serde_json::to_value(ValidateOutput { valid: true })?;
        println!(
            "{}",
            render_response("validate", JsonOutput::Json, data, String::new())
        );
    }

    Ok(())
}

/// JSON structure for a single fragment
#[derive(Debug, Serialize)]
struct FragmentOutput {
    path: String,
    content: String,
}

/// JSON output structure for render command
#[derive(Debug, Serialize)]
struct RenderOutput {
    profile: String,
    pre_prompt: String,
    system_info: String,
    fragments: Vec<FragmentOutput>,
}

/// Render one or more profiles' content to a writer.
///
/// Resolves profile dependencies (each fragment carrying its owning library
/// root) and writes concatenated content to the provided writer, including
/// pre-prompt, system info, file contents with optional separators, and
/// post-prompt. Files are deduplicated across all profiles by absolute path
/// (first occurrence wins).
///
/// # Errors
/// Returns an error if:
/// - Profile resolution fails (missing files, cycles, unknown profiles)
/// - Writing to output fails

pub fn available_profiles(config_override: Option<&Path>) -> Result<Vec<String>, PrompterError> {
    let (_cfg_path, cfg) = load_bundle(config_override)?;
    let mut names: Vec<String> = cfg.profiles.keys().cloned().collect();
    names.sort();
    Ok(names)
}

#[cfg(test)]
#[allow(clippy::wildcard_imports)]
mod tests {
    use super::*;
    #[allow(unused_imports)]
    use std::collections::HashSet;
    use std::io::Write;

    fn mk_tmp(prefix: &str) -> PathBuf {
        let mut p = env::temp_dir();
        let unique = format!(
            "{}_{}_{}",
            prefix,
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        p.push(unique);
        p
    }

    /// Build a [`Config`] whose every profile shares a single library root.
    /// Most existing unit tests only exercise the single-bundle case; this
    /// helper avoids tediously repeating `ProfileDef { ... }` at every call site.
    fn cfg_with_lib<I>(profiles: I, lib: &Path, post_prompt: Option<&str>) -> Config
    where
        I: IntoIterator<Item = (&'static str, Vec<&'static str>)>,
    {
        let profiles = profiles
            .into_iter()
            .map(|(name, deps)| {
                (
                    name.to_string(),
                    ProfileDef {
                        deps: deps.into_iter().map(String::from).collect(),
                        library_root: lib.to_path_buf(),
                    },
                )
            })
            .collect();
        Config {
            profiles,
            post_prompt: post_prompt.map(String::from),
        }
    }

    #[test]
    fn test_unescape() {
        assert_eq!(unescape("a\\nb\\t\\\"\\\\c"), "a\nb\t\"\\c");
        assert_eq!(unescape("line1\\rline2"), "line1\rline2");
        assert_eq!(unescape("noesc"), "noesc");
    }

    #[test]
    fn test_parse_config_file_errors() {
        // Top-level value that is not a table; toml crate should surface this.
        let err = parse_config_file("not valid toml {{{")
            .unwrap_err()
            .to_string();
        assert!(err.contains("Invalid TOML"), "err={err}");
        // `depends_on` must be an array.
        let err = parse_config_file("[p]\ndepends_on = \"x\"\n")
            .unwrap_err()
            .to_string();
        assert!(err.contains("`depends_on`"), "err={err}");
        // `import` must be an array of strings.
        let err = parse_config_file("import = \"oops\"\n")
            .unwrap_err()
            .to_string();
        assert!(err.contains("`import`"), "err={err}");
    }

    #[test]
    fn test_validate_success_and_unknowns() {
        let lib = mk_tmp("prompter_validate_ok");
        fs::create_dir_all(&lib).unwrap();
        fs::write(lib.join("a.md"), b"A").unwrap();
        fs::write(lib.join("b.md"), b"B").unwrap();
        let cfg = cfg_with_lib(
            [("p1", vec!["a.md"]), ("p2", vec!["p1", "b.md"])],
            &lib,
            None,
        );
        assert!(validate(&cfg).is_ok());
        let cfg2 = cfg_with_lib([("root", vec!["nope"])], &lib, None);
        let err = validate(&cfg2).unwrap_err().to_string();
        assert!(err.contains("Unknown profile"));
    }

    #[test]
    fn test_resolve_errors_and_dedup() {
        let lib = mk_tmp("prompter_resolve_errs");
        fs::create_dir_all(&lib).unwrap();
        let cfg = cfg_with_lib([("root", vec!["missing.md"])], &lib, None);
        let mut seen = HashSet::new();
        let mut stack = Vec::new();
        let mut out = Vec::new();
        let err = resolve_profile("root", &cfg, &mut seen, &mut stack, &mut out).unwrap_err();
        match err {
            ResolveError::MissingFile(_, p) => assert_eq!(p, "root"),
            _ => panic!("expected missing file"),
        }

        fs::create_dir_all(lib.join("a")).unwrap();
        fs::write(lib.join("a/b.md"), b"X").unwrap();
        let cfg2 = cfg_with_lib(
            [("A", vec!["a/b.md"]), ("B", vec!["A", "a/b.md"])],
            &lib,
            None,
        );
        let mut seen = HashSet::new();
        let mut stack = Vec::new();
        let mut out = Vec::new();
        resolve_profile("B", &cfg2, &mut seen, &mut stack, &mut out).unwrap();
        assert_eq!(out.len(), 1);
    }

    #[test]
    fn test_parse_args_errors() {
        // unknown flag
        let args = vec!["prompter".into(), "--bogus".into()];
        let err = parse_args_from(args).unwrap_err().to_string();
        assert!(err.contains("unexpected argument"));
        // missing required subcommand
        let args = vec!["prompter".into()];
        let err = parse_args_from(args).unwrap_err().to_string();
        assert!(err.contains("Usage:") || err.contains("COMMAND"));
    }

    #[test]
    fn test_list_profiles_order() {
        let lib = mk_tmp("prompter_list_order");
        fs::create_dir_all(&lib).unwrap();
        let cfg = cfg_with_lib([("b", vec![]), ("a", vec![])], &lib, None);
        let mut out = Vec::new();
        super::list_profiles(&cfg, JsonOutput::Text, &mut out).unwrap();
        assert_eq!(String::from_utf8(out).unwrap(), "a\nb\n");
    }

    #[test]
    fn test_validate_cycle_detected() {
        let lib = mk_tmp("prompter_cycle");
        fs::create_dir_all(&lib).unwrap();
        let cfg = cfg_with_lib([("A", vec!["B"]), ("B", vec!["A"])], &lib, None);
        let err = validate(&cfg).unwrap_err().to_string();
        assert!(err.contains("Cycle detected"));
    }

    #[test]
    fn test_parse_config_file_flattens_dotted_tables() {
        // Preserves pre-existing semantics: `[profile.x]` is a flat profile
        // named "profile.x", not a nested table.
        let cfg = r#"
[profile.x]
depends_on = [
  "a/b.md",
  "c/d.md",
  "e/f.md",
]
"#;
        let parsed = parse_config_file(cfg).unwrap();
        assert_eq!(parsed.profiles.get("profile.x").unwrap().len(), 3);
    }

    #[test]
    fn test_render_to_writer_basic() {
        let lib = mk_tmp("prompter_render_to_writer");
        fs::create_dir_all(lib.join("a")).unwrap();
        fs::create_dir_all(lib.join("f")).unwrap();
        fs::write(lib.join("a/x.md"), b"AX\n").unwrap();
        fs::write(lib.join("f/y.md"), b"FY\n").unwrap();
        let cfg = cfg_with_lib(
            [
                ("child", vec!["a/x.md"]),
                ("root", vec!["child", "f/y.md", "a/x.md"]),
            ],
            &lib,
            None,
        );
        let mut out = Vec::new();
        super::render_to_writer(
            &cfg,
            &mut out,
            &["root".to_string()],
            None,
            Some("\n--\n"),
            None,
            None,
            Framing::Full,
            JsonOutput::Text,
        )
        .unwrap();

        let output_str = String::from_utf8(out).unwrap();
        assert!(output_str.starts_with("You are an LLM coding agent."));
        assert!(output_str.contains("Today is "));
        assert!(output_str.contains(", and you are running on a "));
        assert!(output_str.contains(" system.\n\n"));
        assert!(output_str.contains("AX\n"));
        assert!(output_str.contains("\n--\n"));
        assert!(output_str.contains("FY\n"));
        assert!(output_str.ends_with(
            "Now, read the @AGENTS.md and @CLAUDE.md files in this directory, if they exist."
        ));
    }

    #[test]
    fn test_render_to_writer_bare_omits_framing() {
        let lib = mk_tmp("prompter_render_bare");
        fs::create_dir_all(lib.join("a")).unwrap();
        fs::create_dir_all(lib.join("f")).unwrap();
        fs::write(lib.join("a/x.md"), b"AX\n").unwrap();
        fs::write(lib.join("f/y.md"), b"FY\n").unwrap();
        let cfg = cfg_with_lib(
            [
                ("child", vec!["a/x.md"]),
                ("root", vec!["child", "f/y.md", "a/x.md"]),
            ],
            &lib,
            Some("Config post-prompt"),
        );
        let mut out = Vec::new();
        super::render_to_writer(
            &cfg,
            &mut out,
            &["root".to_string()],
            None,
            Some("\n--\n"),
            None,
            None,
            Framing::Bare,
            JsonOutput::Text,
        )
        .unwrap();

        let output_str = String::from_utf8(out).unwrap();
        // No pre-prompt, no date/system context, no post-prompt.
        assert!(!output_str.starts_with("You are an LLM coding agent."));
        assert!(!output_str.contains("Today is "));
        assert!(!output_str.contains("Config post-prompt"));
        assert!(!output_str.contains(
            "Now, read the @AGENTS.md and @CLAUDE.md files in this directory, if they exist."
        ));
        // Fragments (deduplicated) and the separator are still present, and the
        // output begins directly with the first fragment (no leading newline).
        assert!(output_str.starts_with("AX\n"));
        assert!(output_str.contains("\n--\n"));
        assert!(output_str.contains("FY\n"));
        assert_eq!(output_str.matches("AX\n").count(), 1);
    }

    #[test]
    fn test_render_to_writer_bare_honors_explicit_pre_post() {
        let lib = mk_tmp("prompter_render_bare_explicit");
        fs::create_dir_all(lib.join("a")).unwrap();
        fs::create_dir_all(lib.join("f")).unwrap();
        fs::write(lib.join("a/x.md"), b"AX\n").unwrap();
        fs::write(lib.join("f/y.md"), b"FY\n").unwrap();
        let cfg = cfg_with_lib(
            [("child", vec!["a/x.md"]), ("root", vec!["child", "f/y.md"])],
            &lib,
            Some("Config post-prompt"),
        );
        let mut out = Vec::new();
        super::render_to_writer(
            &cfg,
            &mut out,
            &["root".to_string()],
            None,
            None,
            Some("EXPLICIT-PRE"),
            Some("EXPLICIT-POST"),
            Framing::Bare,
            JsonOutput::Text,
        )
        .unwrap();

        let output_str = String::from_utf8(out).unwrap();
        // Explicit pre/post win even in bare framing; the config post-prompt and
        // the date/system stamp are still suppressed.
        assert!(output_str.starts_with("EXPLICIT-PRE"));
        assert!(output_str.ends_with("EXPLICIT-POST"));
        assert!(!output_str.contains("Config post-prompt"));
        assert!(!output_str.contains("Today is "));
        assert!(output_str.contains("AX\n"));
        assert!(output_str.contains("FY\n"));
    }

    #[test]
    fn test_render_to_writer_custom_pre_prompt() {
        let lib = mk_tmp("prompter_render_custom_pre");
        fs::create_dir_all(lib.join("a")).unwrap();
        fs::write(lib.join("a/x.md"), b"Content\n").unwrap();
        let cfg = cfg_with_lib([("test", vec!["a/x.md"])], &lib, None);
        let mut out = Vec::new();
        super::render_to_writer(
            &cfg,
            &mut out,
            &["test".to_string()],
            None,
            None,
            Some("Custom pre-prompt\n\n"),
            None,
            Framing::Full,
            JsonOutput::Text,
        )
        .unwrap();

        let output_str = String::from_utf8(out).unwrap();
        assert!(output_str.starts_with("Custom pre-prompt\n\n"));
        assert!(output_str.contains("Today is "));
        assert!(output_str.contains("Content\n"));
        assert!(output_str.ends_with(
            "Now, read the @AGENTS.md and @CLAUDE.md files in this directory, if they exist."
        ));
    }

    #[test]
    fn test_render_to_writer_custom_post_prompt() {
        let lib = mk_tmp("prompter_render_custom_post");
        fs::create_dir_all(lib.join("a")).unwrap();
        fs::write(lib.join("a/x.md"), b"Content\n").unwrap();
        let cfg = cfg_with_lib(
            [("test", vec!["a/x.md"])],
            &lib,
            Some("Custom config post-prompt"),
        );
        let mut out = Vec::new();
        super::render_to_writer(
            &cfg,
            &mut out,
            &["test".to_string()],
            None,
            None,
            None,
            None,
            Framing::Full,
            JsonOutput::Text,
        )
        .unwrap();

        let output_str = String::from_utf8(out).unwrap();
        assert!(output_str.ends_with("Custom config post-prompt"));

        let mut out2 = Vec::new();
        super::render_to_writer(
            &cfg,
            &mut out2,
            &["test".to_string()],
            None,
            None,
            None,
            Some("CLI post-prompt"),
            Framing::Full,
            JsonOutput::Text,
        )
        .unwrap();

        let output_str2 = String::from_utf8(out2).unwrap();
        assert!(output_str2.ends_with("CLI post-prompt"));
    }

    #[test]
    fn test_render_multiple_profiles_with_deduplication() {
        let lib = mk_tmp("prompter_multi_profile_dedup");
        fs::create_dir_all(lib.join("shared")).unwrap();
        fs::create_dir_all(lib.join("a")).unwrap();
        fs::create_dir_all(lib.join("b")).unwrap();

        fs::write(lib.join("shared/common.md"), b"COMMON\n").unwrap();
        fs::write(lib.join("a/specific.md"), b"A_SPECIFIC\n").unwrap();
        fs::write(lib.join("b/specific.md"), b"B_SPECIFIC\n").unwrap();

        let cfg = cfg_with_lib(
            [
                ("profile_a", vec!["shared/common.md", "a/specific.md"]),
                ("profile_b", vec!["shared/common.md", "b/specific.md"]),
            ],
            &lib,
            None,
        );

        let mut out = Vec::new();
        super::render_to_writer(
            &cfg,
            &mut out,
            &["profile_a".to_string(), "profile_b".to_string()],
            None,
            Some("\n---\n"),
            None,
            None,
            Framing::Full,
            JsonOutput::Text,
        )
        .unwrap();

        let output_str = String::from_utf8(out).unwrap();

        let common_count = output_str.matches("COMMON").count();
        assert_eq!(
            common_count, 1,
            "Common file should appear exactly once, found {common_count}"
        );
        assert!(output_str.contains("A_SPECIFIC"));
        assert!(output_str.contains("B_SPECIFIC"));

        let common_pos = output_str.find("COMMON").unwrap();
        let a_pos = output_str.find("A_SPECIFIC").unwrap();
        let b_pos = output_str.find("B_SPECIFIC").unwrap();

        assert!(common_pos < a_pos);
        assert!(a_pos < b_pos);
    }

    #[test]
    fn test_family_variant_substitution_fallback_and_neutral_dedup() {
        let lib = mk_tmp("prompter_family_substitution");
        fs::create_dir_all(lib.join("general/families/gpt")).unwrap();
        fs::write(lib.join("general/rules.md"), b"NEUTRAL_RULES\n").unwrap();
        fs::write(lib.join("general/fallback.md"), b"FALLBACK\n").unwrap();
        fs::write(lib.join("general/families/gpt/rules.md"), b"GPT_RULES\n").unwrap();
        let cfg = cfg_with_lib(
            [
                ("first", vec!["general/rules.md", "general/fallback.md"]),
                ("second", vec!["general/rules.md"]),
            ],
            &lib,
            None,
        );
        let family = FamilyName::new("gpt").unwrap();

        let mut family_output = Vec::new();
        super::render_to_writer(
            &cfg,
            &mut family_output,
            &["first".to_string(), "second".to_string()],
            Some(&family),
            None,
            None,
            None,
            Framing::Bare,
            JsonOutput::Text,
        )
        .unwrap();
        let family_output = String::from_utf8(family_output).unwrap();
        assert_eq!(family_output.matches("GPT_RULES").count(), 1);
        assert!(!family_output.contains("NEUTRAL_RULES"));
        assert!(family_output.contains("FALLBACK"));

        let mut neutral_output = Vec::new();
        super::render_to_writer(
            &cfg,
            &mut neutral_output,
            &["first".to_string(), "second".to_string()],
            None,
            None,
            None,
            None,
            Framing::Bare,
            JsonOutput::Text,
        )
        .unwrap();
        let neutral_output = String::from_utf8(neutral_output).unwrap();
        assert_eq!(neutral_output.matches("NEUTRAL_RULES").count(), 1);
        assert!(!neutral_output.contains("GPT_RULES"));
        assert!(neutral_output.contains("FALLBACK"));
    }

    #[test]
    fn test_validate_rejects_orphan_family_variant() {
        let lib = mk_tmp("prompter_family_orphan");
        fs::create_dir_all(lib.join("general/families/gpt")).unwrap();
        fs::write(lib.join("general/rules.md"), b"NEUTRAL_RULES\n").unwrap();
        fs::write(lib.join("general/families/gpt/rules.md"), b"GPT_RULES\n").unwrap();
        let cfg = cfg_with_lib([("root", vec!["general/rules.md"])], &lib, None);
        assert!(validate(&cfg).is_ok());

        let orphan = lib.join("general/families/gpt/orphan.md");
        fs::write(&orphan, b"ORPHAN\n").unwrap();
        let error = validate(&cfg).unwrap_err().to_string();
        assert!(error.contains("Orphan family variant"), "error: {error}");
        assert!(
            error.contains(&orphan.display().to_string()),
            "error: {error}"
        );
    }

    #[test]
    fn test_parse_config_file_with_post_prompt() {
        let cfg = r#"
post_prompt = "Custom post prompt from config"

[profile]
depends_on = ["file.md"]
"#;
        let parsed = parse_config_file(cfg).unwrap();
        assert_eq!(
            parsed.post_prompt,
            Some("Custom post prompt from config".to_string())
        );
        assert_eq!(parsed.profiles.get("profile").unwrap().len(), 1);
    }

    #[test]
    fn test_expand_tilde() {
        let home = env::var("HOME").ok();
        if let Some(h) = home {
            assert_eq!(
                expand_tilde("~/foo/bar").unwrap(),
                PathBuf::from(&h).join("foo/bar")
            );
            assert_eq!(expand_tilde("~").unwrap(), PathBuf::from(&h));
        }
        assert_eq!(
            expand_tilde("/abs/path").unwrap(),
            PathBuf::from("/abs/path")
        );
        assert_eq!(expand_tilde("rel/path").unwrap(), PathBuf::from("rel/path"));
    }

    #[test]
    fn test_load_bundle_single_file() {
        let dir = mk_tmp("prompter_bundle_single");
        fs::create_dir_all(dir.join("library/a")).unwrap();
        fs::write(dir.join("library/a/x.md"), b"AX").unwrap();
        fs::write(
            dir.join("config.toml"),
            r#"
[root]
depends_on = ["a/x.md"]
"#,
        )
        .unwrap();
        let cfg = load_config_bundle(&dir.join("config.toml"), None).unwrap();
        assert_eq!(cfg.profiles.len(), 1);
        let root = cfg.profiles.get("root").unwrap();
        assert_eq!(root.deps, vec!["a/x.md"]);
        // library_root should resolve to <config-dir>/library
        assert_eq!(
            root.library_root,
            fs::canonicalize(dir.join("library")).unwrap()
        );
    }

    #[test]
    fn test_load_bundle_imports_and_dedup_across_libraries() {
        // primary config + one imported bundle; each has its own library.
        let primary_dir = mk_tmp("prompter_bundle_primary");
        let imported_dir = mk_tmp("prompter_bundle_import");

        fs::create_dir_all(primary_dir.join("library/p")).unwrap();
        fs::write(primary_dir.join("library/p/primary.md"), b"P").unwrap();

        fs::create_dir_all(imported_dir.join("library/i")).unwrap();
        fs::write(imported_dir.join("library/i/imported.md"), b"I").unwrap();

        fs::write(
            imported_dir.join("config.toml"),
            r#"
[team.base]
depends_on = ["i/imported.md"]
"#,
        )
        .unwrap();

        let primary_cfg = format!(
            r#"
import = ["{}"]

[my.local]
depends_on = ["team.base", "p/primary.md"]
"#,
            imported_dir.join("config.toml").display()
        );
        fs::write(primary_dir.join("config.toml"), primary_cfg).unwrap();

        let cfg = load_config_bundle(&primary_dir.join("config.toml"), None).unwrap();
        assert_eq!(cfg.profiles.len(), 2);
        assert_eq!(
            cfg.profiles.get("team.base").unwrap().library_root,
            fs::canonicalize(imported_dir.join("library")).unwrap()
        );
        assert_eq!(
            cfg.profiles.get("my.local").unwrap().library_root,
            fs::canonicalize(primary_dir.join("library")).unwrap()
        );

        // Resolution finds both fragments, each in its own library.
        let mut seen = HashSet::new();
        let mut stack = Vec::new();
        let mut out = Vec::new();
        resolve_profile("my.local", &cfg, &mut seen, &mut stack, &mut out).unwrap();
        assert_eq!(out.len(), 2);
    }

    #[test]
    fn test_load_bundle_duplicate_profile_name_across_imports() {
        let primary_dir = mk_tmp("prompter_bundle_dup_primary");
        let imported_dir = mk_tmp("prompter_bundle_dup_import");

        fs::create_dir_all(primary_dir.join("library")).unwrap();
        fs::create_dir_all(imported_dir.join("library")).unwrap();

        fs::write(
            imported_dir.join("config.toml"),
            "\n[clash]\ndepends_on = []\n",
        )
        .unwrap();

        let primary_cfg = format!(
            "\nimport = [\"{}\"]\n\n[clash]\ndepends_on = []\n",
            imported_dir.join("config.toml").display()
        );
        fs::write(primary_dir.join("config.toml"), primary_cfg).unwrap();

        let err = load_config_bundle(&primary_dir.join("config.toml"), None)
            .unwrap_err()
            .to_string();
        assert!(err.contains("Duplicate profile `clash`"), "err={err}");
    }

    #[test]
    fn test_load_bundle_import_cycle() {
        let a_dir = mk_tmp("prompter_cycle_a");
        let b_dir = mk_tmp("prompter_cycle_b");
        fs::create_dir_all(a_dir.join("library")).unwrap();
        fs::create_dir_all(b_dir.join("library")).unwrap();

        let a_path = a_dir.join("config.toml");
        let b_path = b_dir.join("config.toml");
        fs::write(&a_path, format!("import = [\"{}\"]\n", b_path.display())).unwrap();
        fs::write(&b_path, format!("import = [\"{}\"]\n", a_path.display())).unwrap();

        let err = load_config_bundle(&a_path, None).unwrap_err().to_string();
        assert!(err.contains("Import cycle"), "err={err}");
    }

    #[test]
    fn test_load_bundle_explicit_library_key() {
        let dir = mk_tmp("prompter_bundle_explicit_lib");
        fs::create_dir_all(dir.join("alt_library/sub")).unwrap();
        fs::write(dir.join("alt_library/sub/x.md"), b"X").unwrap();
        fs::write(
            dir.join("config.toml"),
            r#"
library = "alt_library"

[p]
depends_on = ["sub/x.md"]
"#,
        )
        .unwrap();

        let cfg = load_config_bundle(&dir.join("config.toml"), None).unwrap();
        let expected = fs::canonicalize(dir.join("alt_library")).unwrap();
        assert_eq!(cfg.profiles.get("p").unwrap().library_root, expected);
    }

    #[test]
    fn test_load_bundle_import_post_prompt_only_from_primary() {
        let primary_dir = mk_tmp("prompter_pp_primary");
        let imported_dir = mk_tmp("prompter_pp_import");
        fs::create_dir_all(primary_dir.join("library")).unwrap();
        fs::create_dir_all(imported_dir.join("library")).unwrap();

        fs::write(
            imported_dir.join("config.toml"),
            r#"
post_prompt = "from imported"
"#,
        )
        .unwrap();
        let primary_cfg = format!(
            r#"
import = ["{}"]
post_prompt = "from primary"
"#,
            imported_dir.join("config.toml").display()
        );
        fs::write(primary_dir.join("config.toml"), primary_cfg).unwrap();
        let cfg = load_config_bundle(&primary_dir.join("config.toml"), None).unwrap();
        assert_eq!(cfg.post_prompt.as_deref(), Some("from primary"));

        // Imported's post_prompt is ignored even if primary has none.
        fs::write(
            primary_dir.join("config.toml"),
            format!(
                r#"
import = ["{}"]
"#,
                imported_dir.join("config.toml").display()
            ),
        )
        .unwrap();
        let cfg2 = load_config_bundle(&primary_dir.join("config.toml"), None).unwrap();
        assert!(cfg2.post_prompt.is_none());
    }

    fn expect_run(args: Vec<String>) -> AppMode {
        let mode = parse_args_from(args).unwrap();
        assert!(matches!(mode, AppMode::Run { .. }), "expected run");
        mode
    }

    #[test]
    fn parse_args_run_with_separator() {
        let args = vec![
            "prompter".into(),
            "run".into(),
            "--separator".into(),
            "\\n--\\n".into(),
            "profile".into(),
        ];
        let AppMode::Run {
            profiles,
            family,
            separator,
            pre_prompt,
            post_prompt,
            framing,
            config,
            json,
        } = expect_run(args)
        else {
            unreachable!()
        };
        assert_eq!(profiles, vec!["profile".to_string()]);
        assert_eq!(family, None);
        assert_eq!(separator, Some("\n--\n".into()));
        assert_eq!(pre_prompt, None);
        assert_eq!(post_prompt, None);
        assert_eq!(framing, Framing::Full);
        assert!(config.is_none());
        assert!(!json);
    }

    #[test]
    fn parse_args_run_with_family() {
        let args = vec![
            "prompter".into(),
            "run".into(),
            "--family".into(),
            "gpt".into(),
            "profile".into(),
        ];
        let AppMode::Run {
            profiles, family, ..
        } = expect_run(args)
        else {
            unreachable!()
        };
        assert_eq!(profiles, vec!["profile".to_string()]);
        assert_eq!(family, Some(FamilyName::new("gpt").unwrap()));
    }

    #[test]
    fn parse_args_rejects_family_path_traversal() {
        let args = vec![
            "prompter".into(),
            "run".into(),
            "--family".into(),
            "../gpt".into(),
            "profile".into(),
        ];
        let error = parse_args_from(args).unwrap_err().to_string();
        assert!(error.contains("family name must be one non-empty path component"));
    }

    #[test]
    fn parse_args_run_with_pre_prompt() {
        let args = vec![
            "prompter".into(),
            "run".into(),
            "--pre-prompt".into(),
            "Custom pre-prompt".into(),
            "profile".into(),
        ];
        let AppMode::Run {
            profiles,
            separator,
            pre_prompt,
            ..
        } = expect_run(args)
        else {
            unreachable!()
        };
        assert_eq!(profiles, vec!["profile".to_string()]);
        assert_eq!(separator, None);
        assert_eq!(pre_prompt, Some("Custom pre-prompt".into()));
    }

    #[test]
    fn parse_args_run_with_bare_flag() {
        let args = vec![
            "prompter".into(),
            "run".into(),
            "--bare".into(),
            "profile".into(),
        ];
        let AppMode::Run {
            profiles, framing, ..
        } = expect_run(args)
        else {
            unreachable!()
        };
        assert_eq!(profiles, vec!["profile".to_string()]);
        assert_eq!(framing, Framing::Bare);
    }

    #[test]
    fn parse_args_system_with_bare_flag() {
        let args = vec![
            "prompter".into(),
            "system".into(),
            "--bare".into(),
            "extra".into(),
        ];
        let AppMode::Run {
            profiles, framing, ..
        } = expect_run(args)
        else {
            unreachable!()
        };
        // System prepends the system base profile before any extras.
        assert_eq!(
            profiles,
            vec![SYSTEM_BASE_PROFILE.to_string(), "extra".to_string()]
        );
        assert_eq!(framing, Framing::Bare);
    }

    #[test]
    fn parse_args_run_with_multiple_profiles() {
        let args = vec![
            "prompter".into(),
            "run".into(),
            "profile1".into(),
            "profile2".into(),
            "profile3.nested".into(),
        ];
        let AppMode::Run { profiles, .. } = expect_run(args) else {
            unreachable!()
        };
        assert_eq!(
            profiles,
            vec![
                "profile1".to_string(),
                "profile2".to_string(),
                "profile3.nested".to_string(),
            ]
        );
    }

    #[test]
    fn parse_args_bare_subcommands() {
        let args = vec!["prompter".into(), "list".into()];
        assert!(matches!(
            parse_args_from(args).unwrap(),
            AppMode::List {
                config: None,
                json: false
            }
        ));
        let args = vec!["prompter".into(), "validate".into()];
        assert!(matches!(
            parse_args_from(args).unwrap(),
            AppMode::Validate {
                config: None,
                json: false
            }
        ));
        let args = vec!["prompter".into(), "init".into()];
        assert!(matches!(parse_args_from(args).unwrap(), AppMode::Init));
        let args = vec!["prompter".into(), "meta".into(), "version".into()];
        assert!(matches!(
            parse_args_from(args).unwrap(),
            AppMode::Version { json: false }
        ));
    }

    #[test]
    fn parse_args_config_before_subcommand() {
        let args = vec![
            "prompter".into(),
            "--config".into(),
            "custom/config.toml".into(),
            "list".into(),
        ];
        let AppMode::List { config, json } = parse_args_from(args).unwrap() else {
            panic!("expected list mode");
        };
        assert_eq!(config, Some(PathBuf::from("custom/config.toml")));
        assert!(!json);
    }

    #[test]
    fn parse_args_config_after_run_subcommand() {
        let args = vec![
            "prompter".into(),
            "run".into(),
            "--config".into(),
            "custom/config.toml".into(),
            "profile".into(),
        ];
        let AppMode::Run { config, json, .. } = parse_args_from(args).unwrap() else {
            panic!("expected run mode");
        };
        assert_eq!(config, Some(PathBuf::from("custom/config.toml")));
        assert!(!json);
    }

    struct FailAfterN {
        writes_done: usize,
        fail_on: usize,
    }

    impl Write for FailAfterN {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.writes_done += 1;
            if self.writes_done == self.fail_on {
                Err(io::Error::other("synthetic write failure"))
            } else {
                Ok(buf.len())
            }
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn test_render_to_writer_write_error_on_separator() {
        let lib = mk_tmp("prompter_write_err_sep");
        fs::create_dir_all(lib.join("a")).unwrap();
        fs::write(lib.join("a/x.md"), b"AX").unwrap();
        fs::write(lib.join("a/y.md"), b"AY").unwrap();
        let cfg = cfg_with_lib([("p", vec!["a/x.md", "a/y.md"])], &lib, None);
        let mut w = FailAfterN {
            writes_done: 0,
            fail_on: 3,
        }; // pre-prompt ok, system prefix ok, fail on separator
        let err = super::render_to_writer(
            &cfg,
            &mut w,
            &["p".to_string()],
            None,
            Some("--"),
            None,
            None,
            Framing::Full,
            JsonOutput::Text,
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("Write error"), "err={err}");
    }

    #[test]
    fn test_render_to_writer_write_error_on_file() {
        let lib = mk_tmp("prompter_write_err_file");
        fs::create_dir_all(lib.join("a")).unwrap();
        fs::write(lib.join("a/x.md"), b"AX").unwrap();
        let cfg = cfg_with_lib([("p", vec!["a/x.md"])], &lib, None);
        let mut w = FailAfterN {
            writes_done: 0,
            fail_on: 1,
        }; // fail on first write (pre-prompt)
        let err = super::render_to_writer(
            &cfg,
            &mut w,
            &["p".to_string()],
            None,
            Some("--"),
            None,
            None,
            Framing::Full,
            JsonOutput::Text,
        )
        .unwrap_err()
        .to_string();
        assert!(err.contains("Write error"), "err={err}");
    }

    #[test]
    #[ignore = "Fails on CI due to HOME environment variable concurrency issues"]
    #[allow(unsafe_code)]
    fn test_run_list_and_validate_with_home_injection() {
        let home = mk_tmp("prompter_home_unit_ok");
        let cfg_dir = home.join(".config/prompter");
        let lib_dir = home.join(".local/prompter/library");
        fs::create_dir_all(&cfg_dir).unwrap();
        fs::create_dir_all(lib_dir.join("a")).unwrap();
        fs::create_dir_all(lib_dir.join("f")).unwrap();
        fs::write(lib_dir.join("a/x.md"), b"AX\n").unwrap();
        fs::write(lib_dir.join("f/y.md"), b"FY\n").unwrap();
        let cfg = r#"
[child]
depends_on = ["a/x.md"]

[root]
depends_on = ["child", "f/y.md"]
"#;
        fs::write(cfg_dir.join("config.toml"), cfg).unwrap();
        let prev_home = env::var("HOME").ok();
        unsafe {
            env::set_var("HOME", &home);
        }
        assert!(super::run_validate_stdout(None, JsonOutput::Text).is_ok());
        assert!(super::run_list_stdout(None, JsonOutput::Text).is_ok());
        if let Some(prev) = prev_home {
            unsafe {
                env::set_var("HOME", prev);
            }
        } else {
            unsafe {
                env::remove_var("HOME");
            }
        }
    }

    #[test]
    #[allow(unsafe_code)]
    fn test_run_validate_with_home_injection_failure() {
        let home = mk_tmp("prompter_home_unit_bad");
        let cfg_dir = home.join(".config/prompter");
        let lib_dir = home.join(".local/prompter/library");
        fs::create_dir_all(&cfg_dir).unwrap();
        fs::create_dir_all(&lib_dir).unwrap();
        let cfg = r#"
[root]
depends_on = ["missing.md", "unknown_profile"]
"#;
        fs::write(cfg_dir.join("config.toml"), cfg).unwrap();
        let prev_home = env::var("HOME").ok();
        unsafe {
            env::set_var("HOME", &home);
        }
        let err = super::run_validate_stdout(None, JsonOutput::Text).unwrap_err();
        assert!(
            err.to_string().contains("Missing file") && err.to_string().contains("Unknown profile"),
            "err={err}"
        );
        if let Some(prev) = prev_home {
            unsafe {
                env::set_var("HOME", prev);
            }
        } else {
            unsafe {
                env::remove_var("HOME");
            }
        }
    }

    #[test]
    fn render_to_vec_returns_bytes() {
        // This test uses the real config, so it depends on prompter being configured.
        // If no config exists, it should return an error, not panic.
        let result = render_to_vec(&[], None, None);
        // Empty profiles should succeed (produces empty or minimal output)
        assert!(result.is_ok() || result.is_err());
    }

    #[test]
    fn available_profiles_returns_sorted() {
        let result = available_profiles(None);
        if let Ok(profiles) = result {
            let mut sorted = profiles.clone();
            sorted.sort();
            assert_eq!(profiles, sorted);
        }
        // If no config, error is acceptable
    }
}