zenops 0.20.0

Declarative system configuration management for shell config and dotfiles.
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
use similar_asserts::assert_eq;
use smol_str::SmolStr;
use zenops::{
    Cmd,
    config_files::{ConfigFilePath, ConfigFilesError},
    error::Error,
    git::GitFileStatus,
    output::{PkgStatus, Status},
    prompt::{PreApplyAnswer, parse_pre_apply_input},
};
use zenops_safe_relative_path::srpath;

use test_env::{Entry, Output, paths};

mod test_env;

#[test]
fn missing_config() {
    let env = test_env::TestEnv::load();

    assert_eq!(
        env.run(&Cmd::Status {
            diff: false,
            all: false
        }),
        Err(Error::Config(zenops::error::ConfigError::OpenDb(
            env.resolve_path(paths::ZENOPS_CONFIG),
            std::io::ErrorKind::NotFound.into()
        )))
    );

    // Check it works with a config file, but no .git repository
    env.write_zenops_file(srpath!("config.toml"), "", None);

    assert_eq!(
        env.run(&Cmd::Status {
            diff: false,
            all: false
        }),
        Ok(Output { entries: vec![] }),
    );

    // Check it works with a .git repository
    env.init_config("");

    assert_eq!(
        env.run(&Cmd::Status {
            diff: false,
            all: false
        }),
        Ok(Output {
            entries: vec![env.git_repo_clean_entry()],
        }),
    );
}

#[test]
fn config_dir_git_status() {
    let env = test_env::TestEnv::load();

    env.init_config("");

    assert_eq!(
        env.run(&Cmd::Status {
            diff: false,
            all: false
        }),
        Ok(Output {
            entries: vec![env.git_repo_clean_entry()],
        })
    );

    env.append_zenops_file(srpath!("config.toml"), "# Modification", None);
    env.write_zenops_file(srpath!("untracked-file"), "# Untracked file", None);

    assert_eq!(
        env.run(&Cmd::Status {
            diff: false,
            all: false
        }),
        Ok(Output {
            entries: vec![
                Entry::Status(Status::Git {
                    repo: env.cfpath("", ConfigFilePath::Zenops),
                    status: GitFileStatus::Modified(srpath!("config.toml").into()),
                }),
                Entry::Status(Status::Git {
                    repo: env.cfpath("", ConfigFilePath::Zenops),
                    status: GitFileStatus::Untracked(srpath!("untracked-file").into()),
                })
            ]
        })
    );
}

#[test]
fn apply_warns_on_uncommitted_changes_with_yes_and_allow_dirty() {
    let env = test_env::TestEnv::load();
    env.init_config("");

    // Modify a tracked file and add an untracked one — neither committed.
    env.append_zenops_file(srpath!("config.toml"), "# Local tweak", None);
    env.write_zenops_file(srpath!("local-note"), "wip", None);

    // --yes --allow-dirty: pre-apply prompt is skipped, warnings still surface, apply runs.
    assert_eq!(
        env.run(&Cmd::Apply {
            pull_config: false,
            yes: true,
            dry_run: false,
            allow_dirty: true,
        }),
        Ok(Output {
            entries: vec![
                Entry::Status(Status::Git {
                    repo: env.cfpath("", ConfigFilePath::Zenops),
                    status: GitFileStatus::Modified(srpath!("config.toml").into()),
                }),
                Entry::Status(Status::Git {
                    repo: env.cfpath("", ConfigFilePath::Zenops),
                    status: GitFileStatus::Untracked(srpath!("local-note").into()),
                }),
            ]
        })
    );
}

#[test]
fn apply_yes_on_dirty_repo_errors_without_allow_dirty() {
    let env = test_env::TestEnv::load();
    env.init_config("");

    env.append_zenops_file(srpath!("config.toml"), "# Local tweak", None);

    assert_eq!(
        env.run(&Cmd::Apply {
            pull_config: false,
            yes: true,
            dry_run: false,
            allow_dirty: false,
        }),
        Err(Error::DirtyRepoRequiresAllowDirty(
            env.resolve_path(paths::ZENOPS_DIR)
        )),
    );
}

#[test]
fn apply_warns_on_deleted_tracked_file() {
    let env = test_env::TestEnv::load();
    env.init_config("");

    // Commit an extra tracked file, then remove it from the working tree.
    env.write_zenops_file(srpath!("extra"), "to be deleted", Some("add extra"));
    env.delete_file(paths::ZENOPS_DIR.safe_join(srpath!("extra")));

    assert_eq!(
        env.run(&Cmd::Apply {
            pull_config: false,
            yes: true,
            dry_run: false,
            allow_dirty: true,
        }),
        Ok(Output {
            entries: vec![Entry::Status(Status::Git {
                repo: env.cfpath("", ConfigFilePath::Zenops),
                status: GitFileStatus::Deleted(srpath!("extra").into()),
            })]
        })
    );
}

#[test]
fn apply_clean_repo_with_yes_does_not_require_allow_dirty() {
    let env = test_env::TestEnv::load();
    env.init_config("");

    assert_eq!(
        env.run(&Cmd::Apply {
            pull_config: false,
            yes: true,
            dry_run: false,
            allow_dirty: false,
        }),
        Ok(Output { entries: vec![] })
    );
}

#[test]
fn parse_pre_apply_input_covers_expected_answers() {
    assert_eq!(parse_pre_apply_input("c"), Some(PreApplyAnswer::Commit));
    assert_eq!(parse_pre_apply_input("C"), Some(PreApplyAnswer::Commit));
    assert_eq!(
        parse_pre_apply_input("commit\n"),
        Some(PreApplyAnswer::Commit)
    );
    assert_eq!(parse_pre_apply_input(""), Some(PreApplyAnswer::Continue));
    assert_eq!(parse_pre_apply_input("\n"), Some(PreApplyAnswer::Continue));
    assert_eq!(parse_pre_apply_input("y"), Some(PreApplyAnswer::Continue));
    assert_eq!(parse_pre_apply_input("YES"), Some(PreApplyAnswer::Continue));
    assert_eq!(parse_pre_apply_input("n"), Some(PreApplyAnswer::Abort));
    assert_eq!(parse_pre_apply_input("abort"), Some(PreApplyAnswer::Abort));
    assert_eq!(parse_pre_apply_input("maybe"), None);
}

#[test]
fn apply_emits_pkg_missing_when_on_plus_detect_misses() {
    // `enable = "on"` says the user expects this pkg. Detect misses on the
    // temp host → push a Status::Pkg{Missing} with the brew-install hint.
    let env = test_env::TestEnv::load();
    env.init_config(
        r#"
        [pkg.ghosttool]
        enable = "on"
        [pkg.ghosttool.install_hint.brew]
        packages = ["ghosttool"]
        [pkg.ghosttool.install_hint.dnf]
        packages = []
        [pkg.ghosttool.install_hint.apt]
        packages = []
        [pkg.ghosttool.install_hint.pacman]
        packages = []
        [pkg.ghosttool.install_hint.cargo]
        packages = []
        [pkg.ghosttool.detect]
        exists = "/definitely/does/not/exist/zenops-test-ghosttool"
    "#,
    );

    // Make brew detectable in this env so the missing-pkg status carries
    // the brew install command. Without this opt-in, pkg detection
    // resolves nothing on the empty controlled PATH and the assertion
    // would be host-dependent.
    env.add_binary("brew");

    let out = env
        .run(&Cmd::Apply {
            pull_config: false,
            yes: true,
            dry_run: false,
            allow_dirty: true,
        })
        .expect("apply should succeed");

    assert!(
        out.entries.contains(&Entry::Status(Status::Pkg {
            pkg: SmolStr::new("ghosttool"),
            status: PkgStatus::Missing {
                install_command: Some("brew install ghosttool".to_string()),
            },
        })),
        "expected Pkg{{Missing}} for ghosttool with brew install hint, got: {:?}",
        out.entries
    );
}

#[test]
fn apply_is_silent_for_detect_variant_miss() {
    // Silence on miss is the point of `enable = "detect"`; no Pkg event.
    let env = test_env::TestEnv::load();
    env.init_config(
        r#"
        [pkg.quietpkg]
        enable = "detect"
        [pkg.quietpkg.install_hint.brew]
        packages = ["quietpkg"]
        [pkg.quietpkg.install_hint.dnf]
        packages = []
        [pkg.quietpkg.install_hint.apt]
        packages = []
        [pkg.quietpkg.install_hint.pacman]
        packages = []
        [pkg.quietpkg.install_hint.cargo]
        packages = []
        [pkg.quietpkg.detect]
        exists = "/definitely/does/not/exist/zenops-test-quietpkg"
    "#,
    );

    let out = env
        .run(&Cmd::Apply {
            pull_config: false,
            yes: true,
            dry_run: false,
            allow_dirty: true,
        })
        .expect("apply should succeed");

    assert!(
        !out.entries.iter().any(|e| matches!(
            e,
            Entry::Status(Status::Pkg { pkg, .. }) if pkg == "quietpkg"
        )),
        "detect-miss should not push any Pkg event, got: {:?}",
        out.entries
    );
}

#[test]
fn apply_pkg_missing_with_no_install_hint_has_no_command() {
    // `on` + detect miss + empty brew packages → Pkg{Missing} without an
    // install command; the user just sees "X is missing".
    let env = test_env::TestEnv::load();
    env.init_config(
        r#"
        [pkg.hintless]
        enable = "on"
        [pkg.hintless.install_hint.brew]
        packages = []
        [pkg.hintless.install_hint.dnf]
        packages = []
        [pkg.hintless.install_hint.apt]
        packages = []
        [pkg.hintless.install_hint.pacman]
        packages = []
        [pkg.hintless.install_hint.cargo]
        packages = []
        [pkg.hintless.detect]
        exists = "/definitely/does/not/exist/zenops-test-hintless"
    "#,
    );

    let out = env
        .run(&Cmd::Apply {
            pull_config: false,
            yes: true,
            dry_run: false,
            allow_dirty: true,
        })
        .expect("apply should succeed");

    assert!(
        out.entries.contains(&Entry::Status(Status::Pkg {
            pkg: SmolStr::new("hintless"),
            status: PkgStatus::Missing {
                install_command: None,
            },
        })),
        "expected Pkg{{Missing}} without install_command, got: {:?}",
        out.entries
    );
}

#[test]
fn apply_no_pkg_missing_when_detect_is_empty() {
    // `on` + no detect → nothing to check, no signal to emit. This is the
    // always-on meta-pkg shape (local-bin, bashrc-chain, etc.).
    let env = test_env::TestEnv::load();
    env.init_config(
        r#"
        [pkg.metapkg]
        enable = "on"
        [pkg.metapkg.install_hint.brew]
        packages = []
        [pkg.metapkg.install_hint.dnf]
        packages = []
        [pkg.metapkg.install_hint.apt]
        packages = []
        [pkg.metapkg.install_hint.pacman]
        packages = []
        [pkg.metapkg.install_hint.cargo]
        packages = []
    "#,
    );

    let out = env
        .run(&Cmd::Apply {
            pull_config: false,
            yes: true,
            dry_run: false,
            allow_dirty: true,
        })
        .expect("apply should succeed");

    assert!(
        !out.entries.iter().any(|e| matches!(
            e,
            Entry::Status(Status::Pkg { pkg, .. }) if pkg == "metapkg"
        )),
        "empty-detect pkg should not emit any Pkg event, got: {:?}",
        out.entries
    );
}

#[test]
fn apply_filters_pkg_by_when_shell() {
    let env = test_env::TestEnv::load();
    env.init_config(
        r#"
        [shell]
        type = "zsh"
        [shell.environment]
        [shell.alias]

        [pkg.alien-shell]
        enable = "on"
        when = "bash"
        [pkg.alien-shell.install_hint.brew]
        packages = []
        [pkg.alien-shell.install_hint.dnf]
        packages = []
        [pkg.alien-shell.install_hint.apt]
        packages = []
        [pkg.alien-shell.install_hint.pacman]
        packages = []
        [pkg.alien-shell.install_hint.cargo]
        packages = []
        [[pkg.alien-shell.shell.interactive_init.zsh]]
        type = "line"
        line = "echo wrong-shell"
    "#,
    );

    env.run(&Cmd::Apply {
        pull_config: false,
        yes: true,
        dry_run: false,
        allow_dirty: true,
    })
    .expect("apply should succeed");

    let zshrc = std::fs::read_to_string(env.resolve_path(srpath!("home/bob/.zshrc")))
        .expect("zshrc should exist");
    assert!(
        !zshrc.contains("echo wrong-shell"),
        "pkg gated by when=\"bash\" must not contribute on the wrong shell, got:\n{zshrc}"
    );
}

#[test]
fn apply_filters_pkg_by_when_os() {
    // A pkg that targets the other OS must be suppressed: its env_init action
    // must not reach .zshenv.
    let other_os = if cfg!(target_os = "macos") {
        "linux"
    } else {
        "macos"
    };
    let env = test_env::TestEnv::load();
    env.init_config(&format!(
        r#"
        [shell]
        type = "zsh"
        [shell.environment]
        [shell.alias]

        [pkg.alien]
        enable = "on"
        when = "{other_os}"
        [pkg.alien.install_hint.brew]
        packages = []
        [pkg.alien.install_hint.dnf]
        packages = []
        [pkg.alien.install_hint.apt]
        packages = []
        [pkg.alien.install_hint.pacman]
        packages = []
        [pkg.alien.install_hint.cargo]
        packages = []
        [[pkg.alien.shell.env_init.zsh]]
        type = "line"
        line = "echo wrong-os"
    "#
    ));

    env.run(&Cmd::Apply {
        pull_config: false,
        yes: true,
        dry_run: false,
        allow_dirty: true,
    })
    .expect("apply should succeed");

    let zshenv = std::fs::read_to_string(env.resolve_path(srpath!("home/bob/.zshenv")))
        .expect("zshenv should exist");
    assert!(
        !zshenv.contains("echo wrong-os"),
        "pkg gated by when=\"<other-os>\" must not contribute on the wrong OS, got:\n{zshenv}"
    );
}

#[test]
fn apply_updates_generated_file_when_disk_content_differs() {
    use zenops::output::AppliedAction;

    // The Modified branch of `apply_changes`: an existing on-disk file
    // already lives at the managed path with stale content. With `yes=true`
    // every diff hunk gets approved and the file is rewritten to match the
    // generated body.
    let env = test_env::TestEnv::load();
    env.init_config(
        r#"
        [shell]
        type = "bash"
        [shell.environment]
        [shell.alias]
    "#,
    );
    let stale = "# stale content from a previous apply\nexport STALE=1\n";
    env.write_file(srpath!("home/bob/.zenops_bash_profile"), stale);

    let out = env
        .run(&Cmd::Apply {
            pull_config: false,
            yes: true,
            dry_run: false,
            allow_dirty: true,
        })
        .expect("apply must succeed");

    // Exactly one UpdatedFile event for the bash profile.
    let updates: Vec<_> = out
        .entries
        .iter()
        .filter_map(|e| match e {
            Entry::AppliedAction(AppliedAction::UpdatedFile(p)) => Some(p),
            _ => None,
        })
        .collect();
    assert_eq!(
        updates.len(),
        1,
        "expected exactly one UpdatedFile event, got: {:?}",
        out.entries,
    );
    assert_eq!(
        updates[0].path,
        ConfigFilePath::in_home(srpath!(".zenops_bash_profile")),
    );

    // Disk no longer contains the stale marker — content was actually rewritten.
    let disk = std::fs::read_to_string(env.resolve_path(srpath!("home/bob/.zenops_bash_profile")))
        .unwrap();
    assert!(
        !disk.contains("STALE"),
        "expected stale content to be replaced, got:\n{disk}"
    );
}

#[test]
fn apply_dry_run_does_not_rewrite_modified_files() {
    use zenops::output::AppliedAction;

    // `dry_run=true` routes through DryRunPrompter, which rejects every
    // hunk. The "all hunks rejected → continue" branch in apply_changes
    // means no UpdatedFile event is emitted and the disk file stays
    // untouched.
    let env = test_env::TestEnv::load();
    env.init_config(
        r#"
        [shell]
        type = "bash"
        [shell.environment]
        [shell.alias]
    "#,
    );
    let stale = "# stale content from a previous apply\nexport STALE=1\n";
    env.write_file(srpath!("home/bob/.zenops_bash_profile"), stale);

    let out = env
        .run(&Cmd::Apply {
            pull_config: false,
            yes: false,
            dry_run: true,
            allow_dirty: true,
        })
        .expect("dry-run apply must succeed");

    let any_update = out
        .entries
        .iter()
        .any(|e| matches!(e, Entry::AppliedAction(AppliedAction::UpdatedFile(_))));
    assert!(
        !any_update,
        "dry-run apply must not emit UpdatedFile, got: {:?}",
        out.entries,
    );

    // Disk content unchanged.
    let disk = std::fs::read_to_string(env.resolve_path(srpath!("home/bob/.zenops_bash_profile")))
        .unwrap();
    assert_eq!(disk, stale, "dry-run must leave the file untouched");
}

#[test]
fn apply_dry_run_skips_create_file() {
    // Fresh apply with no pre-existing shell config. dry_run=true makes
    // every `confirm` return false, so the CreateFile branch must hit its
    // `continue` arm: no UpdatedFile / CreatedFile and the file stays off
    // disk.
    use zenops::output::AppliedAction;

    let env = test_env::TestEnv::load();
    env.init_config(
        r#"
        [shell]
        type = "bash"
        [shell.environment]
        [shell.alias]
    "#,
    );

    let out = env
        .run(&Cmd::Apply {
            pull_config: false,
            yes: false,
            dry_run: true,
            allow_dirty: true,
        })
        .expect("dry-run apply must succeed");

    let any_create = out.entries.iter().any(|e| {
        matches!(
            e,
            Entry::AppliedAction(AppliedAction::CreatedFile(_))
                | Entry::AppliedAction(AppliedAction::UpdatedFile(_))
        )
    });
    assert!(
        !any_create,
        "dry-run apply must not emit CreatedFile/UpdatedFile, got: {:?}",
        out.entries,
    );

    let target = env.resolve_path(srpath!("home/bob/.zenops_bash_profile"));
    assert!(
        target.symlink_metadata().is_err(),
        "dry-run must not create {target:?}"
    );
}

#[test]
fn entry_status_propagates_unreadable_generated_file() {
    // A managed shell config wants to land at ~/.zenops_bash_profile, but a
    // directory occupies that path. read_to_string fails with IsADirectory;
    // expect Error::FailedToReadConfig rather than a `not yet implemented`
    // panic.
    let env = test_env::TestEnv::load();
    env.init_config(
        r#"
        [shell]
        type = "bash"
        [shell.environment]
        [shell.alias]
    "#,
    );

    env.create_dir(srpath!("home/bob/.zenops_bash_profile"));

    let result = env.run(&Cmd::Status {
        diff: false,
        all: false,
    });

    match result {
        Err(Error::ConfigFiles(ConfigFilesError::FailedToReadConfig(p, e))) => {
            assert_eq!(
                p.path,
                ConfigFilePath::in_home(srpath!(".zenops_bash_profile"))
            );
            // IsADirectory landed in stable rust 1.83+. Older targets surface
            // the same condition as Other; accept both.
            assert!(
                matches!(
                    e.kind(),
                    std::io::ErrorKind::IsADirectory | std::io::ErrorKind::Other,
                ),
                "unexpected I/O error kind: {:?}",
                e.kind(),
            );
        }
        other => panic!("expected FailedToReadConfig, got {other:?}"),
    }
}

#[test]
fn apply_journey_import_edit_reconcile_apply() {
    // End-to-end believable workflow: import a populated config, edit a
    // file through its symlink, reconcile-add a new file, reconcile-delete
    // an old one, then apply. Each phase has its own assertions so a
    // regression in any single step trips this test loudly.
    let env = test_env::TestEnv::load();
    env.init_config(
        r#"
[shell]
type = "bash"
[shell.environment]
[shell.alias]
"#,
    );

    // -- Phase A: fresh import of three files. ------------------------
    env.write_file(
        srpath!("home/bob/.config/helix/config.toml"),
        b"theme = 'dark'\n",
    );
    env.write_file(
        srpath!("home/bob/.config/helix/themes/dark.toml"),
        b"name = 'dark'\n",
    );
    env.write_file(srpath!("home/bob/.config/helix/init.lua"), b"-- editor\n");

    let import = Cmd::Import {
        path: env.resolve_path(srpath!("home/bob/.config/helix")),
        pkg: None,
        source: None,
        brew: vec!["helix".into()],
        no_install_hint: false,
        yes: true,
        dry_run: false,
    };
    env.run(&import).expect("phase A: import should succeed");

    let cfg_path = env.resolve_path(srpath!("home/bob/.config/zenops/config.toml"));
    let parse_helix_symlinks = || -> Vec<String> {
        let text = std::fs::read_to_string(&cfg_path).unwrap();
        let cfg: toml::Value = toml::from_str(&text).unwrap();
        let mut s: Vec<String> = cfg["pkg"]["helix"]["configs"][0]["symlinks"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap().to_string())
            .collect();
        s.sort();
        s
    };
    assert_eq!(
        parse_helix_symlinks(),
        vec![
            "config.toml".to_string(),
            "init.lua".to_string(),
            "themes/dark.toml".to_string(),
        ],
    );
    for rel in ["config.toml", "init.lua", "themes/dark.toml"] {
        let home_rel: zenops_safe_relative_path::SafeRelativePathBuf =
            format!("home/bob/.config/helix/{rel}").parse().unwrap();
        let repo_rel: zenops_safe_relative_path::SafeRelativePathBuf =
            format!("home/bob/.config/zenops/configs/helix/{rel}")
                .parse()
                .unwrap();
        assert!(
            std::fs::symlink_metadata(env.resolve_path(&home_rel))
                .unwrap()
                .file_type()
                .is_symlink(),
            "{rel} should be a symlink after import",
        );
        assert!(
            env.resolve_path(&repo_rel).exists(),
            "{rel} repo copy should exist after import",
        );
    }

    // -- Phase B: edit config.toml through its symlink. ---------------
    let helix_cfg_home = env.resolve_path(srpath!("home/bob/.config/helix/config.toml"));
    let helix_cfg_repo =
        env.resolve_path(srpath!("home/bob/.config/zenops/configs/helix/config.toml"));
    std::fs::write(&helix_cfg_home, b"theme = 'dracula'\n").unwrap();
    assert_eq!(
        std::fs::read(&helix_cfg_home).unwrap(),
        b"theme = 'dracula'\n"
    );
    assert_eq!(
        std::fs::read(&helix_cfg_repo).unwrap(),
        b"theme = 'dracula'\n"
    );
    assert!(
        std::fs::symlink_metadata(&helix_cfg_home)
            .unwrap()
            .file_type()
            .is_symlink(),
        "phase B: write through must not break the symlink",
    );

    // -- Phase C: drop a new file, reconcile. -------------------------
    env.write_file(
        srpath!("home/bob/.config/helix/themes/light.toml"),
        b"name = 'light'\n",
    );
    let reconcile = Cmd::Import {
        path: env.resolve_path(srpath!("home/bob/.config/helix")),
        pkg: None,
        source: None,
        brew: Vec::new(),
        no_install_hint: false,
        yes: true,
        dry_run: false,
    };
    env.run(&reconcile)
        .expect("phase C: reconcile should succeed");
    assert_eq!(
        parse_helix_symlinks(),
        vec![
            "config.toml".to_string(),
            "init.lua".to_string(),
            "themes/dark.toml".to_string(),
            "themes/light.toml".to_string(),
        ],
    );
    let new_link = env.resolve_path(srpath!("home/bob/.config/helix/themes/light.toml"));
    let new_repo = env.resolve_path(srpath!(
        "home/bob/.config/zenops/configs/helix/themes/light.toml"
    ));
    assert!(
        std::fs::symlink_metadata(&new_link)
            .unwrap()
            .file_type()
            .is_symlink(),
    );
    assert_eq!(std::fs::read_link(&new_link).unwrap(), new_repo);

    // -- Phase D: delete dark.toml, reconcile again. ------------------
    env.delete_file(srpath!("home/bob/.config/helix/themes/dark.toml"));
    env.delete_file(srpath!(
        "home/bob/.config/zenops/configs/helix/themes/dark.toml"
    ));
    env.run(&reconcile)
        .expect("phase D: reconcile should succeed");
    assert_eq!(
        parse_helix_symlinks(),
        vec![
            "config.toml".to_string(),
            "init.lua".to_string(),
            "themes/light.toml".to_string(),
        ],
    );
    assert!(
        !env.resolve_path(srpath!(
            "home/bob/.config/zenops/configs/helix/themes/dark.toml"
        ))
        .exists(),
    );
    // themes/ still exists because light.toml lives there.
    assert!(
        env.resolve_path(srpath!("home/bob/.config/zenops/configs/helix/themes"))
            .is_dir(),
    );

    // -- Phase E: apply on a dirty (uncommitted-import-changes) repo. -
    env.run(&Cmd::Apply {
        pull_config: false,
        yes: true,
        dry_run: false,
        allow_dirty: true,
    })
    .expect("phase E: apply should succeed");

    // The 3 surviving symlinks still resolve and the edited bytes survive
    // through apply.
    for rel in ["config.toml", "init.lua", "themes/light.toml"] {
        let home_rel: zenops_safe_relative_path::SafeRelativePathBuf =
            format!("home/bob/.config/helix/{rel}").parse().unwrap();
        let repo_rel: zenops_safe_relative_path::SafeRelativePathBuf =
            format!("home/bob/.config/zenops/configs/helix/{rel}")
                .parse()
                .unwrap();
        let home_path = env.resolve_path(&home_rel);
        let repo_path = env.resolve_path(&repo_rel);
        assert!(
            std::fs::symlink_metadata(&home_path)
                .unwrap()
                .file_type()
                .is_symlink(),
            "{rel} should still be a symlink after apply",
        );
        assert_eq!(std::fs::read_link(&home_path).unwrap(), repo_path);
    }
    assert_eq!(
        std::fs::read(&helix_cfg_home).unwrap(),
        b"theme = 'dracula'\n",
        "phase B's edit must still be on disk after apply",
    );
}