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
//! `RunOnceCommand` + `RunOnceHandler<C>` — the shared shape behind
//! the run-once provisioning handlers (`install`, `homebrew`, and the
//! forthcoming `nix`).
//!
//! All three of these handlers do the same job: run a program on a
//! user-provided file, hash the file, write a sentinel so we know not
//! to run again unnecessarily. This module owns that logic once.
//! Per-handler specialization (program name, argument shape, optional
//! pre-flight validation, status copy) lives in a small
//! [`RunOnceCommand`] trait, with [`RunOnceHandler`] handling the
//! rest.
//!
//! # Three-state run-once semantics (#169 PR C / PR D)
//!
//! Run-once handlers consult [`DataStore::did_run`](crate::datastore::DataStore::did_run)
//! to classify a matched file into one of three states:
//!
//! 1. [`NeverRan`](crate::datastore::DidRunStatus::NeverRan) — no
//!    sentinel exists; emit a [`HandlerIntent::Run`] for the file.
//! 2. [`RanCurrent`](crate::datastore::DidRunStatus::RanCurrent) — a
//!    sentinel exists whose recorded hash matches the current
//!    content; skip silently.
//! 3. [`RanDifferent`](crate::datastore::DidRunStatus::RanDifferent) — a
//!    sentinel exists but for a *different* content hash; skip with
//!    notice. The user opts in to re-running via
//!    `dodot up --provision-rerun` (the existing `provision_rerun`
//!    flag — distinct from `--force`, which only overwrites
//!    pre-existing files at symlink target paths).
//!
//! `dodot status` renders this three-way result as `pending` /
//! `deployed` / `older version (N lines added, M removed)` rows; the
//! `--diff` flag dumps the underlying snapshot-vs-current unified
//! diff for the third state.
//!
//! # Snapshots
//!
//! [`DataStore::run_and_record`](crate::datastore::DataStore::run_and_record)
//! writes a `<sentinel>.snapshot` sibling capturing the script's bytes
//! at the moment of a successful run. Snapshots are the data behind
//! the `(N+ M-)` summary in status and the body of
//! `dodot status --diff`. Sentinels predating the convention
//! (pre-#169 PR C) have no snapshot — those rows surface as `older
//! version (no diff data)` and are excluded from `--diff` output.
//!
//! Snapshots live at
//! `<datastore>/packs/<pack>/<handler>/<filename>-<hash>.snapshot`;
//! users who want to manage state directly can delete the sentinel +
//! snapshot pair to roll a file back to `never ran`.

use std::io::Read;
use std::path::Path;

use sha2::{Digest, Sha256};

use crate::datastore::{CommandRunner, DataStore};
use crate::fs::Fs;
use crate::handlers::{ExecutionPhase, Handler, HandlerConfig, HandlerStatus};
use crate::operations::HandlerIntent;
use crate::paths::Pather;
use crate::rules::RuleMatch;
use crate::Result;

/// Per-handler specialization for a run-once handler.
///
/// Implementations declare the handler's identity (name, phase) and
/// how a matched file becomes a command invocation. They may
/// optionally provide a pre-flight check ([`Self::validate`]) and
/// customize status messages for the three-state run-once model
/// described at the module level — `pending` /
/// `deployed` / `ran older version`. Everything else (hashing,
/// sentinel construction, `did_run` lookup, intent emission) is
/// shared via [`RunOnceHandler`].
///
/// # Lifecycle invariant
///
/// Every `RunOnceCommand` implementation shares an **identical
/// has-run / which-version-has-run / will-run lifecycle**. The
/// shared [`RunOnceHandler`] consults
/// [`DataStore::did_run`](crate::datastore::DataStore::did_run) and
/// renders the three states (`NeverRan` / `RanCurrent` /
/// `RanDifferent`) the same way for every command. Permitted
/// specializations are limited to:
///
/// - the executable + arguments to run ([`Self::command_for`]),
/// - status-message copy ([`Self::status_pending`] etc.),
/// - **environmental** pre-flight checks ([`Self::validate`]) —
///   things that fail consistently per-environment (tool present,
///   file readable), not per-content.
///
/// **Per-content gatekeeping at planning time is explicitly out
/// of scope.** Content errors (malformed manifest, syntax error,
/// unsupported shape) must surface at apply time, the same way a
/// broken `Brewfile` errors out of `brew bundle` or a broken
/// `install.sh` errors out of `bash`. A validator that rejects
/// per content breaks the lifecycle invariant: a previously-run
/// file the user later edits into a broken state would fail
/// planning here instead of reaching the `RanDifferent`
/// "older version" notice the run-once policy promises. That
/// asymmetry across commands is the bug, not the feature.
pub trait RunOnceCommand: Send + Sync {
    /// Unique handler name (e.g. `"install"`, `"homebrew"`, `"nix"`).
    fn handler_name(&self) -> &str;

    /// Execution phase for this handler.
    fn phase(&self) -> ExecutionPhase;

    /// Build the `(executable, arguments)` tuple for invoking the
    /// command against `path`.
    fn command_for(&self, path: &Path) -> (String, Vec<String>);

    /// Optional pre-flight check. Default: no-op.
    ///
    /// **Scope: environmental, not content.** See the
    /// "Lifecycle invariant" section in the trait docs — a
    /// validator that fails per-content (e.g. file-syntax check,
    /// manifest-shape rejection) breaks the shared `did_run`
    /// lifecycle by failing planning for a file the run-once
    /// policy says should surface as `older version`. Use
    /// `validate` only for environment-level prerequisites that
    /// fail consistently regardless of the file's current
    /// contents.
    ///
    /// Returning `Err` aborts intent generation for the matched
    /// file and propagates the error. The default implementation
    /// passes any file through unchanged.
    ///
    /// Implementations receive both `fs` (for reading the matched
    /// file's bytes without re-entering the executor) and `runner`
    /// (for shelling out to verify the tool is invokable —
    /// e.g. `nix --version`, `brew --version`). The runner is the
    /// same `CommandRunner` the executor uses for the install
    /// path, so a validator's subprocess output is captured the
    /// same way as the eventual install command's.
    fn validate(&self, _fs: &dyn Fs, _runner: &dyn CommandRunner, _path: &Path) -> Result<()> {
        Ok(())
    }

    /// Human-readable status message when a current-hash sentinel
    /// exists. Default: `"ran"`. Override for per-handler copy
    /// (e.g. `"brew packages installed"`).
    fn status_deployed(&self) -> &str {
        "ran"
    }

    /// Human-readable status message when no sentinel exists.
    /// Default: `"never ran"`.
    fn status_pending(&self) -> &str {
        "never ran"
    }

    /// Human-readable status message when a sentinel exists but for
    /// a *different* content hash — the file has been edited since
    /// the last successful run, but the conservative
    /// notify-don't-rerun policy (#169 PR C) leaves the prior state
    /// in place until the user opts in via `--provision-rerun`.
    ///
    /// Default: `"older version"`. Overridden per-handler for
    /// readability — e.g. `"brew packages older version"` for
    /// homebrew. `dodot status` further annotates this label with a
    /// `(N lines added, M removed)` summary when a snapshot of the
    /// previously-run content is available, or with `(no diff data)`
    /// for sentinels written before snapshots were introduced.
    fn status_ran_different(&self) -> &str {
        "older version"
    }
}

/// The shared body for run-once handlers.
///
/// Holds borrows of [`Fs`] + [`CommandRunner`] and an instance of some
/// [`RunOnceCommand`]. Implements [`Handler`] by routing per-handler
/// concerns to the command and keeping the shared logic — checksum,
/// sentinel, intent construction, status lookup — in one place.
///
/// The runner is passed straight through to
/// [`RunOnceCommand::validate`] at intent-production time so an
/// environmental pre-flight (e.g. verifying the tool is on PATH
/// via `<tool> --version`) can shell out without owning its own
/// runner.
pub struct RunOnceHandler<'a, C: RunOnceCommand> {
    fs: &'a dyn Fs,
    runner: &'a dyn CommandRunner,
    cmd: C,
}

impl<'a, C: RunOnceCommand> RunOnceHandler<'a, C> {
    pub fn new(fs: &'a dyn Fs, runner: &'a dyn CommandRunner, cmd: C) -> Self {
        Self { fs, runner, cmd }
    }

    /// Access the underlying command (useful in tests).
    pub fn command(&self) -> &C {
        &self.cmd
    }
}

impl<C: RunOnceCommand> Handler for RunOnceHandler<'_, C> {
    fn name(&self) -> &str {
        self.cmd.handler_name()
    }

    fn phase(&self) -> ExecutionPhase {
        self.cmd.phase()
    }

    fn to_intents(
        &self,
        matches: &[RuleMatch],
        _config: &HandlerConfig,
        _paths: &dyn Pather,
        _fs: &dyn Fs,
    ) -> Result<Vec<HandlerIntent>> {
        let mut intents = Vec::new();

        for m in matches {
            if m.is_dir {
                continue;
            }

            // First-time-pack passive case: a templated file with no
            // baseline yet lands here as a placeholder match (no
            // bytes, no file on disk). We can't compute a sentinel
            // without rendering, and rendering is the §7.4 violation
            // we refuse. Skip intent generation for this match —
            // status / dry-run will report the file as pending via
            // the symlink chain instead, and the next real `dodot
            // up` plans the Run intent normally. See issue #121.
            //
            // This skip runs *before* validation: a placeholder has
            // no content for a validator to inspect, and we shouldn't
            // surface a validation error for a file that may not
            // exist yet in any meaningful sense.
            let has_rendered = m.rendered_bytes.is_some();
            let has_disk = self.fs.exists(&m.absolute_path);
            if !has_rendered && !has_disk {
                tracing::debug!(
                    pack = %m.pack,
                    file = %m.absolute_path.display(),
                    handler = self.cmd.handler_name(),
                    "skipping run-once intent — no rendered bytes and no on-disk file \
                     (first-time-pack passive placeholder)"
                );
                continue;
            }

            // We have content. Validate first, then hash.
            self.cmd.validate(self.fs, self.runner, &m.absolute_path)?;

            // Sentinel hashing prefers in-memory rendered bytes when
            // they're available (preprocessor-produced files); falls
            // back to a disk read for plain on-disk files. The
            // in-memory path is what lets `dodot status` and `up
            // --dry-run` compute correct sentinels for templated
            // files without writing the rendered file to disk.
            let checksum = match m.rendered_bytes.as_deref() {
                Some(bytes) => file_checksum_bytes(bytes),
                None => file_checksum(self.fs, &m.absolute_path)?,
            };

            let filename = m
                .relative_path
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
                .into_owned();
            let sentinel = format!("{filename}-{checksum}");

            let (executable, arguments) = self.cmd.command_for(&m.absolute_path);

            intents.push(HandlerIntent::Run {
                pack: m.pack.clone(),
                handler: self.cmd.handler_name().into(),
                executable,
                arguments,
                sentinel,
                filename,
                content_hash: checksum,
            });
        }

        Ok(intents)
    }

    fn check_status(
        &self,
        file: &Path,
        pack: &str,
        datastore: &dyn DataStore,
    ) -> Result<HandlerStatus> {
        let checksum = file_checksum(self.fs, file)?;
        let filename = file
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .into_owned();

        let status = datastore.did_run(pack, self.cmd.handler_name(), &filename, &checksum)?;

        // Map the three-way did_run result to the binary
        // deployed/not-deployed status with a descriptive message.
        // `RanDifferent` is marked deployed=true (the script HAS run,
        // just not for the current content) so callers that filter by
        // `deployed` don't miss the entry; the message disambiguates
        // current-version vs. older-version. This is the surface that
        // `dodot status` and `dodot up`'s post-execute rendering both
        // read from, so the "ran older version" notice reaches the
        // user even though it bypasses the OperationResult flow.
        let (deployed, message) = match status {
            crate::datastore::DidRunStatus::NeverRan => (false, self.cmd.status_pending().into()),
            crate::datastore::DidRunStatus::RanCurrent => (true, self.cmd.status_deployed().into()),
            crate::datastore::DidRunStatus::RanDifferent { .. } => (
                true,
                format!(
                    "{} (older version — run `dodot up --provision-rerun` to apply current)",
                    self.cmd.status_deployed()
                ),
            ),
        };

        Ok(HandlerStatus {
            file: file.to_string_lossy().into_owned(),
            handler: self.cmd.handler_name().into(),
            deployed,
            message,
        })
    }
}

/// Canonical run-state copy for a [`RunOnceCommand`] — used by
/// `dodot status` to render the three-state row label without
/// needing a `Box<dyn Handler>` registered with the right `Fs`.
pub struct RunOnceStatusMessages {
    /// Label when no sentinel exists (`DidRunStatus::NeverRan`).
    pub pending: String,
    /// Label when a sentinel matches the current content
    /// (`DidRunStatus::RanCurrent`).
    pub deployed: String,
    /// Label when a sentinel exists for a *different* content hash
    /// (`DidRunStatus::RanDifferent`).
    pub ran_different: String,
}

/// Snapshot the three trait-defined messages off a concrete
/// [`RunOnceCommand`] into owned strings so callers don't have to
/// keep the command instance alive to read them.
pub fn status_messages_for<C: RunOnceCommand>(cmd: &C) -> RunOnceStatusMessages {
    RunOnceStatusMessages {
        pending: cmd.status_pending().to_string(),
        deployed: cmd.status_deployed().to_string(),
        ran_different: cmd.status_ran_different().to_string(),
    }
}

/// Look up the canonical run-state copy for a built-in run-once
/// handler by name. `dodot status` consults this so it can render
/// the three-state row label per handler without instantiating a
/// `RunOnceHandler<C>` against the right `Fs`. Unknown handler names
/// fall back to the trait defaults.
pub fn run_once_status_messages(handler: &str) -> RunOnceStatusMessages {
    use crate::handlers::{HANDLER_HOMEBREW, HANDLER_INSTALL, HANDLER_NIX};
    if handler == HANDLER_INSTALL {
        return status_messages_for(&crate::handlers::install::InstallCommand);
    }
    if handler == HANDLER_HOMEBREW {
        return status_messages_for(&crate::handlers::homebrew::BrewfileCommand);
    }
    if handler == HANDLER_NIX {
        return status_messages_for(&crate::handlers::nix::NixCommand);
    }
    RunOnceStatusMessages {
        pending: "never ran".into(),
        deployed: "ran".into(),
        ran_different: "older version".into(),
    }
}

/// Compute a short SHA-256 hex digest of a file's contents.
///
/// Returns the first 8 bytes of the SHA-256 hash as 16 hex chars —
/// unique enough for sentinel-name disambiguation, short enough to
/// keep on-disk paths readable.
///
/// Internal helper used by [`RunOnceHandler`] and (in PR B) by the
/// retrofitted `install` / `homebrew` handlers. Crate-scoped to keep
/// it out of dodot-lib's public API surface.
pub(crate) fn file_checksum(fs: &dyn Fs, path: &Path) -> Result<String> {
    let mut reader = fs.open_read(path)?;
    let mut hasher = Sha256::new();
    let mut buf = [0u8; 8192];
    loop {
        let n = reader.read(&mut buf).map_err(|e| crate::DodotError::Fs {
            path: path.to_path_buf(),
            source: e,
        })?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    let hash = hasher.finalize();
    Ok(hex_encode(&hash[..8]))
}

/// Same digest format as [`file_checksum`], but over an in-memory
/// byte slice — used when the rendered content is available without
/// a disk read.
pub(crate) fn file_checksum_bytes(bytes: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    let hash = hasher.finalize();
    hex_encode(&hash[..8])
}

fn hex_encode(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::datastore::{CommandOutput, CommandRunner, FilesystemDataStore};
    use crate::testing::TempEnvironment;
    use std::collections::HashMap;
    use std::path::PathBuf;
    use std::sync::Arc;

    // Compile-time check: RunOnceCommand is object-safe.
    #[allow(dead_code)]
    fn assert_object_safe(_: &dyn RunOnceCommand) {}

    struct NoopRunner;
    impl CommandRunner for NoopRunner {
        fn run(&self, _: &str, _: &[String]) -> Result<CommandOutput> {
            Ok(CommandOutput {
                exit_code: 0,
                stdout: String::new(),
                stderr: String::new(),
            })
        }
    }

    fn make_datastore(env: &TempEnvironment) -> FilesystemDataStore {
        FilesystemDataStore::new(env.fs.clone(), env.paths.clone(), Arc::new(NoopRunner))
    }

    /// Test double — a minimal `RunOnceCommand` implementation.
    struct FakeCommand {
        name: &'static str,
        phase: ExecutionPhase,
        executable: String,
        args_template: Vec<String>,
        validate_fails: bool,
        deployed_msg: &'static str,
        pending_msg: &'static str,
    }

    impl FakeCommand {
        fn new(name: &'static str) -> Self {
            Self {
                name,
                phase: ExecutionPhase::Setup,
                executable: "test-cmd".into(),
                args_template: Vec::new(),
                validate_fails: false,
                deployed_msg: "ran",
                pending_msg: "never ran",
            }
        }
    }

    impl RunOnceCommand for FakeCommand {
        fn handler_name(&self) -> &str {
            self.name
        }
        fn phase(&self) -> ExecutionPhase {
            self.phase
        }
        fn command_for(&self, path: &Path) -> (String, Vec<String>) {
            let mut args = self.args_template.clone();
            args.push(path.to_string_lossy().into_owned());
            (self.executable.clone(), args)
        }
        fn validate(&self, _fs: &dyn Fs, _runner: &dyn CommandRunner, path: &Path) -> Result<()> {
            if self.validate_fails {
                Err(crate::DodotError::Fs {
                    path: path.to_path_buf(),
                    source: std::io::Error::other("synthetic validation failure"),
                })
            } else {
                Ok(())
            }
        }
        fn status_deployed(&self) -> &str {
            self.deployed_msg
        }
        fn status_pending(&self) -> &str {
            self.pending_msg
        }
    }

    fn make_match(
        pack: &str,
        relative: &str,
        absolute: PathBuf,
        rendered: Option<Vec<u8>>,
    ) -> RuleMatch {
        RuleMatch {
            relative_path: relative.into(),
            absolute_path: absolute,
            pack: pack.into(),
            handler: "fake".into(),
            is_dir: false,
            options: HashMap::new(),
            preprocessor_source: None,
            rendered_bytes: rendered.map(Arc::from),
        }
    }

    fn pather(env: &TempEnvironment) -> crate::paths::XdgPather {
        crate::paths::XdgPather::builder()
            .home(&env.home)
            .dotfiles_root(&env.dotfiles_root)
            .build()
            .unwrap()
    }

    #[test]
    fn handler_exposes_command_identity() {
        let env = TempEnvironment::builder().build();
        let handler = RunOnceHandler::new(
            env.fs.as_ref(),
            &NoopRunner,
            FakeCommand {
                phase: ExecutionPhase::Provision,
                ..FakeCommand::new("widget")
            },
        );
        assert_eq!(handler.name(), "widget");
        assert_eq!(handler.phase(), ExecutionPhase::Provision);
    }

    #[test]
    fn to_intents_emits_run_with_shared_shape() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("setup.sh", "echo hi")
            .done()
            .build();

        let cmd = FakeCommand {
            executable: "bash".into(),
            args_template: vec!["--".into()],
            ..FakeCommand::new("fake")
        };
        let handler = RunOnceHandler::new(env.fs.as_ref(), &NoopRunner, cmd);

        let abs = env.dotfiles_root.join("vim/setup.sh");
        let matches = vec![make_match("vim", "setup.sh", abs.clone(), None)];
        let intents = handler
            .to_intents(
                &matches,
                &HandlerConfig::default(),
                &pather(&env),
                env.fs.as_ref(),
            )
            .unwrap();

        assert_eq!(intents.len(), 1);
        match &intents[0] {
            HandlerIntent::Run {
                pack,
                handler: h,
                executable,
                arguments,
                sentinel,
                filename,
                content_hash,
            } => {
                assert_eq!(pack, "vim");
                assert_eq!(h, "fake");
                assert_eq!(executable, "bash");
                // Args template + appended path.
                assert_eq!(arguments[0], "--");
                assert!(arguments[1].ends_with("vim/setup.sh"));
                // Sentinel shape: "<filename>-<16 hex chars>".
                assert!(sentinel.starts_with("setup.sh-"));
                assert_eq!(sentinel.len(), "setup.sh-".len() + 16);
                assert_eq!(filename, "setup.sh");
                assert_eq!(content_hash.len(), 16);
                assert_eq!(*sentinel, format!("{filename}-{content_hash}"));
            }
            other => panic!("expected Run, got {other:?}"),
        }
    }

    #[test]
    fn to_intents_prefers_rendered_bytes_over_disk_read() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("setup.sh", "on-disk content")
            .done()
            .build();
        let abs = env.dotfiles_root.join("vim/setup.sh");

        let handler = RunOnceHandler::new(env.fs.as_ref(), &NoopRunner, FakeCommand::new("fake"));

        let rendered = b"rendered content".to_vec();
        let expected_checksum = file_checksum_bytes(&rendered);
        let matches = vec![make_match("vim", "setup.sh", abs.clone(), Some(rendered))];
        let intents = handler
            .to_intents(
                &matches,
                &HandlerConfig::default(),
                &pather(&env),
                env.fs.as_ref(),
            )
            .unwrap();

        match &intents[0] {
            HandlerIntent::Run { sentinel, .. } => {
                assert_eq!(*sentinel, format!("setup.sh-{expected_checksum}"));
            }
            other => panic!("expected Run, got {other:?}"),
        }
    }

    #[test]
    fn to_intents_falls_back_to_disk_when_no_rendered_bytes() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("setup.sh", "disk content")
            .done()
            .build();
        let abs = env.dotfiles_root.join("vim/setup.sh");

        let handler = RunOnceHandler::new(env.fs.as_ref(), &NoopRunner, FakeCommand::new("fake"));

        let expected_checksum = file_checksum(env.fs.as_ref(), &abs).unwrap();
        let matches = vec![make_match("vim", "setup.sh", abs, None)];
        let intents = handler
            .to_intents(
                &matches,
                &HandlerConfig::default(),
                &pather(&env),
                env.fs.as_ref(),
            )
            .unwrap();

        match &intents[0] {
            HandlerIntent::Run { sentinel, .. } => {
                assert_eq!(*sentinel, format!("setup.sh-{expected_checksum}"));
            }
            other => panic!("expected Run, got {other:?}"),
        }
    }

    #[test]
    fn validate_does_not_fire_on_placeholder_match() {
        // A validator that always errors must NOT be called for a
        // first-time-pack passive placeholder (no rendered bytes, no
        // on-disk file). Regression test for Copilot review on #170 —
        // the earlier draft validated before checking for content.
        let env = TempEnvironment::builder().build();
        let cmd = FakeCommand {
            validate_fails: true,
            ..FakeCommand::new("fake")
        };
        let handler = RunOnceHandler::new(env.fs.as_ref(), &NoopRunner, cmd);

        let ghost = env.dotfiles_root.join("ghost/install.sh"); // never written
        let matches = vec![make_match("ghost", "install.sh", ghost, None)];
        let intents = handler
            .to_intents(
                &matches,
                &HandlerConfig::default(),
                &pather(&env),
                env.fs.as_ref(),
            )
            .expect("placeholder match should skip cleanly without invoking validate");
        assert!(intents.is_empty());
    }

    #[test]
    fn to_intents_skips_first_time_pack_passive_placeholder() {
        // No rendered_bytes, file doesn't exist on disk → skip (no
        // intent), don't error.
        let env = TempEnvironment::builder().build();
        let handler = RunOnceHandler::new(env.fs.as_ref(), &NoopRunner, FakeCommand::new("fake"));

        let ghost = env.dotfiles_root.join("ghost/install.sh"); // never written
        let matches = vec![make_match("ghost", "install.sh", ghost, None)];
        let intents = handler
            .to_intents(
                &matches,
                &HandlerConfig::default(),
                &pather(&env),
                env.fs.as_ref(),
            )
            .unwrap();

        assert!(intents.is_empty());
    }

    #[test]
    fn to_intents_propagates_validation_error() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("setup.sh", "content")
            .done()
            .build();
        let abs = env.dotfiles_root.join("vim/setup.sh");

        let cmd = FakeCommand {
            validate_fails: true,
            ..FakeCommand::new("fake")
        };
        let handler = RunOnceHandler::new(env.fs.as_ref(), &NoopRunner, cmd);

        let matches = vec![make_match("vim", "setup.sh", abs, None)];
        let result = handler.to_intents(
            &matches,
            &HandlerConfig::default(),
            &pather(&env),
            env.fs.as_ref(),
        );
        assert!(
            result.is_err(),
            "expected validate failure to propagate, got {result:?}"
        );
    }

    #[test]
    fn to_intents_skips_directories() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("scripts/run", "x")
            .done()
            .build();
        let handler = RunOnceHandler::new(env.fs.as_ref(), &NoopRunner, FakeCommand::new("fake"));

        let dir_match = RuleMatch {
            is_dir: true,
            ..make_match(
                "vim",
                "scripts",
                env.dotfiles_root.join("vim/scripts"),
                None,
            )
        };
        let intents = handler
            .to_intents(
                &[dir_match],
                &HandlerConfig::default(),
                &pather(&env),
                env.fs.as_ref(),
            )
            .unwrap();
        assert!(intents.is_empty());
    }

    #[test]
    fn to_intents_emits_one_intent_per_match() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("a.sh", "alpha")
            .file("b.sh", "beta")
            .done()
            .build();
        let handler = RunOnceHandler::new(env.fs.as_ref(), &NoopRunner, FakeCommand::new("fake"));

        let matches = vec![
            make_match("vim", "a.sh", env.dotfiles_root.join("vim/a.sh"), None),
            make_match("vim", "b.sh", env.dotfiles_root.join("vim/b.sh"), None),
        ];
        let intents = handler
            .to_intents(
                &matches,
                &HandlerConfig::default(),
                &pather(&env),
                env.fs.as_ref(),
            )
            .unwrap();
        assert_eq!(intents.len(), 2);
    }

    #[test]
    fn check_status_reports_deployed_when_sentinel_exists() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("setup.sh", "content")
            .done()
            .build();
        let abs = env.dotfiles_root.join("vim/setup.sh");
        let checksum = file_checksum(env.fs.as_ref(), &abs).unwrap();
        let sentinel = format!("setup.sh-{checksum}");

        // Pre-create the sentinel on disk so check_status finds it.
        let sentinel_dir = env.paths.handler_data_dir("vim", "fake");
        env.fs.mkdir_all(&sentinel_dir).unwrap();
        env.fs
            .write_file(&sentinel_dir.join(&sentinel), b"completed|0")
            .unwrap();

        let datastore = make_datastore(&env);
        let cmd = FakeCommand {
            deployed_msg: "all set",
            ..FakeCommand::new("fake")
        };
        let handler = RunOnceHandler::new(env.fs.as_ref(), &NoopRunner, cmd);

        let status = handler.check_status(&abs, "vim", &datastore).unwrap();
        assert!(status.deployed);
        assert_eq!(status.message, "all set");
        assert_eq!(status.handler, "fake");
    }

    #[test]
    fn check_status_reports_older_version_when_hash_differs() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("setup.sh", "new content")
            .done()
            .build();
        let abs = env.dotfiles_root.join("vim/setup.sh");

        // Pre-create a sentinel for a different hash → did_run
        // returns RanDifferent → check_status reports "older version".
        let sentinel_dir = env.paths.handler_data_dir("vim", "fake");
        env.fs.mkdir_all(&sentinel_dir).unwrap();
        env.fs
            .write_file(
                &sentinel_dir.join("setup.sh-aaaaaaaaaaaaaaaa"),
                b"completed|100",
            )
            .unwrap();

        let datastore = make_datastore(&env);
        let cmd = FakeCommand {
            deployed_msg: "ran",
            ..FakeCommand::new("fake")
        };
        let handler = RunOnceHandler::new(env.fs.as_ref(), &NoopRunner, cmd);

        let status = handler.check_status(&abs, "vim", &datastore).unwrap();
        assert!(status.deployed, "older version still counts as deployed");
        assert!(
            status.message.contains("older version"),
            "message should flag older version, got: {}",
            status.message
        );
        assert!(
            status.message.contains("--provision-rerun"),
            "message should mention --provision-rerun, got: {}",
            status.message
        );
    }

    #[test]
    fn check_status_reports_pending_when_no_sentinel() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("setup.sh", "content")
            .done()
            .build();
        let abs = env.dotfiles_root.join("vim/setup.sh");

        let datastore = make_datastore(&env);
        let cmd = FakeCommand {
            pending_msg: "needs attention",
            ..FakeCommand::new("fake")
        };
        let handler = RunOnceHandler::new(env.fs.as_ref(), &NoopRunner, cmd);

        let status = handler.check_status(&abs, "vim", &datastore).unwrap();
        assert!(!status.deployed);
        assert_eq!(status.message, "needs attention");
    }

    #[test]
    fn file_checksum_and_bytes_agree() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("file.txt", "consistent content")
            .done()
            .build();
        let abs = env.dotfiles_root.join("vim/file.txt");
        let disk = file_checksum(env.fs.as_ref(), &abs).unwrap();
        let in_mem = file_checksum_bytes(b"consistent content");
        assert_eq!(disk, in_mem);
        assert_eq!(disk.len(), 16);
    }

    #[test]
    fn file_checksum_changes_with_content() {
        let a = file_checksum_bytes(b"version 1");
        let b = file_checksum_bytes(b"version 2");
        assert_ne!(a, b);
    }
}