dodot-lib 5.0.0

Core library for dodot dotfiles manager
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
//! Integration tests for gating behaviour: §7.4 passive-command contract (#121), cross-pack conflict detection, and the C3/C5/gate-before-preprocess regression suite.

#![allow(unused_imports)]

use std::sync::Arc;

use crate::commands;
use crate::config::ConfigManager;
use crate::datastore::{CommandOutput, CommandRunner, FilesystemDataStore};
use crate::fs::Fs;
use crate::packs::orchestration::ExecutionContext;
use crate::paths::Pather;
use crate::render;
use crate::testing::TempEnvironment;
use crate::Result;
use standout_render::OutputMode;

use super::support::{make_ctx, make_ctx_with_runner, CannedRunner};

// ── §7.4 passive-command contract (#121) ───────────────────

#[test]
fn status_does_not_write_to_datastore() {
    // §7.4: passive commands MUST NOT mutate the datastore.
    // Running `up` once primes the data dir; running `status`
    // afterwards must leave that state byte-identical.
    let env = TempEnvironment::builder()
        .pack("app")
        .file("config.toml.tmpl", "name = {{ name }}")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\n")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    let snapshot = snapshot_dir_contents(&env, env.paths.data_dir());

    // Two consecutive status runs must leave data_dir unchanged.
    commands::status::status(None, &ctx).unwrap();
    commands::status::status(None, &ctx).unwrap();

    let after = snapshot_dir_contents(&env, env.paths.data_dir());
    assert_eq!(
        snapshot, after,
        "status must be byte-identical to the post-up snapshot — \
         no datastore writes allowed"
    );
}

#[test]
fn up_dry_run_does_not_write_to_datastore() {
    // Pin the same §7.4 contract for `up --dry-run`.
    let env = TempEnvironment::builder()
        .pack("app")
        .file("config.toml.tmpl", "name = {{ name }}")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\n")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();
    let snapshot = snapshot_dir_contents(&env, env.paths.data_dir());

    let mut dry_ctx = make_ctx(&env);
    dry_ctx.dry_run = true;
    commands::up::up(None, &dry_ctx).unwrap();

    let after = snapshot_dir_contents(&env, env.paths.data_dir());
    assert_eq!(
        snapshot, after,
        "dry-run must be byte-identical to the post-up snapshot"
    );
}

#[test]
fn install_template_dry_run_emits_correct_sentinel_without_writing_rendered_file() {
    // The §7.4 unblocker: in Passive mode the rendered file isn't
    // on disk, so the install handler used to fail to compute its
    // sentinel. With `rendered_bytes` threaded through, dry-run now
    // emits a Run intent with the same sentinel as the active path
    // would — without ever writing the rendered file. (#121)
    let env = TempEnvironment::builder()
        .pack("app")
        .file("install.sh.tmpl", "#!/bin/sh\necho hello {{ name }}")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\n")
        .done()
        .build();

    // First up establishes the baseline so Passive mode has
    // something to read. no_provision = false so the install
    // handler actually plans Run intents (the default test ctx
    // suppresses code-execution handlers).
    let mut ctx = make_ctx(&env);
    ctx.no_provision = false;
    commands::up::up(None, &ctx).unwrap();

    // Capture the active sentinel (it lives in the executed
    // RunCommand operation).
    let active_intents = crate::packs::orchestration::collect_pack_intents(
        &crate::packs::Pack::new(
            "app".into(),
            env.dotfiles_root.join("app"),
            ctx.config_manager
                .config_for_pack(&env.dotfiles_root.join("app"))
                .unwrap()
                .to_handler_config(),
        ),
        &ctx,
    )
    .unwrap();
    let active_sentinel = active_intents
        .iter()
        .find_map(|i| match i {
            crate::operations::HandlerIntent::Run { sentinel, .. } => Some(sentinel.clone()),
            _ => None,
        })
        .expect("active path must produce a Run intent for install.sh");

    // Snapshot the rendered datastore file's existence — Passive
    // must not modify it, but it should already exist from the
    // earlier active up.
    let rendered_path = env
        .paths
        .handler_data_dir("app", "preprocessed")
        .join("install.sh");
    assert!(
        ctx.fs.exists(&rendered_path),
        "active up must have written the rendered file"
    );
    let rendered_before = ctx.fs.read_file(&rendered_path).unwrap();

    // Now plan via dry-run; the install handler must produce the
    // same sentinel from in-memory bytes. Same no_provision = false
    // so the handler actually emits intents.
    let mut dry_ctx = make_ctx(&env);
    dry_ctx.no_provision = false;
    dry_ctx.dry_run = true;
    let plan = crate::packs::orchestration::plan_pack(
        &crate::packs::Pack::new(
            "app".into(),
            env.dotfiles_root.join("app"),
            dry_ctx
                .config_manager
                .config_for_pack(&env.dotfiles_root.join("app"))
                .unwrap()
                .to_handler_config(),
        ),
        &dry_ctx,
        crate::preprocessing::PreprocessMode::Passive,
    )
    .unwrap();
    let dry_sentinel = plan
        .intents
        .iter()
        .find_map(|i| match i {
            crate::operations::HandlerIntent::Run { sentinel, .. } => Some(sentinel.clone()),
            _ => None,
        })
        .expect("passive path must produce a Run intent for install.sh");

    assert_eq!(
        active_sentinel, dry_sentinel,
        "passive sentinel must match active — same rendered bytes either way"
    );
    let rendered_after = ctx.fs.read_file(&rendered_path).unwrap();
    assert_eq!(
        rendered_before, rendered_after,
        "passive must not rewrite the rendered file"
    );
}

#[test]
fn up_dry_run_first_time_pack_with_install_template_does_not_error() {
    // Regression for Copilot review on PR #126: a first-time pack
    // containing `install.sh.tmpl` (no baseline yet, no rendered
    // file on disk) must not crash dry-run intent collection. The
    // install handler used to read `m.absolute_path` unconditionally
    // and propagate an Fs error; now it skips intent generation for
    // the placeholder match instead. Same shape for `Brewfile.tmpl`
    // / homebrew handler.
    let env = TempEnvironment::builder()
        .pack("setup")
        .file("install.sh.tmpl", "#!/bin/sh\necho hello {{ name }}")
        .file("Brewfile.tmpl", "brew '{{ pkg }}'")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\npkg = \"jq\"\n")
        .done()
        .build();

    let mut dry_ctx = make_ctx(&env);
    dry_ctx.no_provision = false;
    dry_ctx.dry_run = true;

    // The fix: this returns Ok and emits zero Run intents (the
    // placeholders skip intent generation cleanly). Pre-fix, the
    // install/homebrew handlers tried to read missing rendered
    // files and propagated an Fs error.
    let result = commands::up::up(None, &dry_ctx).unwrap();
    assert!(result.dry_run);
}

#[test]
fn passive_first_time_pack_surfaces_pending_placeholder() {
    // §7.4 acceptance: a passive command on a brand-new pack with
    // no baseline cache yet must surface a coherent placeholder
    // (template stripped name, status pending), never panic, never
    // fall through to template evaluation. (#121)
    let env = TempEnvironment::builder()
        .pack("app")
        .file("greet.tmpl", "hello {{ name }}")
        .config("[preprocessor.template.vars]\nname = \"Alice\"\n")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    let files = &result.packs[0].files;
    assert_eq!(files.len(), 1, "should surface the templated entry");
    assert_eq!(
        files[0].name, "greet",
        "stripped name (not source filename)"
    );
    assert_eq!(
        files[0].status, "pending",
        "first-time template before any up: pending"
    );
}

/// Snapshot a directory tree (file contents + directory paths) to a
/// stable signature for the §7.4 no-mutation contract tests. Each
/// entry is keyed by absolute path; files map to `Some(contents)`,
/// directories to `None`. Comparing two snapshots for equality is
/// equivalent to "directory tree is byte-identical, including empty
/// directories." Including dir paths catches mutations like
/// `mkdir <data_dir>/<pack>/preprocessed` that would silently slip
/// past a contents-only check.
///
/// Unreadable entries / read errors propagate as panics rather than
/// silent skips — a passive command that produces an unreadable
/// entry under `<data_dir>` is itself a §7.4 violation worth
/// failing the test on.
fn snapshot_dir_contents(
    env: &crate::testing::TempEnvironment,
    root: &std::path::Path,
) -> std::collections::BTreeMap<std::path::PathBuf, Option<Vec<u8>>> {
    use std::collections::BTreeMap;
    let mut out = BTreeMap::new();
    if !env.fs.exists(root) {
        return out;
    }
    let mut stack: Vec<std::path::PathBuf> = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let entries = env
            .fs
            .read_dir(&dir)
            .unwrap_or_else(|e| panic!("snapshot_dir_contents: read_dir({dir:?}): {e}"));
        for entry in entries {
            if entry.is_dir {
                out.insert(entry.path.clone(), None);
                stack.push(entry.path);
            } else {
                let bytes = env.fs.read_file(&entry.path).unwrap_or_else(|e| {
                    panic!("snapshot_dir_contents: read_file({:?}): {e}", entry.path)
                });
                out.insert(entry.path, Some(bytes));
            }
        }
    }
    out
}

// ── cross-pack conflict detection: up command ──────────────

#[test]
fn up_halts_on_cross_pack_symlink_conflict() {
    // Two packs both deploying a file that resolves to ~/.aliases
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.aliases", "alias a=1")
        .done()
        .pack("pack-b")
        .file("home.aliases", "alias b=2")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();

    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "expected CrossPackConflict, got: {err}"
    );

    // Error message should include both packs and the target
    let msg = err.to_string();
    assert!(msg.contains("pack-a"), "msg: {msg}");
    assert!(msg.contains("pack-b"), "msg: {msg}");
    assert!(msg.contains(".aliases"), "msg: {msg}");
}

#[test]
fn up_halts_no_partial_deployment_on_conflict() {
    // When a conflict is detected, NO packs should be deployed —
    // not even the non-conflicting ones.
    let env = TempEnvironment::builder()
        .pack("conflict-a")
        .file("home.aliases", "a")
        .done()
        .pack("conflict-b")
        .file("home.aliases", "b")
        .done()
        .pack("innocent")
        .file("vimrc", "set nocompatible")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let _err = commands::up::up(None, &ctx).unwrap_err();

    // Nothing should be deployed — check the innocent pack
    env.assert_no_handler_state("innocent", "symlink");
    env.assert_no_handler_state("conflict-a", "symlink");
    env.assert_no_handler_state("conflict-b", "symlink");
}

#[test]
fn up_force_does_not_override_cross_pack_conflict() {
    // --force only helps with pre-existing non-dodot files.
    // Cross-pack conflicts are a config problem and --force must NOT help.
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.aliases", "a")
        .done()
        .pack("pack-b")
        .file("home.aliases", "b")
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.force = true;

    let err = commands::up::up(None, &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "force should NOT override cross-pack conflict, got: {err}"
    );
    assert!(
        err.to_string().contains("--force does not override"),
        "msg: {}",
        err
    );
}

#[test]
fn up_dry_run_still_detects_cross_pack_conflict() {
    let env = TempEnvironment::builder()
        .pack("a")
        .file("bashrc", "a")
        .done()
        .pack("b")
        .file("bashrc", "b")
        .done()
        .build();

    let mut ctx = make_ctx(&env);
    ctx.dry_run = true;

    let err = commands::up::up(None, &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "dry-run should still detect conflicts, got: {err}"
    );
}

/// Regression: `dodot up` on a cross-pack conflict must render the full
/// per-pack listing, notes, and ignored-pack section — not a bare
/// conflicts dump. Before the fix, the CLI handler hardcoded
/// `packs: Vec::new()` on the `CrossPackConflict` branch, so users only
/// saw the trailing conflicts section and lost all context about what
/// *would* have been deployed.
#[test]
fn up_with_cross_pack_conflict_renders_full_status_view() {
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.aliases", "alias a=1")
        .done()
        .pack("pack-b")
        .file("home.aliases", "alias b=2")
        .done()
        // An unrelated pack so we can assert the listing is preserved.
        .pack("innocent")
        .file("home.vimrc", "set nocompatible")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up_or_status_for_conflict(None, &ctx)
        .expect("status fallback should produce Ok on cross-pack conflict");

    // Top-level message explains why nothing deployed.
    assert_eq!(
        result.message.as_deref(),
        Some("Cross-pack conflicts prevent deployment."),
        "got message: {:?}",
        result.message
    );

    // Full per-pack listing is present — the regression was this being empty.
    assert!(
        !result.packs.is_empty(),
        "up-with-conflict must render pack rows, not a bare conflicts dump"
    );
    let pack_names: Vec<&str> = result.packs.iter().map(|p| p.name.as_str()).collect();
    assert!(
        pack_names.contains(&"pack-a"),
        "expected pack-a in listing, got: {:?}",
        pack_names
    );
    assert!(
        pack_names.contains(&"pack-b"),
        "expected pack-b in listing, got: {:?}",
        pack_names
    );
    assert!(
        pack_names.contains(&"innocent"),
        "expected innocent pack in listing, got: {:?}",
        pack_names
    );

    // Conflicts section is still populated — same data the old branch showed.
    assert!(
        !result.conflicts.is_empty(),
        "expected conflicts section to be populated"
    );
    let conflict = &result.conflicts[0];
    assert!(
        conflict.target.contains(".aliases"),
        "conflict target should reference .aliases, got: {}",
        conflict.target
    );

    // Nothing was actually deployed — rows should report pending, not deployed.
    for pack in &result.packs {
        for file in &pack.files {
            assert_ne!(
                file.status, "deployed",
                "{}::{} should not be deployed when conflict blocks up, got: {} ({})",
                pack.name, file.name, file.status, file.status_label
            );
        }
    }
}

#[test]
fn up_no_conflict_when_different_target_files() {
    // Different filenames → different targets → no conflict.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .done()
        .pack("git")
        .file("gitconfig", "[user]\n  name = test")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
}

#[test]
fn up_no_conflict_within_same_pack() {
    // Same pack with multiple files targeting different paths — fine.
    let env = TempEnvironment::builder()
        .pack("shell")
        .file("bashrc", "# bash")
        .file("zshrc", "# zsh")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
}

#[test]
fn up_conflict_via_config_mapping() {
    // Two packs with different source filenames but mapping to the same target
    // via [symlink.targets].
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("settings", "a")
        .config("[symlink]\ntargets = { settings = \"myapp/settings.toml\" }")
        .done()
        .pack("pack-b")
        .file("config", "b")
        .config("[symlink]\ntargets = { config = \"myapp/settings.toml\" }")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();

    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "expected CrossPackConflict for config mapping collision, got: {err}"
    );

    let msg = err.to_string();
    assert!(
        msg.contains("myapp/settings.toml"),
        "should mention the conflicting target: {msg}"
    );
}

#[test]
fn up_conflict_via_home_prefix() {
    // pack-a uses _home/vim/vimrc → ~/.vim/vimrc
    // pack-b uses vim/vimrc (subdirectory) → ~/.config/vim/vimrc
    // These target DIFFERENT paths, so no conflict.
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("_home/vim/vimrc", "a")
        .done()
        .pack("pack-b")
        .file("vim/vimrc", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(
        result.message.as_deref(),
        Some("Packs deployed."),
        "different targets should not conflict"
    );
}

#[test]
fn up_conflict_two_packs_same_home_prefix_target() {
    // Both packs use the `home.X` per-file home opt-in → both resolve
    // to ~/.bashrc, conflict.
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.bashrc", "# a")
        .done()
        .pack("pack-b")
        .file("home.bashrc", "# b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "both targeting ~/.bashrc should conflict, got: {err}"
    );
}

#[test]
fn up_filtered_packs_only_checks_filtered_subset() {
    // pack-a and pack-b conflict, but if we only deploy pack-a,
    // there's no conflict.
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.aliases", "a")
        .done()
        .pack("pack-b")
        .file("home.aliases", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let filter = vec!["pack-a".into()];
    let result = commands::up::up(Some(&filter), &ctx).unwrap();

    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
    assert_eq!(result.packs.len(), 1);
    assert_eq!(result.packs[0].name, "pack-a");
}

#[test]
fn up_same_name_shell_scripts_are_not_conflicts() {
    // Two packs both having aliases.sh is a legitimate and common
    // pattern — they're staged in per-pack namespaced directories.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .pack("git")
        .file("aliases.sh", "alias g=git")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
}

#[test]
fn up_path_dirs_with_different_executables_ok() {
    // Two packs both having bin/ with different file names — no conflict.
    let env = TempEnvironment::builder()
        .pack("tools-a")
        .file("bin/tool-a", "#!/bin/sh")
        .done()
        .pack("tools-b")
        .file("bin/tool-b", "#!/bin/sh")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
}

#[test]
fn up_path_dirs_with_same_executable_name_conflicts() {
    // Two packs both have bin/tool — one would shadow the other in PATH.
    let env = TempEnvironment::builder()
        .pack("tools-a")
        .file("bin/tool", "#!/bin/sh\necho a")
        .done()
        .pack("tools-b")
        .file("bin/tool", "#!/bin/sh\necho b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();
    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "same-name executables across packs should conflict: {err}"
    );
    let msg = err.to_string();
    assert!(msg.contains("tool"), "should mention the executable: {msg}");
    assert!(msg.contains("tools-a"), "should mention pack a: {msg}");
    assert!(msg.contains("tools-b"), "should mention pack b: {msg}");
}

#[test]
fn up_no_cross_handler_conflict() {
    // A shell script and a symlink file with the same name don't conflict
    // because they're in different handler namespaces.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("aliases.sh", "alias vi=vim")
        .done()
        .pack("git")
        .file("gitconfig", "[user]\n  name = test")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    assert_eq!(result.message.as_deref(), Some("Packs deployed."));
}

#[test]
fn up_three_packs_partial_conflict() {
    // Three packs, only two conflict — all three are blocked.
    let env = TempEnvironment::builder()
        .pack("a")
        .file("home.aliases", "a")
        .done()
        .pack("b")
        .file("home.aliases", "b")
        .done()
        .pack("c")
        .file("gitconfig", "c")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();

    assert!(
        matches!(err, crate::DodotError::CrossPackConflict { .. }),
        "should detect the conflict even if not all packs are involved"
    );

    // Verify nothing was deployed
    env.assert_no_handler_state("a", "symlink");
    env.assert_no_handler_state("b", "symlink");
    env.assert_no_handler_state("c", "symlink");
}

#[test]
fn up_error_message_includes_all_conflict_details() {
    let env = TempEnvironment::builder()
        .pack("alpha")
        .file("home.aliases", "a")
        .done()
        .pack("beta")
        .file("home.aliases", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();

    let msg = err.to_string();
    // Should mention both packs
    assert!(msg.contains("alpha"), "msg: {msg}");
    assert!(msg.contains("beta"), "msg: {msg}");
    // Should mention the handler
    assert!(msg.contains("symlink"), "msg: {msg}");
    // Should mention the target path
    assert!(msg.contains(".aliases"), "msg: {msg}");
}

// ── cross-pack conflict detection: status command ──────────

#[test]
fn status_warns_on_potential_cross_pack_conflict() {
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("home.aliases", "a")
        .done()
        .pack("pack-b")
        .file("home.aliases", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    // Status should still succeed (it's informational) and surface the
    // conflict as structured data on the result.
    assert_eq!(result.conflicts.len(), 1, "should detect one conflict");
    let c = &result.conflicts[0];
    assert_eq!(c.kind, "symlink");
    let packs: Vec<&str> = c.claimants.iter().map(|cl| cl.pack.as_str()).collect();
    assert!(packs.contains(&"pack-a"), "claimants: {:?}", c.claimants);
    assert!(packs.contains(&"pack-b"), "claimants: {:?}", c.claimants);
}

#[test]
fn status_no_warnings_without_conflicts() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "set nocompatible")
        .done()
        .pack("git")
        .file("gitconfig", "[user]\n  name = test")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    assert!(
        result.warnings.is_empty(),
        "no warnings expected, got: {:?}",
        result.warnings
    );
    assert!(
        result.conflicts.is_empty(),
        "no conflicts expected, got: {:?}",
        result.conflicts
    );
}

#[test]
fn status_shows_conflict_even_when_not_deployed() {
    // Neither pack is deployed yet — status should still show the
    // potential conflict.
    let env = TempEnvironment::builder()
        .pack("a")
        .file("bashrc", "a")
        .done()
        .pack("b")
        .file("bashrc", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    // Both packs should show as pending
    for pack in &result.packs {
        for file in &pack.files {
            assert_eq!(file.status, "pending");
        }
    }

    // Conflict data should still be emitted.
    assert!(
        !result.conflicts.is_empty(),
        "should flag potential conflict even when undeployed"
    );
}

#[test]
fn status_filtered_to_one_pack_no_conflict_warning() {
    // If we only ask about one pack, no cross-pack comparison happens.
    let env = TempEnvironment::builder()
        .pack("a")
        .file("home.aliases", "a")
        .done()
        .pack("b")
        .file("home.aliases", "b")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let filter = vec!["a".into()];
    let result = commands::status::status(Some(&filter), &ctx).unwrap();

    assert!(
        result.conflicts.is_empty(),
        "single-pack filter should not produce cross-pack conflicts"
    );
}

#[test]
fn status_conflict_with_config_mapping() {
    let env = TempEnvironment::builder()
        .pack("pack-a")
        .file("settings", "a")
        .config("[symlink]\ntargets = { settings = \"myapp/settings.toml\" }")
        .done()
        .pack("pack-b")
        .file("config", "b")
        .config("[symlink]\ntargets = { config = \"myapp/settings.toml\" }")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    assert_eq!(
        result.conflicts.len(),
        1,
        "config mapping collision should surface one conflict"
    );
    assert!(
        result.conflicts[0].target.contains("settings.toml"),
        "should mention the conflicting target: {:?}",
        result.conflicts[0]
    );
}

// ── C3: pack-level [pack] os ────────────────────────────────────

#[test]
fn pack_os_inactive_pack_surfaces_in_status() {
    // Use an OS value that no real host reports as `dodot.os` so the
    // test is portable across darwin and linux CI.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("vimrc", "x")
        .done()
        .pack("mac-only")
        .file("install.sh", "#!/bin/sh\necho mac")
        .config("[pack]\nos = [\"nonexistent-os\"]")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    let active_pack_names: Vec<&str> = result.packs.iter().map(|p| p.name.as_str()).collect();
    assert_eq!(active_pack_names, vec!["vim"]);

    assert_eq!(
        result.inactive_packs.len(),
        1,
        "{:?}",
        result.inactive_packs
    );
    let entry = &result.inactive_packs[0];
    assert!(entry.starts_with("mac-only"), "{entry}");
    assert!(entry.contains("os=nonexistent-os"), "{entry}");
    assert!(entry.contains("current="), "{entry}");

    let output = render::render("pack-status", &result, OutputMode::Text).unwrap();
    assert!(output.contains("Inactive on this OS"), "output: {output}");
    assert!(output.contains("mac-only"), "output: {output}");
}

#[test]
fn pack_os_active_pack_runs_normally() {
    // List several OSes including the current target_os values for
    // both darwin and linux so this passes on either host.
    let env = TempEnvironment::builder()
        .pack("portable")
        .file("vimrc", "x")
        .config("[pack]\nos = [\"darwin\", \"linux\", \"windows\"]")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();

    let active_pack_names: Vec<&str> = result.packs.iter().map(|p| p.name.as_str()).collect();
    assert_eq!(active_pack_names, vec!["portable"]);
    assert!(result.inactive_packs.is_empty());
}

#[test]
fn pack_os_macos_alias_matches_darwin_target() {
    // On a darwin host, [pack] os = ["macos"] should match.
    // Skip on non-darwin hosts since we can't fake target_os here.
    if !cfg!(target_os = "macos") {
        return;
    }
    let env = TempEnvironment::builder()
        .pack("mac")
        .file("vimrc", "x")
        .config("[pack]\nos = [\"macos\"]")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();
    let names: Vec<&str> = result.packs.iter().map(|p| p.name.as_str()).collect();
    assert_eq!(names, vec!["mac"]);
    assert!(result.inactive_packs.is_empty());
}

#[test]
fn pack_os_inactive_pack_emits_no_operations_in_up() {
    // `dodot up` on an inactive pack should produce a successful, empty
    // PackResult — same shape `.dodotignore` would have if it reached
    // the execute() loop.
    let env = TempEnvironment::builder()
        .pack("mac-only")
        .file("Brewfile", "brew \"ripgrep\"")
        .config("[pack]\nos = [\"nonexistent-os\"]")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::up::up(None, &ctx).unwrap();
    // No deployed pack rows.
    assert!(result.packs.is_empty(), "packs: {:?}", result.packs);
}

// ── C5: adopt --only-os ─────────────────────────────────────────

#[test]
fn adopt_only_os_wraps_file_in_gate_dir() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("placeholder", "")
        .done()
        .home_file(".vimrc", "set nocompatible")
        .build();
    let ctx = make_ctx(&env);
    let source = env.home.join(".vimrc");

    commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        Some("darwin"),
        &ctx,
    )
    .unwrap();

    // File is wrapped in `_darwin/` inside the pack — the in-pack
    // path becomes `_darwin/home.vimrc`. On `dodot up`, the gate
    // dir strips on darwin and the `home.X` prefix routes the file
    // to ~/.vimrc.
    env.assert_regular_file(
        &env.dotfiles_root.join("vim/_darwin/home.vimrc"),
        "set nocompatible",
    );
    assert!(env.fs.is_symlink(&source));
}

#[test]
fn adopt_only_os_unknown_label_errors() {
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("placeholder", "")
        .done()
        .home_file(".vimrc", "x")
        .build();
    let ctx = make_ctx(&env);
    let source = env.home.join(".vimrc");

    let err = commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        Some("nonexistent-label"),
        &ctx,
    )
    .unwrap_err();
    let msg = format!("{err}");
    assert!(msg.contains("nonexistent-label"), "missing label: {msg}");
    assert!(msg.contains("--only-os"), "missing flag: {msg}");
}

#[test]
fn adopt_only_os_user_defined_label_works() {
    // A user-defined label in root config is recognised by adopt.
    let env = TempEnvironment::builder()
        .pack("vim")
        .file("placeholder", "")
        .done()
        .home_file(".vimrc", "x")
        .build();
    env.fs
        .write_file(
            &env.dotfiles_root.join(".dodot.toml"),
            b"[gates]\nlaptop = { hostname = \"mbp\" }\n",
        )
        .unwrap();
    let ctx = make_ctx(&env);
    let source = env.home.join(".vimrc");

    commands::adopt::adopt(
        Some("vim"),
        std::slice::from_ref(&source),
        false,
        false,
        false,
        Some("laptop"),
        &ctx,
    )
    .unwrap();

    env.assert_regular_file(&env.dotfiles_root.join("vim/_laptop/home.vimrc"), "x");
}

// ── Gate-before-preprocess regression ───────────────────────────

#[test]
fn gate_failed_template_does_not_render_at_up() {
    // Regression guard: a gate-failed template (e.g.
    // `aliases._linux.sh.tmpl` on a darwin host) must NOT be expanded by
    // the template preprocessor. If the gate check ran AFTER preprocessing,
    // MiniJinja would render the template and fire secret-provider calls and
    // baseline-cache writes for entries the user explicitly opted out of.
    //
    // Two independent assertions, each catching a distinct failure mode:
    //
    // 1. **Functional**: the template uses `{{ undefined_variable }}`,
    //    a strict-undefined error if MiniJinja runs. If the gate-failed
    //    template reaches the engine, pack planning fails and the
    //    co-located `home.profile` plain file is NOT deployed. Asserting
    //    `~/.profile` exists after `up` proves planning succeeded.
    //
    // 2. **Side-effect**: even if planning happened to succeed somehow,
    //    a render would write a baseline-cache JSON under
    //    `<cache_dir>/preprocessor/p/template/`. Its absence proves the
    //    engine never fired.
    let gated = if cfg!(target_os = "macos") {
        "linux"
    } else if cfg!(target_os = "linux") {
        "darwin"
    } else {
        return; // skip on unsupported hosts
    };
    let template_name = format!("aliases._{gated}.sh.tmpl");
    let env = TempEnvironment::builder()
        .pack("p")
        .file(&template_name, "alias x={{ undefined_variable }}")
        // Co-located plain file. Its deployment proves pack planning
        // didn't abort because of the gated template.
        .file("home.profile", "export PATH=$PATH:~/.local/bin")
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    // (1) The plain file must be deployed.
    let profile_link = env.home.join(".profile");
    assert!(
        env.fs.exists(&profile_link),
        "co-located plain file was not deployed; pack planning likely failed \
         because the gated template still reached the template engine: {profile_link:?}"
    );

    // (2) No baseline cache for the gated source.
    let baseline_dir = ctx.paths.cache_dir().join("preprocessor/p/template");
    if env.fs.exists(&baseline_dir) {
        let baselines = env.fs.read_dir(&baseline_dir).unwrap_or_default();
        assert!(
            baselines.is_empty(),
            "preprocessor wrote {} baseline file(s) for a gated-out template: {:?}",
            baselines.len(),
            baselines.iter().map(|e| e.name.clone()).collect::<Vec<_>>()
        );
    }

    // No rendered output in the preprocessed dir for the gated template.
    let preprocessed = ctx.paths.data_dir().join("packs/p/preprocessed/aliases.sh");
    assert!(
        !env.fs.exists(&preprocessed),
        "gated-out template was rendered to datastore at {preprocessed:?}"
    );
    // And no shell stage link.
    let shell_link = ctx.paths.data_dir().join("packs/p/shell/aliases.sh");
    assert!(
        !env.fs.exists(&shell_link),
        "gated-out template surfaced as a shell-stage entry at {shell_link:?}"
    );
}

#[test]
fn up_catches_mappings_gates_filename_conflict() {
    // Round-2 review feedback (orchestration.rs:637): the `up` path
    // strips basename gates BEFORE match_entries, so the
    // [mappings.gates] vs filename-gate conflict needs to fire in
    // filter_basename_gates rather than match_entries. Without the
    // fix, this combination would silently pass through `up`.
    let env = TempEnvironment::builder()
        .pack("p")
        .file("install._darwin.sh", "echo x")
        .config("[mappings.gates]\n\"install._darwin.sh\" = \"linux\"\n")
        .done()
        .build();
    let ctx = make_ctx(&env);

    let err = commands::up::up(None, &ctx).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("gate-routing conflict"), "msg: {msg}");
    assert!(msg.contains("install._darwin.sh"), "msg: {msg}");
}

#[test]
fn up_rejects_invalid_mappings_gates_glob() {
    // Round-2 review feedback (rules/mod.rs:387): invalid glob
    // patterns in [mappings.gates] used to be silently dropped via
    // `.ok()`. They now hard-error so a typo is loud, not silent.
    let env = TempEnvironment::builder()
        .pack("p")
        .file("vimrc", "x")
        .config("[mappings.gates]\n\"[unclosed\" = \"darwin\"\n")
        .done()
        .build();
    let ctx = make_ctx(&env);
    let err = commands::up::up(None, &ctx).unwrap_err();
    let msg = err.to_string();
    assert!(
        msg.contains("invalid `[mappings.gates]` glob"),
        "msg: {msg}"
    );
}

#[test]
fn status_surfaces_gated_template_under_original_name() {
    // Round-3 review feedback (status.rs:545): without pre-preprocess
    // gate filtering in the status path, a gated template would get
    // partitioned by `preprocess_pack` and replaced by a virtual
    // entry whose path is the *stripped* virtual name (e.g.
    // `aliases.sh`), losing the on-disk source name (`aliases._linux.sh.tmpl`).
    // status would then show the virtual name with no indication it
    // was gated.
    let gated = if cfg!(target_os = "macos") {
        "linux"
    } else if cfg!(target_os = "linux") {
        "darwin"
    } else {
        return;
    };
    let template_name = format!("aliases._{gated}.sh.tmpl");
    let env = TempEnvironment::builder()
        .pack("p")
        .file(&template_name, "alias x=y\n")
        .done()
        .build();

    let ctx = make_ctx(&env);
    let result = commands::status::status(None, &ctx).unwrap();
    assert_eq!(result.packs.len(), 1);
    let files = &result.packs[0].files;
    assert_eq!(files.len(), 1, "files: {files:?}");
    let row = &files[0];
    // The status row must surface under the *source* filename so the
    // user can find the file and the gate that dropped it. If
    // preprocessing fired, the row would name the rendered virtual
    // path instead.
    assert_eq!(
        row.name, template_name,
        "expected source filename in row, not a preprocessed virtual name"
    );
    assert_eq!(row.handler, "gate", "row.handler: {}", row.handler);
}

#[test]
fn up_skips_mappings_gated_template() {
    // Round-3 review feedback (orchestration.rs:645): a
    // `[mappings.gates]`-gated template must not reach the
    // preprocessor. Like the basename-gate regression, we use a
    // template that would error if rendered to prove the engine
    // never fired.
    let gated = if cfg!(target_os = "macos") {
        "linux"
    } else if cfg!(target_os = "linux") {
        "darwin"
    } else {
        return;
    };
    let env = TempEnvironment::builder()
        .pack("p")
        .file("aliases.sh.tmpl", "alias x={{ undefined_variable }}")
        .file("home.profile", "export PATH=$PATH:~/.local/bin")
        .config(&format!(
            "[mappings.gates]\n\"aliases.sh.tmpl\" = \"{gated}\"\n"
        ))
        .done()
        .build();

    let ctx = make_ctx(&env);
    commands::up::up(None, &ctx).unwrap();

    // Plain co-located file deployed → pack planning succeeded.
    let profile_link = env.home.join(".profile");
    assert!(
        env.fs.exists(&profile_link),
        "co-located plain file was not deployed; mapping-gated template \
         likely reached the engine: {profile_link:?}"
    );

    // No baseline cache for the gated template.
    let baseline_dir = ctx.paths.cache_dir().join("preprocessor/p/template");
    if env.fs.exists(&baseline_dir) {
        let baselines = env.fs.read_dir(&baseline_dir).unwrap_or_default();
        assert!(
            baselines.is_empty(),
            "preprocessor wrote {} baseline file(s) for a mapping-gated template: {:?}",
            baselines.len(),
            baselines.iter().map(|e| e.name.clone()).collect::<Vec<_>>()
        );
    }
}