dodot-lib 5.10.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
//! `up` command — deploy packs (create symlinks, run provisioning).
//!
//! Uses a two-phase execution model:
//! 1. **Collect** intents from all packs (no mutations).
//! 2. **Detect** cross-pack conflicts across all collected intents.
//! 3. **Execute** only if no conflicts are found.
//!
//! This prevents partial deployments where one pack silently overwrites
//! another pack's symlinks.
//!
//! Between 2 and 3, and only on a real run, `up` asks each package
//! manager it is about to spawn whether it is new enough to run what
//! the user wrote (`provisioners::fitness`). That question costs a
//! subprocess, which is why it lives here and not in planning: this
//! file is the only place in dodot that asks it.
//!
//! ## Output rendering
//!
//! For non-dry-run executions, `up` renders by calling `status::status()`
//! on the affected packs after execution and overlaying any operation
//! errors. This guarantees that the per-file labels you see after `up`
//! match exactly what you'd see if you ran `status` immediately
//! afterward — there's a single rendering path, not two.
//!
//! Dry-run keeps the per-intent rendering since there's no
//! post-execution state to verify.
//!
//! Both renderings additionally place a row for every file
//! `--no-provision` dropped during planning. Those files produce no
//! intent and no operation, so nothing else in either path would
//! mention them — the user's own choice would read as an empty pack.
//!
//! ## Failures
//!
//! A failed operation is contained to the file it happened to: the
//! rest of the pack still executes, and the failure flips that file's
//! row to `error` with the failure text as its note. `up` reports
//! whether the run left any failure behind in
//! [`PackStatusResult::failed`], which the CLI turns into the process
//! exit code — the signal a bootstrap script or an image build reads.

use std::collections::{HashMap, HashSet};

use tracing::{debug, info};

use crate::commands::{
    handler_description, handler_symbol, status, status_style, DisplayConflict, DisplayFile,
    DisplayNote, DisplayPack, PackStatusResult,
};
use crate::conflicts;
use crate::handlers;
use crate::operations::HandlerIntent;
use crate::packs::orchestration::{self, ExecutionContext, PackResult};
use crate::packs::Pack;
use crate::probe;
use crate::shell;
use crate::Result;

/// Run the `up` command: deploy packs and regenerate shell init.
///
/// Collects all intents across all packs first, checks for cross-pack
/// conflicts, then executes. If conflicts are found, **no** pack is
/// deployed and a `CrossPackConflict` error is returned — even if
/// `--force` is set, because cross-pack conflicts are a configuration
/// problem, not a deployment problem.
///
/// Operation failures do not abort the run: they are collected into
/// the returned result, whose [`PackStatusResult::failed`] flag says
/// whether anything failed. Only a dry run leaves that flag false
/// regardless of what it reports.
pub fn up(pack_filter: Option<&[String]>, ctx: &ExecutionContext) -> Result<PackStatusResult> {
    info!(
        dry_run = ctx.dry_run,
        force = ctx.force,
        no_provision = ctx.no_provision,
        "starting up command"
    );

    // Validate names up front so an explicitly-requested ignored pack
    // surfaces the same "pack '…' is ignored, skipping" warning that
    // `status`/`down` emit — prepare_packs discards these. (issue #222)
    let mut warnings: Vec<String> = match pack_filter {
        Some(names) => orchestration::validate_pack_names(names, ctx)?,
        None => Vec::new(),
    };

    // Discover `.dodotignore`-marked packs so we can both report them in
    // the same ignored rows `status` shows and sweep any
    // stale datastore state they left behind. Without the sweep, a pack
    // deployed before it was ignored keeps getting sourced from the
    // regenerated init script. (issue #222)
    let ignored = orchestration::scan_ignored(pack_filter, ctx)?;

    // Surface orphaned state — datastore subtrees for packs deleted
    // from the dotfiles root since they were deployed. `up` only warns:
    // the init script regenerated below still carries the orphans (it
    // is driven off the whole datastore), and sweeping here would let a
    // misresolved dotfiles root silently wipe legitimate state on
    // deploy. `dodot down` is the removal path. (issue #255)
    let orphaned = orchestration::scan_orphaned(ctx)?;
    if !orphaned.is_empty() {
        warnings.push(orchestration::orphan_warning(&orphaned, ctx));
    }

    // Phase 1: Discover packs and collect intents
    let packs = orchestration::prepare_packs(pack_filter, ctx)?;

    // Preflight secret providers once per active run. Skipped on
    // `--dry-run` because the Passive envelope (`secrets.lex` §7.4) is
    // exactly the contract that the secrets layer is not touched at all.
    // We also skip when no provider is enabled (`build_secret_registry`
    // returns `None`) — there's nothing to probe and templates that
    // reference `secret(...)` will fail loudly at render time with a
    // separate, more specific error.
    if !ctx.dry_run {
        let root_config = ctx.config_manager.root_config()?;
        if root_config.secret.enabled {
            if let Some(registry) = crate::preprocessing::build_secret_registry(
                &root_config.secret,
                ctx.command_runner.clone(),
                ctx.paths.dotfiles_root(),
            ) {
                crate::secret::preflight(&registry)?;
            }
        }
    }

    let mut pack_intents: Vec<(String, Vec<HandlerIntent>)> = Vec::with_capacity(packs.len());
    let mut intent_errors: Vec<PackResult> = Vec::new();
    // Per-pack record of what `--no-provision` dropped. Only the
    // dry-run renderer reads it: a real run renders through
    // `status::status()`, which reads the same list off its own
    // planning pass. Empty on every run without `--no-provision`.
    let mut pack_skips: Vec<(String, Vec<orchestration::ProvisionSkip>)> = Vec::new();
    // Per-pack record of what an absent (or unprobeable) manager
    // dropped. The dry-run renderer places its rows — a real run
    // renders through `status::status()`, which asks the same probe on
    // its own planning pass — and both runs read it below for the one
    // outcome that is a failure rather than a skip: a probe that could
    // not answer at all.
    let mut pack_unavailable: Vec<(String, Vec<orchestration::ProvisionUnavailable>)> = Vec::new();

    for pack in &packs {
        // Active when actually deploying; Passive on `--dry-run`. The
        // Passive envelope skips template evaluation (no provider
        // calls, no auth prompts) and skips datastore + baseline
        // writes. See `secrets.lex` §7.4 / issue #121.
        let mode = if ctx.dry_run {
            crate::preprocessing::PreprocessMode::Passive
        } else {
            crate::preprocessing::PreprocessMode::Active
        };
        match orchestration::plan_pack(pack, ctx, mode) {
            Ok(plan) => {
                warnings.extend(plan.warnings);
                if !plan.provision_skipped.is_empty() {
                    pack_skips.push((pack.display_name.clone(), plan.provision_skipped));
                }
                if !plan.provision_unavailable.is_empty() {
                    pack_unavailable.push((pack.display_name.clone(), plan.provision_unavailable));
                }
                pack_intents.push((pack.display_name.clone(), plan.intents));
            }
            Err(e) => {
                info!(pack = %pack.display_name, error = %e, "intent collection failed");
                intent_errors.push(PackResult {
                    pack_name: pack.display_name.clone(),
                    success: false,
                    operations: Vec::new(),
                    error: Some(format!("intent collection error: {e}")),
                });
            }
        }
    }

    // Phase 2: Detect cross-pack conflicts
    info!("checking for cross-pack conflicts");
    let conflicts = conflicts::detect_cross_pack_conflicts(&pack_intents, ctx.fs.as_ref());
    if !conflicts.is_empty() {
        info!(count = conflicts.len(), "cross-pack conflicts detected");
        return Err(crate::DodotError::CrossPackConflict { conflicts });
    }
    debug!("no cross-pack conflicts");

    // Phase 2.5: is each manager the run is about to spawn *well
    // enough* to use?
    //
    // `!ctx.dry_run` is the whole up-only contract, stated once: the
    // fitness probe spawns the manager to ask, and a dry run that
    // spawned the user's package manager would no longer be
    // reporting what it *would* do. `status` never reaches this file
    // at all. See `provisioners::fitness`.
    if !ctx.dry_run {
        warnings.extend(provisioner_fitness_warnings(&pack_intents, ctx));
    }

    // Phase 3: Reconcile non-provisioning state, then execute intents.
    //
    // For configuration handlers (path, shell, symlink), every `up` is
    // equivalent to "down (those handlers) + up": we wipe the stored
    // state for each pack before re-applying current source. That way
    // a file deleted from the pack stops appearing in the regenerated
    // init script and the deployed user-side links — instead of
    // lingering as a stale entry that points at a now-missing source.
    //
    // Provisioning handlers (install, homebrew, nix) are deliberately
    // left alone. Their sentinels record "did this run with this
    // content?" independently of whether the source still exists right
    // now; wiping them would force install scripts, `brew bundle`, and
    // `nix profile install` to re-execute on every up, defeating the
    // sentinel mechanism.
    let mut pack_results: Vec<PackResult> = intent_errors;
    let config_handlers = if ctx.dry_run {
        Vec::new()
    } else {
        handlers::configuration_handler_names(ctx.fs.as_ref())
    };
    // pack_intents was built from `packs`, so every display_name maps
    // to exactly one Pack. Keying by &str avoids cloning and makes the
    // missing-pack case a bug rather than silent skip.
    let pack_by_display: HashMap<&str, &Pack> =
        packs.iter().map(|p| (p.display_name.as_str(), p)).collect();

    for (pack_name, intents) in pack_intents {
        info!(pack = %pack_name, intents = intents.len(), "executing pack");

        if !ctx.dry_run {
            let pack = pack_by_display
                .get(pack_name.as_str())
                .copied()
                .expect("pack_intents was built from packs; lookup must succeed");
            if let Err(e) = wipe_configuration_state(pack, &config_handlers, ctx) {
                info!(pack = %pack_name, error = %e, "reconcile failed");
                pack_results.push(PackResult {
                    pack_name,
                    success: false,
                    operations: Vec::new(),
                    error: Some(format!("reconcile error: {e}")),
                });
                continue;
            }
        }

        match orchestration::execute_intents(intents, ctx) {
            Ok(operations) => {
                let success = operations.iter().all(|r| r.success);
                let succeeded = operations.iter().filter(|o| o.success).count();
                let failed = operations.iter().filter(|o| !o.success).count();
                debug!(pack = %pack_name, succeeded, failed, "pack execution complete");
                pack_results.push(PackResult {
                    pack_name,
                    success,
                    operations,
                    error: None,
                });
            }
            Err(e) => {
                info!(pack = %pack_name, error = %e, "pack execution failed");
                pack_results.push(PackResult {
                    pack_name,
                    success: false,
                    operations: Vec::new(),
                    error: Some(format!("execution error: {e}")),
                });
            }
        }
    }

    // The generation the user's shells were hooked up to *before* this
    // run regenerates the init script. Captured here because it is the
    // only fair yardstick for the activation verdict below: comparing
    // the invoking shell's stamp against the generation we are about to
    // write would mark every single `up` as running from a stale shell.
    let pre_up_generation =
        shell::activation::read_script_generation(ctx.fs.as_ref(), ctx.paths.as_ref());

    if !ctx.dry_run {
        // Tear down any stale state for packs that are now ignored, so
        // the regenerated (global) init script below stops sourcing
        // them — unfiltered, since the init script covers every pack
        // regardless of this run's filter. (#222)
        orchestration::sweep_pack_state(&ignored.sweep_dir_names, ctx)?;
        info!("regenerating shell init script");
        let root_config = ctx.config_manager.root_config()?;
        // Ask brew for its bootstrap now and persist it to the
        // datastore cache, so no generation path ever has to —
        // including `dodot init-sh`, which emits from this cache on
        // every shell start (shell-hookup-ergonomics.lex §4). Two
        // `brew` spawns per `up`, one per shell dialect; the capture
        // belongs to `up`, not to every generation. A host without
        // brew captures nothing (clearing any stale cache) and this
        // `up` heals it. A *detected* brew that fails to answer is a
        // different event: the previous capture is kept and a warning
        // lands in this run's output (#301).
        let brew = shell::homebrew::capture_and_persist(
            ctx.fs.as_ref(),
            ctx.command_runner.as_ref(),
            &root_config,
            ctx.paths.as_ref(),
        )?;
        if let Some(warning) = brew.warning {
            warnings.push(warning);
        }
        shell::write_init_script(
            ctx.fs.as_ref(),
            ctx.paths.as_ref(),
            root_config.profiling.enabled,
            brew.blocks.as_ref(),
        )?;
        info!("writing deployment map");
        probe::write_deployment_map(ctx.fs.as_ref(), ctx.paths.as_ref())?;
        // cfprefsd cache-invalidation hint (macOS): if any plist file
        // in any active pack has drifted since the previous successful
        // `up`, drop a marker so the CLI's post-`up` prompt can offer
        // `killall cfprefsd`. The previous-up timestamp must be
        // captured BEFORE the new last-up marker is written below;
        // afterwards every plist's mtime would be older than the new
        // marker and the detector would always report "no drift".
        // No-op on non-macOS hosts (cfprefsd doesn't exist there).
        if cfg!(target_os = "macos") {
            let prev_last_up = probe::read_last_up_marker(ctx.fs.as_ref(), ctx.paths.as_ref());
            if let Err(e) = maybe_record_cfprefsd_drift(ctx, &packs, prev_last_up) {
                debug!(error = %e, "cfprefsd drift check skipped");
            }
        }
        // Record the unix timestamp of this up so `dodot probe shell-init`
        // can flag profiles captured before it as stale. Best effort —
        // a clock skip would only affect the staleness banner, never the
        // deployment itself, so we don't fail the run on a write error.
        if let Err(e) = probe::write_last_up_marker(ctx.fs.as_ref(), ctx.paths.as_ref()) {
            debug!(error = %e, "failed to write last-up marker");
        }
        // Prune old shell-init profile reports. Cheap (one read_dir +
        // a few unlinks at most) and runs in dodot's process, not the
        // user's shell.
        let removed = probe::rotate_profiles(
            ctx.fs.as_ref(),
            ctx.paths.as_ref(),
            root_config.profiling.keep_last_runs,
        )?;
        if removed > 0 {
            debug!(removed, "pruned old shell-init profiles");
        }

        // Pre-flight syntax check: parse-only run of bash/zsh against
        // each deployed shell source so a typo in `aliases.sh` shows up
        // here instead of silently breaking next shell startup. The
        // sidecar files this writes are read back by `dodot status`.
        // The checker is injected via context so tests can stub it out.
        let report = shell::validate_shell_sources(
            ctx.fs.as_ref(),
            ctx.paths.as_ref(),
            ctx.syntax_checker.as_ref(),
        )?;
        if !report.failures.is_empty() {
            info!(
                count = report.failures.len(),
                "shell syntax check found failures"
            );
            eprintln!(
                "dodot: {} shell file{} failed pre-flight syntax check (see `dodot status`)",
                report.failures.len(),
                if report.failures.len() == 1 { "" } else { "s" }
            );
        }
        for interp in &report.missing_interpreters {
            // One-line skip notice per missing interpreter, not per
            // file. Doesn't fail the run — the file is still deployed.
            eprintln!(
                "dodot: `{interp}` not on PATH, skipped syntax check for matching shell files"
            );
        }
    }

    // A manager dodot could not *look for* is a failure, and the only
    // one that never reaches `pack_results`: a probe failure produces
    // no intent, so it produces no operation to carry a verdict.
    //
    // Absence is not counted here. The two outcomes are separated
    // precisely because they differ: a missing brew is an ordinary
    // machine state with a remedy the user can act on, while a
    // `/opt/homebrew` dodot cannot stat means the question went
    // unanswered — the run's report about that file is not to be
    // trusted, and `up` says so with its exit code. The rest of the
    // pack still deploys either way (ADR-0008).
    let unprobeable = pack_unavailable
        .iter()
        .flat_map(|(_, files)| files)
        .any(|f| {
            matches!(
                f.availability,
                crate::provisioners::availability::Availability::ProbeFailed { .. }
            )
        });
    let has_failures = unprobeable
        || pack_results
            .iter()
            .any(|pr| !pr.success || pr.operations.iter().any(|op| !op.success));

    // Build display packs.
    //
    // For real executions, render through status::status() so the user sees
    // the same labels they'd see by running `dodot status` immediately
    // afterward. Operation failures flip their matching row's status to
    // "error" and attach a command-wide note; pack-level errors synthesize
    // an error row at the end of the pack.
    //
    // For dry-run, render the simulated operations directly — there's no
    // post-execution state to verify, and the user wants to see the planned
    // changes, not the unchanged current state.
    let (display_packs, notes) = if ctx.dry_run {
        render_intents(
            &pack_results,
            &pack_skips,
            &pack_unavailable,
            ctx.paths.home_dir(),
        )
    } else {
        let pack_names: Vec<String> = packs.iter().map(|p| p.display_name.clone()).collect();
        let status_result = status::status(Some(&pack_names), ctx)?;
        // status::status() may have populated notes (PendingConflict etc.);
        // preserve them and continue numbering from there.
        let mut notes = status_result.notes;
        let display_packs = overlay_errors(
            status_result.packs,
            &pack_results,
            ctx.paths.home_dir(),
            &mut notes,
        );
        (display_packs, notes)
    };

    let message = if has_failures {
        "Packs deployed with errors.".into()
    } else {
        "Packs deployed.".into()
    };

    Ok(PackStatusResult {
        message: Some(message),
        dry_run: ctx.dry_run,
        packs: display_packs,
        warnings,
        notes,
        conflicts: Vec::new(),
        ignored_packs: ignored.display_packs,
        inactive_packs: Vec::new(),
        view_mode: ctx.view_mode.as_str().into(),
        group_mode: ctx.group_mode.as_str().into(),
        diffs: Vec::new(),
        shell_hookup: activation_notice(ctx, pre_up_generation),
        // A dry run attempted nothing, so it reports failures without
        // being one — `dodot up --dry-run` in a script stays exit 0.
        failed: has_failures && !ctx.dry_run,
    })
}

/// Ask each manager this run is about to spawn whether it is well
/// enough to use, print what to tell the user about the ones that are
/// not, and return the same text for the run's warning list.
///
/// Asked here rather than during planning because planning is shared
/// with `--dry-run`, and asked before Phase 3 rather than inside the
/// executor because the answer has to be on screen before the
/// manager's own parse error is.
///
/// That last part is why the warning is *printed here* rather than
/// only returned. `PackStatusResult::warnings` is printed by the CLI
/// after `up` has returned, and a failing `brew bundle` writes its
/// stderr straight to the user's terminal while it runs — so a
/// warning that was only collected would arrive after the parse error
/// it exists to explain, which is the wrong way round. It is still
/// collected as well: the end-of-run warning list is what `--output
/// json` serializes and what an API caller reads, and repeating one
/// line in the run's summary costs less than dropping it from the
/// machine-readable output.
///
/// One spawn per (manager, executable) pair per run, however many
/// packs declare a file for it — three packs with a `Brewfile` ask
/// brew its version once. The cache is here, and not in
/// `provisioners::availability`, for the reason ADR-0008 gives:
/// caching a couple of `stat` calls buys nothing, and caching a
/// subprocess buys the whole difference.
///
/// A file whose receipt is already current is not asked about at all
/// — see [`will_spawn`](crate::execution::run::will_spawn).
fn provisioner_fitness_warnings(
    pack_intents: &[(String, Vec<HandlerIntent>)],
    ctx: &ExecutionContext,
) -> Vec<String> {
    use std::io::Write;

    let mut asked: HashSet<(&str, &str)> = HashSet::new();
    let mut warnings = Vec::new();
    for (_, intents) in pack_intents {
        for intent in intents {
            let HandlerIntent::Run {
                handler,
                executable,
                environment,
                ..
            } = intent
            else {
                continue;
            };
            if crate::provisioners::fitness::floor_for(handler).is_none() {
                continue;
            }
            // Order matters: a manager is marked asked only once
            // something has actually asked it. Marking on sight would
            // let a pack whose receipt is current swallow the
            // question on behalf of a pack whose `Brewfile` is about
            // to run against the same brew.
            if !crate::execution::run::will_spawn(
                ctx.datastore.as_ref(),
                ctx.provision_rerun,
                intent,
            ) {
                continue;
            }
            if !asked.insert((handler.as_str(), executable.as_str())) {
                continue;
            }
            let fitness = crate::provisioners::fitness::probe(
                ctx.command_runner.as_ref(),
                handler,
                executable,
                environment,
            );
            if let Some(warning) = fitness.warning(handler, executable) {
                tracing::warn!(handler = %handler, "{warning}");
                // Now, on the user's stderr, and not only in the
                // returned list: Phase 3 is about to spawn this
                // manager, and its output goes to the same terminal.
                // Tracing is not a substitute — in the default quiet
                // mode it reaches the log file and nothing else.
                //
                // Written through `std::io::stderr()` rather than
                // `eprintln!` so it is the same handle
                // `ShellCommandRunner` forwards a failing command's
                // stderr through: one descriptor, two writers, and
                // the order on screen is the order things happened.
                let _ = writeln!(std::io::stderr(), "dodot: {warning}");
                warnings.push(warning);
            }
        }
    }
    warnings
}

/// The shell-hookup footer `up` reports.
///
/// The shared builder (`commands::shell_hookup_footer`) with `up`'s two
/// choices filled in:
///
/// - It judges against `pre_up_generation` — the generation the user's
///   shells could actually have loaded before this run rewrote the
///   script. Judging against the new one would tell every user to open
///   a new shell after every deploy.
/// - It is the one command where a *measurement* is worth its cost:
///   when the cheap signals come back inconclusive, `up` spawns the
///   user's shell and reports what actually happened (spec §3.1). A
///   green first `up` ends on a measured verdict, not a promise; a
///   healthy machine never spawns anything.
///
/// A fresh install has no heartbeat and no stamp, so this is where the
/// new-user failure story gets caught: at the end of a green first
/// `up`.
///
/// A `--dry-run` regenerated no script, so measuring the current one
/// would report on a world this run did not create — evidence only
/// there, which the footer omits entirely when nothing has ever been
/// deployed.
fn activation_notice(
    ctx: &ExecutionContext,
    pre_up_generation: Option<u64>,
) -> Option<crate::shell::ActivationNotice> {
    let policy = if ctx.dry_run {
        crate::shell::ProbePolicy::Never
    } else {
        ctx.shell_probe
    };
    crate::commands::shell_hookup_footer(ctx, pre_up_generation, &policy)
}

/// Run `up`, falling back to a status render when a cross-pack conflict
/// blocks deployment.
///
/// On a plain success, this returns `up()`'s result unchanged. On a
/// cross-pack conflict it re-runs the status scan and folds the
/// conflicts in, so the caller gets the full per-pack file listing plus
/// the conflicts section — the same view `dodot status` produces — with
/// a top-level message explaining that nothing was deployed. Other
/// errors propagate unchanged.
///
/// The CLI uses this so `dodot up` and `dodot status` look identical
/// when a cross-pack conflict is present, rather than stripping the
/// per-pack rows down to a bare conflict dump.
pub fn up_or_status_for_conflict(
    pack_filter: Option<&[String]>,
    ctx: &ExecutionContext,
) -> Result<PackStatusResult> {
    match up(pack_filter, ctx) {
        Ok(r) => Ok(r),
        Err(crate::DodotError::CrossPackConflict { conflicts: raw }) => {
            let home = ctx.paths.home_dir();
            let display_conflicts: Vec<DisplayConflict> = raw
                .iter()
                .map(|c| DisplayConflict::from_conflict(c, home))
                .collect();
            let mut base = status::status(pack_filter, ctx)?;
            base.message = Some("Cross-pack conflicts prevent deployment.".into());
            base.dry_run = ctx.dry_run;
            base.conflicts = display_conflicts;
            // Nothing deployed, so an active run is a failed one: a
            // script chaining off `dodot up` must not proceed against
            // a machine where every pack was blocked. A dry run is a
            // preview and stays exit 0.
            base.failed = !ctx.dry_run;
            Ok(base)
        }
        Err(e) => Err(e),
    }
}

/// macOS cfprefsd drift detection.
///
/// Walks the packs that this `up` actually targeted (so a
/// `dodot up <one-pack>` run never fires cfprefsd because of a plist
/// in some unrelated pack) for files whose suffix matches the
/// pack-resolved `[symlink] plist_extensions` list. If any plist's
/// mtime is newer than `prev_last_up_ts` (or the marker is missing —
/// first `up` on this machine), drop the cfprefsd-needs-invalidation
/// marker so the CLI's post-`up` prompt fires.
///
/// "Drift" here is intentionally loose: it captures both
/// deploy-time changes (a new plist landed) and between-`up` app
/// drift (the GUI app rewrote the plist between yesterday's `up` and
/// today's). cfprefsd's cache may be stale either way; the prompt is
/// what gives the user a single chance to clear it.
fn maybe_record_cfprefsd_drift(
    ctx: &ExecutionContext,
    packs: &[Pack],
    prev_last_up_ts: Option<u64>,
) -> Result<()> {
    use std::time::UNIX_EPOCH;

    let plist_files = crate::commands::git_filters::detect_plist_files_in(ctx, packs)?;
    if plist_files.is_empty() {
        return Ok(());
    }
    let drifted = plist_files.iter().any(|p| {
        let mtime_secs = ctx
            .fs
            .modified(p)
            .ok()
            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
            .map(|d| d.as_secs());
        match (mtime_secs, prev_last_up_ts) {
            // No previous up marker (first run on this machine):
            // every plist counts as fresh.
            (Some(_), None) => true,
            // Strict newer-than: equal timestamps (same-second `up`
            // run) don't fire the prompt — the file was just written
            // by us, no app-side drift to invalidate.
            (Some(m), Some(prev)) => m > prev,
            (None, _) => false,
        }
    });
    if drifted {
        probe::write_cfprefsd_marker(ctx.fs.as_ref(), ctx.paths.as_ref())?;
    }
    Ok(())
}

/// Remove datastore state for a pack across the given configuration
/// handlers. Datastore is keyed by on-disk directory name (e.g.
/// `010-nvim`), not the display name (`nvim`).
fn wipe_configuration_state(
    pack: &Pack,
    config_handlers: &[String],
    ctx: &ExecutionContext,
) -> Result<()> {
    for handler in config_handlers {
        ctx.datastore.remove_state(&pack.name, handler)?;
    }
    Ok(())
}

/// Render operations directly from pack_results — used for dry-run, where
/// there's no executed state to verify and the user wants to see the
/// planned changes rather than the unchanged status quo.
///
/// `pack_skips` carries the files `--no-provision` dropped during
/// planning, keyed by pack display name. They produced no intent and
/// so no operation; without them the preview would simply omit the
/// files the user asked to skip, which reads as "dodot found nothing
/// here" rather than "you told me not to".
///
/// `pack_unavailable` carries the files whose manager is not on this
/// machine, for the same reason and with a different story: not "you
/// told me not to" but "brew is not here, and here is where I
/// looked". Its rows are worded by the availability module, so a
/// preview and the `status` row for the same machine match.
///
/// Returns (packs, notes). Failed operations keep their row but receive a
/// `note_ref` into the command-wide notes list, keeping the column layout
/// intact.
fn render_intents(
    pack_results: &[PackResult],
    pack_skips: &[(String, Vec<orchestration::ProvisionSkip>)],
    pack_unavailable: &[(String, Vec<orchestration::ProvisionUnavailable>)],
    home: &std::path::Path,
) -> (Vec<DisplayPack>, Vec<DisplayNote>) {
    let mut notes: Vec<DisplayNote> = Vec::new();
    let packs = pack_results
        .iter()
        .map(|pr| {
            let mut files: Vec<DisplayFile> = pr
                .operations
                .iter()
                .map(|op| {
                    let (handler, name, user_target) = extract_op_info(&op.operation, home);
                    let (status, status_label, note_ref) = if op.success {
                        (status_style(true).to_string(), op.message.clone(), None)
                    } else {
                        notes.push(DisplayNote::error(op.message.clone()));
                        (
                            "error".to_string(),
                            "error".to_string(),
                            Some(notes.len() as u32),
                        )
                    };
                    DisplayFile {
                        name: name.clone(),
                        symbol: handler_symbol(&handler).into(),
                        description: handler_description(&handler, &name, user_target.as_deref()),
                        status,
                        status_label,
                        handler,
                        note_ref,
                    }
                })
                .collect();

            if let Some((_, skips)) = pack_skips.iter().find(|(name, _)| name == &pr.pack_name) {
                files.extend(skips.iter().map(|skip| DisplayFile {
                    name: skip.relative_path.clone(),
                    symbol: handler_symbol(&skip.handler).into(),
                    description: handler_description(&skip.handler, &skip.relative_path, None),
                    status: "skipped".into(),
                    status_label: crate::commands::PROVISION_SKIPPED_LABEL.into(),
                    handler: skip.handler.clone(),
                    note_ref: None,
                }));
            }

            if let Some((_, unavailable)) = pack_unavailable
                .iter()
                .find(|(name, _)| name == &pr.pack_name)
            {
                for entry in unavailable {
                    let Some(row) = entry.availability.unavailable_row(&entry.handler) else {
                        continue;
                    };
                    notes.push(DisplayNote {
                        body: row.note,
                        hint: None,
                        kind: row.note_kind.into(),
                        timeline: None,
                        command: None,
                    });
                    files.push(DisplayFile {
                        name: entry.relative_path.clone(),
                        symbol: handler_symbol(&entry.handler).into(),
                        description: handler_description(
                            &entry.handler,
                            &entry.relative_path,
                            None,
                        ),
                        status: row.style.into(),
                        status_label: row.label,
                        handler: entry.handler.clone(),
                        note_ref: Some(notes.len() as u32),
                    });
                }
            }

            if let Some(err) = &pr.error {
                notes.push(DisplayNote::error(err.clone()));
                files.push(DisplayFile {
                    name: String::new(),
                    symbol: "×".into(),
                    description: String::new(),
                    status: "error".into(),
                    status_label: "error".into(),
                    handler: String::new(),
                    note_ref: Some(notes.len() as u32),
                });
            }

            DisplayPack::new(pr.pack_name.clone(), files)
        })
        .collect();
    (packs, notes)
}

/// Take the steady-state DisplayPacks produced by `status::status()` and
/// flip the matching row's status to "error" for any failed operation,
/// attaching a note with the full error body. Pack-level errors (intent
/// collection, execution) synthesize a dedicated error row at the end of
/// the pack. All notes share a single 1-based command-wide index.
pub(crate) fn overlay_errors(
    mut packs: Vec<DisplayPack>,
    pack_results: &[PackResult],
    home: &std::path::Path,
    notes: &mut Vec<DisplayNote>,
) -> Vec<DisplayPack> {
    for pr in pack_results {
        let display_pack = match packs.iter_mut().find(|p| p.name == pr.pack_name) {
            Some(p) => p,
            None => continue,
        };

        for op_result in &pr.operations {
            if op_result.success {
                continue;
            }
            let (handler, name, user_target) = extract_op_info(&op_result.operation, home);
            let body = op_result.message.clone();

            // Prefer to flip the existing status row so the file listing
            // stays one line per item. Match order:
            //   1. (handler, name) — exact match. Status rows are keyed
            //      by pack-relative path, and a RunCommand carries the
            //      same pack-relative path, so this is the match for a
            //      failed provisioning run at any depth.
            //   2. (handler, user_target) — covers the pre-link CreateUserLink
            //      conflict case where datastore_path is defaulted (empty)
            //      and the op's "name" comes from user_path.file_name(),
            //      which won't match a `home.X` or subdir pack row. The
            //      row's description is the shortened user_target, so that
            //      matches what the op tried to write.
            //   3. Fallback: match by name only (any handler).
            //   4. Synthesize a new error row if nothing matched.
            let pos = display_pack
                .files
                .iter()
                .position(|f| f.handler == handler && f.name == name)
                .or_else(|| {
                    user_target.as_ref().and_then(|ut| {
                        display_pack
                            .files
                            .iter()
                            .position(|f| f.handler == handler && &f.description == ut)
                    })
                })
                .or_else(|| display_pack.files.iter().position(|f| f.name == name));

            match pos {
                Some(idx) => {
                    // If the row already carries a note (e.g. status flagged
                    // it as PendingConflict), replace that note in place so
                    // numbering stays contiguous and we don't leave a stale
                    // "would conflict" note alongside the actual failure.
                    let file = &mut display_pack.files[idx];
                    if let Some(existing) = file.note_ref {
                        notes[(existing - 1) as usize] = DisplayNote::error(body);
                    } else {
                        notes.push(DisplayNote::error(body));
                        file.note_ref = Some(notes.len() as u32);
                    }
                    file.status = "error".into();
                    file.status_label = "error".into();
                }
                None => {
                    notes.push(DisplayNote::error(body));
                    display_pack.files.push(DisplayFile {
                        name: name.clone(),
                        symbol: handler_symbol(&handler).into(),
                        description: handler_description(&handler, &name, user_target.as_deref()),
                        status: "error".into(),
                        status_label: "error".into(),
                        handler,
                        note_ref: Some(notes.len() as u32),
                    });
                }
            }
        }

        if let Some(err) = &pr.error {
            // Pack-level errors (intent collection failure, orchestration
            // failure bubbled up from execute_intents) don't name a
            // specific file. Attach the note to an existing row so the
            // user can tell which item the failure relates to. Prefer a
            // row that isn't already flipped to error (otherwise we'd
            // clobber a more specific per-op note); if no row qualifies,
            // synthesize a pack-level error row as a last resort.
            let fallback_idx = if display_pack.files.is_empty() {
                None
            } else {
                Some(0)
            };
            let target_idx = display_pack
                .files
                .iter()
                .position(|f| f.status != "error")
                .or(fallback_idx);
            let body = err.clone();
            match target_idx {
                Some(idx) => {
                    let file = &mut display_pack.files[idx];
                    if let Some(existing) = file.note_ref {
                        notes[(existing - 1) as usize] = DisplayNote::error(body);
                    } else {
                        notes.push(DisplayNote::error(body));
                        file.note_ref = Some(notes.len() as u32);
                    }
                    file.status = "error".into();
                    file.status_label = "error".into();
                }
                None => {
                    notes.push(DisplayNote::error(body));
                    display_pack.files.push(DisplayFile {
                        name: String::new(),
                        symbol: "×".into(),
                        description: String::new(),
                        status: "error".into(),
                        status_label: "error".into(),
                        handler: String::new(),
                        note_ref: Some(notes.len() as u32),
                    });
                }
            }
        }
    }
    for pack in &mut packs {
        pack.recompute_summary();
    }
    packs
}

/// Extract handler name, display name, and optional user target from an operation.
fn extract_op_info(
    op: &crate::operations::Operation,
    home: &std::path::Path,
) -> (String, String, Option<String>) {
    match op {
        crate::operations::Operation::CreateDataLink {
            handler, source, ..
        } => (
            handler.clone(),
            source
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned(),
            None,
        ),
        crate::operations::Operation::CreateUserLink {
            handler,
            datastore_path,
            user_path,
            ..
        } => {
            let name = datastore_path
                .file_name()
                .unwrap_or_else(|| user_path.file_name().unwrap_or_default())
                .to_string_lossy()
                .into_owned();
            let target = if let Ok(rel) = user_path.strip_prefix(home) {
                format!("~/{}", rel.display())
            } else {
                user_path.display().to_string()
            };
            (handler.clone(), name, Some(target))
        }
        // The run-once file, not the command line: this name is what
        // `overlay_errors` matches against the status rows, and those
        // are keyed by the pack-relative path of the file a rule
        // matched (`install.sh`, `extras/install.sh`), never by the
        // `bash -- /long/path` dodot built from it. Carrying the full
        // relative path — not the basename — is what keeps two
        // same-named run-once files in one pack from flipping each
        // other's row. The command line still reaches the user, in
        // the row's message.
        crate::operations::Operation::RunCommand {
            handler,
            relative_path,
            ..
        } => (handler.clone(), relative_path.clone(), None),
        crate::operations::Operation::CheckSentinel {
            handler, sentinel, ..
        } => (handler.clone(), sentinel.clone(), None),
        crate::operations::Operation::FetchExternal {
            handler, name, url, ..
        } => (handler.clone(), format!("{name}{url}"), None),
    }
}