dodot-lib 5.6.0

Core library for dodot dotfiles manager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
//! The verification probe — measuring whether a *new* shell would
//! activate dodot (`docs/proposals/shipped/shell-hookup.lex` §3).
//!
//! Signals 1 and 2 (the environment stamp and the heartbeat, both in
//! [`crate::shell::activation`]) answer "is this shell live?" and "has
//! any shell activated?". Neither answers the question a fresh install
//! or a freshly broken hookup actually poses: *would the next terminal
//! the user opens load dodot?* Only running one answers that, so when
//! the cheap signals come back inconclusive, dodot spawns the user's
//! shell and reads the stamp back out of it.
//!
//! # Gating
//!
//! [`gate_says_probe`] is the whole cost story. A current stamp or a
//! fresh heartbeat means shells are activating, and the probe never
//! runs. The first real shell activation writes the heartbeat and
//! retires the probe until the hookup actually breaks — so a healthy
//! machine pays nothing, forever. `dodot status` never spawns a shell
//! at all (spec §9); only `up` and `install` may, and only through
//! [`ProbePolicy::Gated`], which every non-production
//! [`ExecutionContext`](crate::packs::ExecutionContext) leaves at
//! [`ProbePolicy::Never`].
//!
//! # Mechanics
//!
//! User rc files prompt, hang, `exec` into multiplexers, and fail in
//! creative ways, so [`run`] is defensive by construction: interactive
//! non-login shell (the mode that reads the file the hook lives in),
//! stdin from `/dev/null`, output captured, a hard timeout that kills
//! the whole process group, and `DODOT_INIT_*` scrubbed from the child
//! environment — an inherited stamp would be a false positive every
//! time the probe runs from an already-live shell.
//!
//! That defensive envelope lives in [`spawn_captured`], which is the
//! one place dodot spawns anything user-authored: [`run`] uses it for
//! the activation probe, and [`crate::shell::trace`] reuses it
//! unchanged for the hook-line trace (RCS01 WS02) — one audited
//! process-group kill, not two.
//!
//! # Verdicts
//!
//! [`Verdict`] keeps four outcomes apart because they demand
//! different action: verified, version-skew (the shell activated, from
//! a dodot other than the one running), verified-broken (with the
//! static rc scan splitting *hook absent* from *hook present but never
//! reached*), and couldn't-verify, which degrades to the scan's answer
//! labeled as configuration state. A probe failure never wedges `up`.
//!
//! The skew arm is why the probed shell reports *both* halves of the
//! stamp ([`ProbeStamp`]). A generation alone cannot tell a working
//! hookup from one that resolves to the wrong binary — a hand-wired
//! `eval` hook running some other dodot mints a fresh generation just
//! as convincingly as the right one — so reading it alone would report
//! the epic's own failure as health, on the first `up`, which is the
//! run this probe exists for.

use std::io::Read;
use std::path::Path;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use crate::fs::Fs;
use crate::paths::Pather;
use crate::shell::activation::{
    self, ActivationNotice, ActivationState, EvidenceVersion, HeartbeatState, StampState,
    INIT_GEN_ENV, INIT_VERSION_ENV,
};
use crate::shell::rc::{self, HookPresence, ShellEnv};

/// Prefix the probe command prints its stamp behind, so the record we
/// read survives arbitrary rc noise on the same stream.
pub const PROBE_MARKER: &str = "dodot-probe-stamp:";

/// Separates the two fields of a probe record: the generation the
/// spawned shell sourced, and the dodot that wrote it.
pub const PROBE_FIELD_SEP: char = '|';

/// How long a spawned shell gets before its process group is killed.
/// Spec §3.2 calls for "order of 5 seconds": long enough for a heavy
/// rc file, short enough that a hung one is not a hung `dodot up`.
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5);

/// Environment prefix scrubbed from the probed shell.
const SCRUB_PREFIX: &str = "DODOT_INIT_";

/// How long to wait between liveness checks on the spawned shell.
const POLL_INTERVAL: Duration = Duration::from_millis(20);

// ── Policy ──────────────────────────────────────────────────────

/// Whether a command may spawn a shell while judging activation.
///
/// *Which* shell is not this type's business — that comes from the
/// context's [`ShellEnv`], the same value the rc ladder reads, so a
/// probe can never measure one shell while the diagnosis names another
/// shell's rc file.
///
/// Defaults to [`ProbePolicy::Never`], which is what makes "no test
/// ever spawns the developer's real shell" a property of the type
/// rather than of everyone's discipline: only
/// [`ExecutionContext::production`](crate::packs::ExecutionContext::production)
/// opts in, and probe tests opt in with a fabricated shell.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ProbePolicy {
    /// Report from evidence alone. Every test context, and `status`
    /// no matter the context.
    #[default]
    Never,
    /// Spawn the shell when [`gate_says_probe`] says the cheap signals
    /// are inconclusive, giving it `timeout` to finish starting up.
    Gated { timeout: Duration },
}

impl ProbePolicy {
    /// The production policy: gated, with the standard timeout.
    pub fn production() -> Self {
        ProbePolicy::Gated {
            timeout: DEFAULT_TIMEOUT,
        }
    }

    /// The timeout when spawning is allowed at all, else `None`.
    pub fn timeout(&self) -> Option<Duration> {
        match self {
            ProbePolicy::Never => None,
            ProbePolicy::Gated { timeout } => Some(*timeout),
        }
    }
}

/// Whether the cheap signals leave anything worth measuring.
///
/// A current stamp means the calling shell is live; a fresh heartbeat
/// means some shell activated since the last regeneration. Either is
/// proof enough, and proof is cheaper than measurement. Only when
/// neither holds — the fresh-install and broken-hook cases, precisely
/// — is a shell spawn justified (spec §3.1).
pub fn gate_says_probe(stamp: StampState, heartbeat: HeartbeatState) -> bool {
    !matches!(stamp, StampState::Current) && !matches!(heartbeat, HeartbeatState::Fresh)
}

// ── Running one ─────────────────────────────────────────────────

/// What the spawned shell reported about the init script it sourced.
///
/// Both fields, never just the generation: a hookup can source a
/// current-generation script written by a *different* dodot, and a
/// generation alone reads that as health (`shell-hookup-ergonomics.lex`
/// §2.3). [`EvidenceVersion`] rather than an `Option<String>` so a
/// version-less report carries the same bounded meaning here as it does
/// in the evidence path — one rule, both signals.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProbeStamp {
    /// `DODOT_INIT_GEN` as the spawned shell exported it.
    pub generation: u64,
    /// `DODOT_INIT_VERSION`, or [`EvidenceVersion::PreVersion`] when
    /// the script that ran was too old to export one.
    pub version: EvidenceVersion,
}

/// What one shell spawn reported back.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProbeOutcome {
    /// The shell finished and printed a parseable stamp.
    Stamp(ProbeStamp),
    /// The shell finished and printed no stamp — it did not source
    /// dodot's init script.
    NoStamp,
    /// The shell outlived its timeout; its process group was killed.
    TimedOut,
    /// The shell could not be run at all.
    SpawnFailed(String),
}

/// The line the probe prints before spawning. The probe is announced,
/// never covert (spec §3.2): every terminal open runs the user's rc
/// anyway, and the only unacceptable version of this is a silent one.
pub fn announcement(shell: &Path) -> String {
    let name = shell
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("your shell");
    format!("verifying shell integration ({name})…")
}

/// The command handed to the spawned shell: print both halves of the
/// stamp it may or may not have inherited from its rc, behind a marker.
///
/// Both are printed unconditionally, empty when unset, so the record
/// always has its two fields and the parser never has to guess which
/// one a lone value was.
fn probe_command() -> String {
    format!(
        "printf '{PROBE_MARKER}%s{PROBE_FIELD_SEP}%s\\n' \
         \"${{{INIT_GEN_ENV}-}}\" \"${{{INIT_VERSION_ENV}-}}\""
    )
}

/// Extract the stamp from captured probe output.
///
/// Scans every line for the marker and takes the last one: an rc file
/// is free to print whatever it likes before our command runs, and the
/// probe reads exactly one record out of the noise. A record whose
/// generation does not parse is not a stamp at all — the same rule
/// [`activation::read_heartbeat`] holds the heartbeat to, so an
/// activation is never inferred from a version field alone.
pub fn parse_probe_output(stdout: &str) -> Option<ProbeStamp> {
    stdout
        .lines()
        .filter_map(|line| line.trim().strip_prefix(PROBE_MARKER))
        .filter_map(|record| record.split_once(PROBE_FIELD_SEP))
        .filter_map(|(generation, version)| {
            Some(ProbeStamp {
                generation: activation::parse_generation(generation)?,
                version: EvidenceVersion::from_field(Some(version)),
            })
        })
        .next_back()
}

/// Both streams a spawned process wrote before finishing, and how it
/// finished.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpawnCapture {
    pub stdout: String,
    pub stderr: String,
    /// The exit code, or `None` when the process was killed by a
    /// signal.
    ///
    /// The activation probe ignores it on purpose — unrelated rc
    /// breakage exits non-zero and still activates dodot, so the stamp
    /// is the bit. [`crate::shell::trace`] needs it for the opposite
    /// kind of question: `<shell> -n` answers *only* through its exit
    /// status, and a syntax check whose answer is discarded is a
    /// syntax check that never ran.
    pub status: Option<i32>,
}

/// What became of one enveloped spawn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpawnOutcome {
    /// The process finished (any exit status) within the timeout.
    Finished(SpawnCapture),
    /// The process outlived its timeout; its process group was killed.
    TimedOut,
    /// The process could not be spawned at all.
    SpawnFailed(String),
}

/// Run `command` under the probe envelope and capture both streams.
///
/// The envelope, applied here so every caller gets all of it: stdin
/// from `/dev/null` (an rc file that prompts gets EOF instead of
/// blocking), stdout/stderr captured off-thread (a chatty rc cannot
/// deadlock a full pipe against our wait loop), `DODOT_INIT_*`
/// scrubbed (an inherited stamp must never masquerade as the child's),
/// its own process group, and a hard timeout that kills that whole
/// group. Callers set the program, arguments, and any extra
/// environment before handing the command over.
pub fn spawn_captured(mut command: Command, timeout: Duration) -> SpawnOutcome {
    command
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    for key in scrubbed_keys(std::env::vars().map(|(k, _)| k)) {
        command.env_remove(key);
    }
    // Its own process group, so a timeout can take out everything the
    // rc file spawned, not just the shell we can see.
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        command.process_group(0);
    }

    let mut child = match command.spawn() {
        Ok(c) => c,
        Err(e) => return SpawnOutcome::SpawnFailed(format!("{e}")),
    };
    let pid = child.id();

    // Drain both pipes off-thread: a chatty rc file that fills a pipe
    // buffer would otherwise deadlock against our own wait loop.
    let stdout = child.stdout.take().map(drain);
    let stderr = child.stderr.take().map(drain);

    let deadline = Instant::now() + timeout;
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break Some(status),
            Ok(None) => {}
            Err(e) => return SpawnOutcome::SpawnFailed(format!("{e}")),
        }
        if Instant::now() >= deadline {
            kill_process_group(pid);
            // Reap: the group is dead, so this returns promptly and we
            // leave no zombie behind.
            let _ = child.wait();
            break None;
        }
        std::thread::sleep(POLL_INTERVAL);
    };

    let stdout = stdout.and_then(|h| h.join().ok()).unwrap_or_default();
    let stderr = stderr.and_then(|h| h.join().ok()).unwrap_or_default();

    let Some(status) = status else {
        return SpawnOutcome::TimedOut;
    };
    SpawnOutcome::Finished(SpawnCapture {
        stdout,
        stderr,
        status: status.code(),
    })
}

/// Spawn `shell` interactively and read the stamp back.
///
/// Safe against hostile rc files by construction — the whole
/// [`spawn_captured`] envelope. Never returns an error: every failure
/// mode is an outcome, because a probe that could not run must
/// degrade, not propagate (spec §3.3).
pub fn run(shell: &Path, timeout: Duration) -> ProbeOutcome {
    let mut command = Command::new(shell);
    // Interactive non-login: the mode that reads the rc file the hook
    // lives in.
    command.arg("-ic").arg(probe_command());
    match spawn_captured(command, timeout) {
        SpawnOutcome::SpawnFailed(e) => ProbeOutcome::SpawnFailed(e),
        SpawnOutcome::TimedOut => ProbeOutcome::TimedOut,
        // A nonzero exit is not a failed probe: unrelated rc breakage
        // fails loudly and still activates dodot. The stamp is the bit.
        SpawnOutcome::Finished(capture) => match parse_probe_output(&capture.stdout) {
            Some(stamp) => ProbeOutcome::Stamp(stamp),
            None => ProbeOutcome::NoStamp,
        },
    }
}

/// Read a child pipe to end on its own thread.
fn drain<R: Read + Send + 'static>(mut pipe: R) -> std::thread::JoinHandle<String> {
    std::thread::spawn(move || {
        let mut buf = Vec::new();
        let _ = pipe.read_to_end(&mut buf);
        String::from_utf8_lossy(&buf).into_owned()
    })
}

/// The environment keys the child must not inherit.
///
/// The child inherits our exports, and this process may well have been
/// started *by* an activated shell — an inherited stamp would make
/// every probe from a live shell report success regardless of what the
/// spawned one did (spec §3.2).
pub fn scrubbed_keys(keys: impl Iterator<Item = String>) -> Vec<String> {
    keys.filter(|k| k.starts_with(SCRUB_PREFIX)).collect()
}

/// Kill the probed shell's whole process group.
///
/// The shell was spawned as its own group leader, so its pid is the
/// group id and a negative-pid signal reaches every process the rc
/// file started — the `exec`-into-a-multiplexer case, where killing
/// only the shell we can see would leave the real hang behind.
#[cfg(unix)]
fn kill_process_group(pid: u32) {
    // SAFETY: `kill` is a plain syscall wrapper with no memory
    // effects. A negative pid addresses the process group; the group
    // is one we created via `process_group(0)`, so we are not
    // signalling anything we did not spawn. A failure (the group
    // already exited) is nothing to handle.
    unsafe {
        libc::kill(-(pid as libc::pid_t), libc::SIGKILL);
    }
}

// ── Verdicts ────────────────────────────────────────────────────

/// Why a measured-broken hookup is broken (spec §3.3).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Diagnosis {
    /// The hook is not in the rc file the shell reads.
    HookAbsent { rc: String },
    /// The hook is there, but the shell never got to it — something
    /// earlier in the file is failing.
    HookNotReached { rc: String },
    /// The shell activated, but from an init script older than the one
    /// on disk. The hookup works; what it sources is stale.
    StaleScript { found: u64, expected: u64 },
    /// No rc file could be named (unsupported shell), so the scan has
    /// nothing to say. The hook line is all we can offer.
    Unknown,
}

/// The measured answer to "would a new shell activate dodot?"
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
    /// Measured ✓ — the spawned shell reported the current generation,
    /// from the dodot now running.
    Verified { generation: u64 },
    /// The shell activated, and from a *different* dodot than the one
    /// running. Measured, so it is the same finding
    /// [`ActivationState::VersionSkew`] names from evidence, arrived at
    /// the one way that cannot be talked out of it.
    VersionSkew {
        generation: u64,
        loaded: EvidenceVersion,
    },
    /// The shell ran and did not activate dodot.
    Broken { diagnosis: Diagnosis },
    /// The measurement itself failed. Degrade to configuration state.
    Unverified { reason: String },
}

impl Verdict {
    /// Fold one spawn's outcome into a verdict, using the static rc
    /// scan only where spec §2.2 allows it: to explain a failure.
    ///
    /// `running` is the version every measured stamp is judged against,
    /// through [`activation::is_skewed`] — the same rule
    /// [`activation::Evidence`] applies to the cheap signals, called
    /// rather than restated, so a probe cannot certify a hookup the
    /// footer would call skewed. Skew outranks the generation ladder
    /// for the same reason it does there: a current generation from
    /// the wrong dodot is not health, and a stale one from the wrong
    /// dodot is not fixed by opening a new shell.
    pub fn from_outcome(
        outcome: ProbeOutcome,
        reference: Option<u64>,
        running: &str,
        hook: Option<(HookPresence, String)>,
    ) -> Verdict {
        match outcome {
            ProbeOutcome::Stamp(stamp) if activation::is_skewed(Some(&stamp.version), running) => {
                Verdict::VersionSkew {
                    generation: stamp.generation,
                    loaded: stamp.version,
                }
            }
            ProbeOutcome::Stamp(stamp) => {
                let found = stamp.generation;
                match activation::classify_stamp(Some(found), reference) {
                    StampState::Current => Verdict::Verified { generation: found },
                    // Unreachable in practice — a new shell sources the
                    // script we just wrote — but a real answer beats
                    // rounding it up to "verified".
                    _ => Verdict::Broken {
                        diagnosis: Diagnosis::StaleScript {
                            found,
                            expected: reference.unwrap_or(found),
                        },
                    },
                }
            }
            ProbeOutcome::NoStamp => Verdict::Broken {
                diagnosis: match hook {
                    Some((presence, rc)) if presence.is_present() => {
                        Diagnosis::HookNotReached { rc }
                    }
                    Some((_, rc)) => Diagnosis::HookAbsent { rc },
                    None => Diagnosis::Unknown,
                },
            },
            ProbeOutcome::TimedOut => Verdict::Unverified {
                reason: "your shell did not finish starting up in time".into(),
            },
            ProbeOutcome::SpawnFailed(e) => Verdict::Unverified {
                reason: format!("could not run your shell ({e})"),
            },
        }
    }

    /// Render the verdict for `up` / `install` output.
    ///
    /// `evidence` is the footer the signal ladder alone produced,
    /// `evidence_line` the footer's second line re-read *after* the
    /// probe ran (the spawned shell updates the heartbeat, so the
    /// pre-probe reading is stale by the time there is a verdict), and
    /// `hook_line` the manual line to fall back on. A couldn't-verify
    /// verdict degrades to `evidence`, clearly labeled as
    /// configuration state rather than measured activation; the other
    /// two verdicts are measurements and take precedence over it —
    /// including over the stale-shell advice, which is the wrong
    /// answer for a hookup that just measured broken.
    ///
    /// A measured verdict says the same thing the evidence path says
    /// for the same state, in the same words — and reaches the state
    /// the same way. A spawn settles the generation ladder's rung with
    /// certainty and learns nothing about the two rules that override
    /// it, so the ladder's answer goes through the shared
    /// [`activation::refine`] before [`ActivationNotice::for_state`]
    /// renders it. Short-circuiting straight to `Healthy` is how the
    /// measured path used to report "dodot is sourced in new shells"
    /// for a deployment of no packs, contradicting the `status` run
    /// immediately after it.
    ///
    /// `script_has_contributions` is the input that rule needs; it is
    /// a property of the script on disk, which the spawn does not
    /// change. Only [`Verdict::Broken`] writes its own hint, because
    /// only it has something the evidence path cannot know — which of
    /// the [`Diagnosis`] shapes the failure took.
    pub fn notice(
        &self,
        evidence: Option<ActivationNotice>,
        evidence_line: &str,
        hook_line: &str,
        script_has_contributions: bool,
    ) -> Option<ActivationNotice> {
        match self {
            // One arm: a measured activation is the ladder's `Healthy`
            // rung, and which state that *is* depends on the same two
            // overrides the evidence path applies.
            Verdict::Verified { .. } | Verdict::VersionSkew { .. } => {
                let state = activation::refine(
                    ActivationState::Healthy,
                    matches!(self, Verdict::VersionSkew { .. }),
                    script_has_contributions,
                );
                Some(ActivationNotice::for_state(
                    state,
                    hook_line,
                    None,
                    evidence_line.into(),
                ))
            }
            Verdict::Broken { diagnosis } => Some(ActivationNotice {
                state: ActivationState::VerifiedBroken.as_str().into(),
                severity: "error".into(),
                message: activation::VERIFIED_BROKEN_MESSAGE.into(),
                evidence: evidence_line.into(),
                hint: Some(match diagnosis {
                    Diagnosis::HookAbsent { rc } => format!(
                        "The dodot hook is missing from {rc} — run `dodot install --write` to add it."
                    ),
                    Diagnosis::HookNotReached { rc } => format!(
                        "The dodot hook is in {rc} but was never reached — something earlier in \
                         that file is failing before it."
                    ),
                    Diagnosis::StaleScript { found, expected } => format!(
                        "Your shell sourced an older init script (generation {found}, current is \
                         {expected}) — check for a second dodot hook or a stale copy."
                    ),
                    Diagnosis::Unknown => format!(
                        "dodot could not tell which rc file your shell reads. Add this line to it: \
                         {hook_line}"
                    ),
                }),
            }),
            Verdict::Unverified { reason } => {
                let mut notice = evidence?;
                notice.hint = Some(match notice.hint.take() {
                    Some(hint) => format!(
                        "{hint} (dodot could not verify by running your shell — {reason} — so this \
                         reports your configuration, not measured activation.)"
                    ),
                    None => format!(
                        "dodot could not verify by running your shell — {reason} — so this reports \
                         your configuration, not measured activation."
                    ),
                });
                Some(notice)
            }
        }
    }
}

// ── The measured path ───────────────────────────────────────────

/// Run the probe and turn it into a notice, doing the rc scan for the
/// diagnosis.
///
/// `reference` is the generation a shell started now would pick up
/// (the script on disk), and `evidence` the signals-only notice this
/// replaces when the measurement succeeds. `rc_override` names the
/// file the diagnosis should talk about when the caller already knows
/// it (`dodot install --rc`), instead of re-walking the ladder.
pub fn measure(
    fs: &dyn Fs,
    paths: &dyn Pather,
    timeout: Duration,
    shell_env: &ShellEnv,
    rc_override: Option<&Path>,
    reference: Option<u64>,
    evidence: Option<ActivationNotice>,
) -> Option<ActivationNotice> {
    let hook_line = activation::hook_line(&paths.init_script_path(), paths.home_dir());
    let stale_line = evidence
        .as_ref()
        .map(|n| n.evidence.clone())
        .unwrap_or_else(|| "Never loaded.".into());
    // Read once, before the spawn: the probe runs the user's rc, not
    // `dodot up`, so the script it sources is the same file afterwards.
    let has_contributions = activation::read_script(fs, paths)
        .is_some_and(|script| crate::shell::script_has_contributions(&script));
    let Some(shell) = shell_env.shell.as_deref().map(Path::new) else {
        return Verdict::Unverified {
            reason: "$SHELL is not set".into(),
        }
        .notice(evidence, &stale_line, &hook_line, has_contributions);
    };

    eprintln!("{}", announcement(shell));
    let outcome = run(shell, timeout);
    let hook = rc::scan_expected_rc(fs, paths.home_dir(), shell_env, rc_override);
    // Line two is re-read now, not before the spawn: a shell that
    // activated wrote the heartbeat on its way through, and "last
    // loaded 9 days ago" under a verdict that just watched it load
    // would contradict itself. A shell that did *not* activate left
    // the heartbeat alone, so the same read still reports the last
    // time one did — which is the evidence the broken verdict wants.
    let evidence_line =
        activation::Evidence::collect(fs, paths, activation::EnvStamp::default(), reference, false)
            .map(|e| e.evidence_line())
            .unwrap_or(stale_line);
    Verdict::from_outcome(outcome, reference, activation::running_version(), hook).notice(
        evidence,
        &evidence_line,
        &hook_line,
        has_contributions,
    )
}

/// Evaluate shell activation for a command that is allowed to measure.
///
/// Evidence first, always: [`gate_says_probe`] has to agree before a
/// shell is spawned, so the steady-state cost of this call on a
/// healthy machine is the two signal reads it would have done anyway.
///
/// `reference_for_gate` is the generation the *evidence* is judged
/// against (for `up`, the pre-regeneration one — see
/// `commands::shell_hookup_footer`), while the probe is judged against
/// the script on disk, which is what a shell started now would source.
///
/// `tty` is the session evidence the stampless ladder falls back on
/// (#279), and callers pass it **as it is** — whether it gets used is
/// this function's decision, not theirs.
///
/// It is consulted only when no measurement happens, because a spawn
/// answers the same question better. But "may this caller spawn" and
/// "did a spawn happen" are different facts, and only the second one
/// licences dropping the session signal: [`gate_says_probe`] declines
/// whenever the heartbeat is `Fresh`, which is *precisely* the case
/// #279 introduced the session signal to overrule — some other shell
/// activated, this one demonstrably did not. Deciding from the policy
/// instead let `up` print "dodot is sourced in new shells" in a session
/// that had not loaded dodot, while `status` in the same terminal
/// correctly said it had not, neither of them having spawned anything.
/// So the gate runs first and its answer, not the policy's permission,
/// is what suppresses the signal.
pub fn notice_with_probe(
    fs: &dyn Fs,
    paths: &dyn Pather,
    policy: &ProbePolicy,
    shell_env: &ShellEnv,
    env_stamp: &activation::EnvStamp,
    reference_for_gate: Option<u64>,
    tty: bool,
) -> Option<ActivationNotice> {
    // Nothing deployed means there is no hookup to measure yet, so the
    // script's existence is part of the same question.
    let timeout = policy
        .timeout()
        .filter(|_| fs.exists(&paths.init_script_path()))
        .filter(|_| {
            gate_says_probe(
                activation::classify_stamp(env_stamp.generation, reference_for_gate),
                activation::classify_heartbeat(
                    activation::read_heartbeat(fs, paths).map(|h| h.generation),
                    reference_for_gate,
                ),
            )
        });
    let evidence = activation::notice_for(
        fs,
        paths,
        env_stamp.clone(),
        reference_for_gate,
        tty && timeout.is_none(),
        shell_env,
    );
    let Some(timeout) = timeout else {
        return evidence;
    };
    let reference = activation::read_script_generation(fs, paths);
    measure(fs, paths, timeout, shell_env, None, reference, evidence)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_gate_fires_only_when_both_cheap_signals_are_inconclusive() {
        use HeartbeatState as H;
        use StampState as S;
        let matrix = [
            // A live shell is proof; never probe.
            (S::Current, H::Absent, false),
            (S::Current, H::Fresh, false),
            (S::Current, H::Old, false),
            // Some shell activated since the last regeneration; proof
            // enough, whatever this process inherited.
            (S::Absent, H::Fresh, false),
            (S::Stale, H::Fresh, false),
            // Fresh install: nothing has ever activated.
            (S::Absent, H::Absent, true),
            // Previously working, now nothing since the regeneration —
            // the broken-hook case the probe exists for.
            (S::Absent, H::Old, true),
            (S::Stale, H::Old, true),
            (S::Stale, H::Absent, true),
        ];
        for (stamp, heartbeat, expected) in matrix {
            assert_eq!(
                gate_says_probe(stamp, heartbeat),
                expected,
                "stamp={stamp:?} heartbeat={heartbeat:?}"
            );
        }
    }

    /// A stamp for `generation` from `version`, the shape a probed
    /// shell running the current dodot reports.
    fn stamp(generation: u64, version: &str) -> ProbeStamp {
        ProbeStamp {
            generation,
            version: EvidenceVersion::Known(version.into()),
        }
    }

    #[test]
    fn the_stamp_is_read_out_of_arbitrary_rc_noise() {
        let noisy = format!(
            "Welcome to your shell!\n[oh-my-zsh] update available\n{PROBE_MARKER}1755200000|5.6.0\n"
        );
        assert_eq!(
            parse_probe_output(&noisy),
            Some(stamp(1_755_200_000, "5.6.0"))
        );
        // A shell that sourced a pre-RCS01 script reports a generation
        // and an empty version — bounded, not unknown, exactly as the
        // heartbeat's version-less shape reads.
        assert_eq!(
            parse_probe_output(&format!("{PROBE_MARKER}1755200000|\n")),
            Some(ProbeStamp {
                generation: 1_755_200_000,
                version: EvidenceVersion::PreVersion,
            })
        );
        // No stamp exported: the marker is there, both fields empty.
        assert_eq!(parse_probe_output(&format!("{PROBE_MARKER}|\n")), None);
        // A version with no generation is not evidence a shell loaded
        // anything, the same rule the heartbeat is held to.
        assert_eq!(parse_probe_output(&format!("{PROBE_MARKER}|5.6.0\n")), None);
        assert_eq!(parse_probe_output("nothing at all\n"), None);
    }

    #[test]
    fn only_the_init_stamp_family_is_scrubbed() {
        let keys = [
            "DODOT_INIT_GEN",
            "DODOT_INIT_ANYTHING",
            "DODOT_DATA_DIR",
            "PATH",
            "HOME",
        ]
        .into_iter()
        .map(String::from);
        assert_eq!(
            scrubbed_keys(keys),
            vec!["DODOT_INIT_GEN".to_string(), "DODOT_INIT_ANYTHING".into()]
        );
    }

    #[test]
    fn the_announcement_names_the_shell_being_run() {
        assert_eq!(
            announcement(Path::new("/bin/zsh")),
            "verifying shell integration (zsh)…"
        );
    }

    // ── Verdicts ────────────────────────────────────────────────

    fn hook(presence: HookPresence) -> Option<(HookPresence, String)> {
        Some((presence, "~/.zshrc".to_string()))
    }

    /// The version every verdict test judges its measured stamp
    /// against — a fixed string rather than [`activation::running_version`],
    /// so the assertions do not move with the crate's own release.
    const RUNNING: &str = "5.6.0";

    /// `script_has_contributions` for a machine with packs deployed —
    /// the ordinary case, and the one the verdict tests below are not
    /// about. The empty case has a test of its own.
    const DEPLOYED: bool = true;

    #[test]
    fn a_current_stamp_is_a_measured_verification() {
        let v = Verdict::from_outcome(
            ProbeOutcome::Stamp(stamp(100, RUNNING)),
            Some(100),
            RUNNING,
            hook(HookPresence::ManagedBlock),
        );
        assert_eq!(v, Verdict::Verified { generation: 100 });
        let notice = v
            .notice(
                None,
                "Last loaded just now by dodot 5.6.0.",
                "HOOK",
                DEPLOYED,
            )
            .unwrap();
        assert_eq!(notice.state, "healthy");
        assert_eq!(notice.severity, "ok");
        // A measurement reports the healthy state in the state's own
        // words: what the spawn buys is that the claim is right, not a
        // second phrasing of it for the docs to keep in sync.
        assert_eq!(notice.message, activation::HEALTHY_MESSAGE);
        assert_eq!(notice.evidence, "Last loaded just now by dodot 5.6.0.");
    }

    /// The false positive this probe was rebuilt to stop reporting: a
    /// hand-wired hook resolves to some other dodot, that dodot's init
    /// script mints a perfectly current generation, and a
    /// generation-only probe converts it into a green "sourced in new
    /// shells". Both shapes skew — a named older version, and the
    /// version-less script every pre-RCS01 dodot generates.
    #[test]
    fn a_current_generation_from_another_dodot_is_skew_not_health() {
        for loaded in [
            EvidenceVersion::Known("5.0.0".into()),
            EvidenceVersion::PreVersion,
        ] {
            let v = Verdict::from_outcome(
                ProbeOutcome::Stamp(ProbeStamp {
                    generation: 100,
                    version: loaded.clone(),
                }),
                Some(100),
                RUNNING,
                hook(HookPresence::Manual),
            );
            assert_eq!(
                v,
                Verdict::VersionSkew {
                    generation: 100,
                    loaded: loaded.clone()
                },
                "a current generation from {loaded} is not a verification"
            );
            let notice = v
                .notice(
                    None,
                    "Last loaded just now by dodot 5.0.0.",
                    "HOOK",
                    DEPLOYED,
                )
                .unwrap();
            // The state the evidence path would name, in the evidence
            // path's own words — the measurement changes which state is
            // reported, never how a state reads.
            assert_eq!(notice.state, "version-skew");
            assert_eq!(notice.severity, "warning");
            assert_eq!(
                notice.message,
                "Shell hookup: your shells load a different dodot."
            );
            assert!(notice.hint.unwrap().contains("PATH finds first"));
        }
    }

    /// A measurement settles which rung of the generation ladder the
    /// hookup is on. It says nothing about whether the script that
    /// shell sourced deploys anything, so the measured path has to run
    /// its answer through the same [`activation::refine`] the evidence
    /// path does. Short-circuiting to `Healthy` had `up` say "dodot is
    /// sourced in new shells" on a fresh install with no packs, with
    /// `status` contradicting it a second later.
    #[test]
    fn a_measured_activation_of_an_empty_script_is_not_reported_healthy() {
        let v = Verdict::from_outcome(
            ProbeOutcome::Stamp(stamp(100, RUNNING)),
            Some(100),
            RUNNING,
            hook(HookPresence::ManagedBlock),
        );
        assert_eq!(v, Verdict::Verified { generation: 100 });

        let deployed = v
            .notice(None, "Last loaded just now.", "HOOK", DEPLOYED)
            .unwrap();
        assert_eq!(deployed.state, "healthy");

        let empty = v
            .notice(None, "Last loaded just now.", "HOOK", false)
            .unwrap();
        assert_eq!(
            empty.state, "empty-script",
            "the spawn proved the hookup fires; it proved nothing about what it deploys"
        );
        // The evidence path's words for the state, not a second set.
        assert_eq!(
            empty.message,
            "Shell hookup: wired, but no packs are deployed."
        );
    }

    /// Skew outranks the empty-script rule for the measured path too —
    /// the order is [`activation::refine`]'s, applied once, not
    /// re-decided here.
    #[test]
    fn a_measured_skew_outranks_an_empty_script() {
        let v = Verdict::VersionSkew {
            generation: 100,
            loaded: EvidenceVersion::Known("5.0.0".into()),
        };
        let notice = v
            .notice(None, "Last loaded just now.", "HOOK", false)
            .unwrap();
        assert_eq!(notice.state, "version-skew");
    }

    /// Skew outranks the generation ladder in both directions, exactly
    /// as [`activation::Evidence::state`] applies it: a *stale*
    /// generation from the wrong dodot is still skew, because "open a
    /// new shell" is not the fix.
    #[test]
    fn skew_outranks_a_stale_generation_the_way_the_evidence_path_does() {
        let v = Verdict::from_outcome(
            ProbeOutcome::Stamp(stamp(90, "5.0.0")),
            Some(100),
            RUNNING,
            hook(HookPresence::ManagedBlock),
        );
        assert_eq!(
            v,
            Verdict::VersionSkew {
                generation: 90,
                loaded: EvidenceVersion::Known("5.0.0".into())
            }
        );
    }

    /// The bound release cannot tell its own version-less evidence from
    /// an older dodot's, so it claims no skew — one rule
    /// ([`activation::EvidenceVersion::is`]), applied here by calling
    /// it rather than by restating it.
    #[test]
    fn the_bound_release_does_not_claim_skew_on_a_version_less_stamp() {
        let v = Verdict::from_outcome(
            ProbeOutcome::Stamp(ProbeStamp {
                generation: 100,
                version: EvidenceVersion::PreVersion,
            }),
            Some(100),
            activation::PRE_VERSION_RELEASE,
            hook(HookPresence::ManagedBlock),
        );
        assert_eq!(v, Verdict::Verified { generation: 100 });
    }

    #[test]
    fn no_stamp_plus_no_hook_names_the_file_and_the_command() {
        let v = Verdict::from_outcome(
            ProbeOutcome::NoStamp,
            Some(100),
            RUNNING,
            hook(HookPresence::Absent),
        );
        assert_eq!(
            v,
            Verdict::Broken {
                diagnosis: Diagnosis::HookAbsent {
                    rc: "~/.zshrc".into()
                }
            }
        );
        let notice = v.notice(None, "Never loaded.", "HOOK", DEPLOYED).unwrap();
        assert_eq!(notice.state, "verified-broken");
        assert_eq!(notice.severity, "error");
        let hint = notice.hint.unwrap();
        assert!(hint.contains("~/.zshrc"), "{hint}");
        assert!(hint.contains("dodot install --write"), "{hint}");
    }

    #[test]
    fn no_stamp_with_the_hook_present_blames_the_rc_file_instead() {
        for presence in [HookPresence::ManagedBlock, HookPresence::Manual] {
            let v =
                Verdict::from_outcome(ProbeOutcome::NoStamp, Some(100), RUNNING, hook(presence));
            let hint = v
                .notice(None, "Never loaded.", "HOOK", DEPLOYED)
                .unwrap()
                .hint
                .unwrap();
            assert!(
                hint.contains("never reached"),
                "{presence:?} should diagnose a broken rc, not a missing hook: {hint}"
            );
            assert!(
                !hint.contains("dodot install --write"),
                "adding the hook again fixes nothing here: {hint}"
            );
        }
    }

    #[test]
    fn an_unknown_shell_falls_back_to_the_hook_line() {
        let v = Verdict::from_outcome(ProbeOutcome::NoStamp, Some(100), RUNNING, None);
        assert_eq!(
            v,
            Verdict::Broken {
                diagnosis: Diagnosis::Unknown
            }
        );
        let hint = v
            .notice(None, "Never loaded.", "THE-HOOK-LINE", DEPLOYED)
            .unwrap()
            .hint
            .unwrap();
        assert!(hint.contains("THE-HOOK-LINE"), "{hint}");
    }

    #[test]
    fn a_stale_sourced_script_is_reported_as_such() {
        let v = Verdict::from_outcome(
            ProbeOutcome::Stamp(stamp(90, RUNNING)),
            Some(100),
            RUNNING,
            hook(HookPresence::ManagedBlock),
        );
        assert_eq!(
            v,
            Verdict::Broken {
                diagnosis: Diagnosis::StaleScript {
                    found: 90,
                    expected: 100
                }
            }
        );
    }

    #[test]
    fn a_failed_measurement_degrades_to_the_evidence_notice() {
        let evidence = ActivationNotice {
            state: "never-activated".into(),
            severity: "warning".into(),
            message: "Shell hookup: no shell has loaded dodot yet.".into(),
            hint: Some("Add this to your rc file: HOOK".into()),
            evidence: "Never loaded.".into(),
        };
        for outcome in [
            ProbeOutcome::TimedOut,
            ProbeOutcome::SpawnFailed("no such file".into()),
        ] {
            let v = Verdict::from_outcome(outcome, Some(100), RUNNING, hook(HookPresence::Absent));
            let notice = v
                .notice(Some(evidence.clone()), "Never loaded.", "HOOK", DEPLOYED)
                .unwrap();
            // The evidence verdict survives untouched...
            assert_eq!(notice.state, "never-activated");
            assert_eq!(notice.severity, "warning");
            // ...but is labeled as configuration, not measurement.
            let hint = notice.hint.unwrap();
            assert!(hint.starts_with("Add this to your rc file: HOOK"), "{hint}");
            assert!(hint.contains("could not verify"), "{hint}");
            assert!(hint.contains("not measured activation"), "{hint}");
        }
    }

    #[test]
    fn a_failed_measurement_with_nothing_to_degrade_to_stays_silent() {
        // Healthy-and-quiet evidence plus an unrunnable shell is not a
        // reason to invent a warning.
        let v = Verdict::Unverified {
            reason: "boom".into(),
        };
        assert_eq!(v.notice(None, "Never loaded.", "HOOK", DEPLOYED), None);
    }

    // ── Spawn mechanics, against fabricated shells ──────────────
    //
    // Every test below runs a shell script this file wrote into a
    // temp dir. None of them can reach the developer's real `$SHELL`
    // or their real rc files — which is the whole point: the probe's
    // job is surviving hostile rc behaviour, and the only way to test
    // that is to fabricate the hostility.

    use crate::testing::TempEnvironment;
    use std::path::PathBuf;

    /// Write an executable fake `$SHELL`.
    ///
    /// It is invoked exactly as the real thing is — `<shell> -ic
    /// '<command>'` — so `$2` is the probe command, and `eval "$2"` is
    /// the fake's stand-in for "run the command after the rc file".
    /// What each fixture puts *before* that line is the rc behaviour
    /// under test.
    fn fake_shell(env: &TempEnvironment, name: &str, rc_behaviour: &str) -> PathBuf {
        let path = env.home.join(name);
        let script = format!("#!/bin/sh\n{rc_behaviour}\neval \"$2\"\n");
        env.fs
            .write_file_with_mode(&path, script.as_bytes(), 0o755)
            .unwrap();
        path
    }

    #[test]
    fn a_shell_that_activates_reports_both_halves_of_the_stamp() {
        let env = TempEnvironment::builder().build();
        let shell = fake_shell(
            &env,
            "activating-shell",
            &format!("export {INIT_GEN_ENV}=1755200000\nexport {INIT_VERSION_ENV}=5.6.0"),
        );
        assert_eq!(
            run(&shell, Duration::from_secs(10)),
            ProbeOutcome::Stamp(stamp(1_755_200_000, "5.6.0"))
        );
    }

    /// The epic's own failure, measured end to end: the hook resolves
    /// to a different dodot, whose init script exports a *current*
    /// generation — the shape that used to come back as a green
    /// "sourced in new shells". Both flavours of wrong binary: one that
    /// names its version, and a pre-RCS01 one that exports none.
    #[test]
    fn a_shell_activating_another_dodot_measures_as_skew() {
        for (name, exports, loaded) in [
            (
                "older-dodot-shell",
                format!("export {INIT_GEN_ENV}=1755200000\nexport {INIT_VERSION_ENV}=5.0.0"),
                EvidenceVersion::Known("5.0.0".into()),
            ),
            (
                "pre-version-dodot-shell",
                format!("export {INIT_GEN_ENV}=1755200000"),
                EvidenceVersion::PreVersion,
            ),
        ] {
            let env = TempEnvironment::builder().build();
            let shell = fake_shell(&env, name, &exports);
            let outcome = run(&shell, Duration::from_secs(10));
            assert_eq!(
                outcome,
                ProbeOutcome::Stamp(ProbeStamp {
                    generation: 1_755_200_000,
                    version: loaded.clone(),
                }),
                "{name}"
            );
            let verdict = Verdict::from_outcome(
                outcome,
                Some(1_755_200_000),
                RUNNING,
                hook(HookPresence::Manual),
            );
            assert_eq!(
                verdict,
                Verdict::VersionSkew {
                    generation: 1_755_200_000,
                    loaded
                },
                "{name}: a fresh generation from the wrong dodot is not a verification"
            );
        }
    }

    #[test]
    fn a_shell_with_no_hook_reports_no_stamp() {
        let env = TempEnvironment::builder().build();
        let shell = fake_shell(&env, "bare-shell", "echo 'welcome to your shell'");
        assert_eq!(run(&shell, Duration::from_secs(10)), ProbeOutcome::NoStamp);
    }

    #[test]
    fn rc_noise_and_a_nonzero_exit_do_not_fail_a_successful_probe() {
        // Unrelated rc breakage is loud and irrelevant: the shell
        // still sourced dodot, so the probe still says verified.
        let env = TempEnvironment::builder().build();
        let path = env.home.join("noisy-shell");
        let script = format!(
            "#!/bin/sh\n\
             echo 'error: some unrelated rc line failed' >&2\n\
             echo 'p10k wants your attention'\n\
             export {INIT_GEN_ENV}=42\n\
             export {INIT_VERSION_ENV}=5.6.0\n\
             eval \"$2\"\n\
             exit 3\n"
        );
        env.fs
            .write_file_with_mode(&path, script.as_bytes(), 0o755)
            .unwrap();
        assert_eq!(
            run(&path, Duration::from_secs(10)),
            ProbeOutcome::Stamp(stamp(42, "5.6.0"))
        );
    }

    #[test]
    fn a_hanging_rc_times_out_and_takes_its_children_with_it() {
        let env = TempEnvironment::builder().build();
        let pidfile = env.home.join("grandchild.pid");
        // A shell that hangs *and* leaves a background process behind
        // — the `exec`-into-a-multiplexer shape. Killing only the
        // shell we can see would leave that process running forever.
        let path = env.home.join("hanging-shell");
        let script = format!(
            "#!/bin/sh\nsh -c 'echo $$ > {pid}; sleep 300' &\nsleep 300\n",
            pid = pidfile.display()
        );
        env.fs
            .write_file_with_mode(&path, script.as_bytes(), 0o755)
            .unwrap();

        let start = Instant::now();
        let outcome = run(&path, Duration::from_millis(500));
        assert_eq!(outcome, ProbeOutcome::TimedOut);
        assert!(
            start.elapsed() < Duration::from_secs(30),
            "the timeout must not wait out the rc file: {:?}",
            start.elapsed()
        );

        let pid: i32 = wait_for_pidfile(&env, &pidfile);
        assert!(
            wait_until_dead(pid),
            "pid {pid} survived the timeout: the process *group* was not killed"
        );
    }

    /// Read the grandchild's pid, giving the fake shell a moment to
    /// have written it.
    fn wait_for_pidfile(env: &TempEnvironment, pidfile: &Path) -> i32 {
        for _ in 0..100 {
            if let Ok(text) = env.fs.read_to_string(pidfile) {
                if let Ok(pid) = text.trim().parse() {
                    return pid;
                }
            }
            std::thread::sleep(Duration::from_millis(20));
        }
        panic!("the fake shell never recorded its background child's pid");
    }

    /// Poll `kill(pid, 0)` until the process is gone. Reparenting to
    /// init reaps it, so this converges quickly — but not instantly,
    /// which is why it polls instead of asserting once.
    fn wait_until_dead(pid: i32) -> bool {
        for _ in 0..100 {
            // SAFETY: signal 0 sends nothing; it only asks whether the
            // pid can be signalled, which is the liveness check here.
            let alive = unsafe { libc::kill(pid, 0) } == 0;
            if !alive {
                return true;
            }
            std::thread::sleep(Duration::from_millis(20));
        }
        false
    }

    #[test]
    fn an_inherited_stamp_is_scrubbed_before_the_child_sees_it() {
        // The probe often runs *from* a live shell, which exports the
        // stamp. Without scrubbing, a totally unhooked shell would
        // still hand it back and every probe would report success.
        let env = TempEnvironment::builder().build();
        let _guard = crate::testing::EnvVarGuard::set(INIT_GEN_ENV, "999999");
        let shell = fake_shell(&env, "inheriting-shell", "# sources nothing");
        assert_eq!(
            run(&shell, Duration::from_secs(10)),
            ProbeOutcome::NoStamp,
            "an inherited stamp must not count as this shell's activation"
        );
    }

    #[test]
    fn a_shell_that_cannot_be_run_is_a_couldnt_verify_not_a_panic() {
        let env = TempEnvironment::builder().build();
        let missing = env.home.join("no-such-shell");
        assert!(matches!(
            run(&missing, Duration::from_secs(5)),
            ProbeOutcome::SpawnFailed(_)
        ));
    }
}