varve-core 0.47.0

Layer manifests, resolution, the core store, and verification wiring for varve
Documentation
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
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
//! What a refused shim can still tell you (REQ-SHIMFALLBACK-001, varve#273).
//!
//! A shim asked for a tool the pinned layer does not carry refuses. By default
//! it never runs an ambient binary: that is the mixed-toolchain hazard varve
//! exists to close, and REQ-SHADOW-001 reports exactly that shadowing as a
//! defect. The one exception is a USER-level opt-in (REQ-PASSTHROUGH-001,
//! further down, decided 2026-11-10 after varve#273); without it, the refusal
//! below is exactly what happens. But a
//! bare refusal leaves the person with a tool installed locally and no way to
//! use it that they can see. So the refusal LISTS the options and runs none:
//! the executable on PATH (with the command that runs it directly, outside
//! varve), and every installed layer that carries the tool (with the pin
//! change that would select it).
//!
//! Everything here is a pure read. Nothing executes, nothing is installed, and
//! no pin is written.

use std::ffi::OsStr;
use std::path::{Path, PathBuf};

use crate::pin::Channel;
use crate::store::Store;

/// Every executable named `tool` on `path_var`, in PATH order, as a shell
/// would find them — except that `shim_dir` is skipped. The shim directory
/// holds a link to varve under this very name, so without the exclusion the
/// refusal would offer the shim as the way around itself.
///
/// An entry is skipped when it canonicalizes to the shim directory, so a
/// symlinked or `..`-spelled route to it does not slip through. The same
/// executable reached through two PATH entries is listed once.
pub fn on_path(path_var: Option<&OsStr>, tool: &str, shim_dir: &Path) -> Vec<PathBuf> {
    search_path(path_var, tool, shim_dir, None)
}

/// [`on_path`], optionally looking at absolute entries only (`Some(cwd)`), and
/// then not at those inside a repository above `cwd` either. The filter has to
/// run BEFORE the de-duplication: otherwise a relative spelling of a directory
/// listed ahead of its absolute one would swallow it.
fn search_path(
    path_var: Option<&OsStr>,
    tool: &str,
    shim_dir: &Path,
    absolute_only: Option<&Path>,
) -> Vec<PathBuf> {
    if tool.is_empty() || tool.contains('/') || tool.contains('\\') {
        return Vec::new();
    }
    let Some(path_var) = path_var else {
        return Vec::new();
    };
    let shim_canon = std::fs::canonicalize(shim_dir).ok();
    let repos = absolute_only.map(repository_roots).unwrap_or_default();
    let mut out: Vec<PathBuf> = Vec::new();
    let mut seen: Vec<PathBuf> = Vec::new();
    for dir in std::env::split_paths(path_var) {
        if absolute_only.is_some() && !dir.is_absolute() {
            continue;
        }
        let dir = if dir.as_os_str().is_empty() {
            PathBuf::from(".")
        } else {
            dir
        };
        let dir_canon = std::fs::canonicalize(&dir).ok();
        if dir == shim_dir || (dir_canon.is_some() && dir_canon == shim_canon) {
            continue;
        }
        // direnv's `PATH_add bin`: an absolute entry that is the repository's
        // own, however spelt (symlinks and `..` resolved).
        if dir_canon
            .as_deref()
            .is_some_and(|d| repos.iter().any(|r| d.starts_with(r)))
        {
            continue;
        }
        let candidate = dir.join(tool);
        if !crate::shadow::is_executable_file(&candidate) {
            continue;
        }
        let key = std::fs::canonicalize(&candidate).unwrap_or_else(|_| candidate.clone());
        if seen.contains(&key) {
            continue;
        }
        seen.push(key);
        out.push(candidate);
    }
    out
}

/// One installed layer that carries the tool.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Carrier {
    /// The realm partition's fingerprint, `None` for the top-level store.
    pub partition: Option<String>,
    /// Whether this is the partition the project's pin resolves in. When it
    /// is not, selecting the layer also means changing realm.
    pub in_pin_partition: bool,
    pub layer: String,
    pub channel: String,
    pub digest: String,
}

/// Every installed layer, in any partition under the varve root, whose
/// dispatchable `bin/` carries `tool`. `exclude_digest` is the layer the pin
/// already resolves (it was just found not to carry it). Sorted by layer,
/// then partition, then digest, so the output is stable run to run.
pub fn carriers(store: &Store, tool: &str, exclude_digest: &str) -> Vec<Carrier> {
    let mut out = Vec::new();
    for (partition, part) in store.partitions() {
        let Ok(layers) = part.list() else { continue };
        for layer in layers {
            if layer.digest == exclude_digest || part.tool_path(&layer, tool).is_none() {
                continue;
            }
            out.push(Carrier {
                in_pin_partition: part.root() == store.root(),
                partition: partition.clone(),
                layer: layer.layer.to_string(),
                channel: layer.channel.clone(),
                digest: layer.digest.clone(),
            });
        }
    }
    out.sort_by(|a, b| {
        (&a.layer, &a.partition, &a.digest).cmp(&(&b.layer, &b.partition, &b.digest))
    });
    out
}

/// The lines to put in `varve.toml` to select `c`, given the current pin.
fn pin_change(c: &Carrier, pin_channel: Channel, pin_realm: Option<&str>) -> String {
    let mut lines = vec![format!("layer = \"{}\"", c.layer)];
    if !c.channel.is_empty() && c.channel != pin_channel.as_str() {
        lines.push(format!("channel = \"{}\"", c.channel));
    }
    if !c.in_pin_partition {
        lines.push(match (&c.partition, pin_realm) {
            (Some(fp), _) => format!(
                "realm = <the realm whose trust-root fingerprint is {fp}> (this layer is \
                 installed under another realm)"
            ),
            (None, Some(r)) => format!(
                "remove the `realm = \"{r}\"` line (this layer is installed outside any realm)"
            ),
            (None, None) => String::new(),
        });
    }
    lines.retain(|l| !l.is_empty());
    lines.join("; ")
}

/// The refusal's second half: what the person can do instead. Never empty —
/// when there is nothing to offer, that is said outright rather than left as
/// two blank headings.
pub fn describe(
    tool: &str,
    args_quoted: &str,
    pin_file: &Path,
    on_path: &[PathBuf],
    carriers: &[Carrier],
    pin_channel: Channel,
    pin_realm: Option<&str>,
) -> String {
    let mut s = String::from("varve ran nothing. ");
    if on_path.is_empty() && carriers.is_empty() {
        s.push_str(&format!(
            "Nothing else provides '{tool}': no executable of that name is on PATH \
             (outside the shim directory) and no installed layer carries it."
        ));
        return s;
    }
    s.push_str("Options (varve will not pick one for you):");
    for p in on_path {
        let suffix = if args_quoted.is_empty() {
            String::new()
        } else {
            format!(" {args_quoted}")
        };
        s.push_str(&format!(
            "\n  - '{tool}' is on PATH at {} — it is NOT part of the pinned layer. Run it \
             directly, outside the layer: {}{suffix}",
            p.display(),
            crate::shellquote::quote_sh(&p.to_string_lossy())
        ));
    }
    for c in carriers {
        s.push_str(&format!(
            "\n  - installed layer {} ({}) carries '{tool}'. To select it, set in {}: {}",
            c.layer,
            c.channel,
            pin_file.display(),
            pin_change(c, pin_channel, pin_realm)
        ));
    }
    s
}

// ---------------------------------------------------------------------------
// Passthrough (REQ-PASSTHROUGH-001, revising the decision above)
//
// The refusal above stays the default. A person may now say, in a file that
// belongs to THEM and not to any repository, that the shim for a tool the
// pinned layer does not carry may run the executable found on PATH. Four
// things keep that from reopening the hole REQ-SHADOW-001 closes:
//
//   * the grant lives outside every repository — a committed `varve.toml`
//     cannot carry it, and a file that is inside the repository is refused
//     even when an environment variable the repository controls points at it;
//   * a tool the layer CARRIES never reads this file at all (the caller only
//     asks after the layer has said it does not carry the tool);
//   * the search can never land on a shim — this one's or another root's;
//   * every use is announced on stderr, and every session that allowed it is
//     recorded where verify, exports and attestations can show it.
// ---------------------------------------------------------------------------

/// The user-level configuration, relative to the config home.
pub const USER_CONFIG_FILE: &str = "varve/config.toml";

/// Which tools a user's shims may pass through to PATH.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum Allow {
    /// No configuration, or one that lists nothing: the refusal stands.
    #[default]
    Nothing,
    /// `*`: any tool the layer does not carry.
    Everything,
    Tools(std::collections::BTreeSet<String>),
}

impl Allow {
    /// Whether the user's configuration names `tool` (or `*`). This is NOT
    /// the whole decision: the layer carrying the tool overrides it.
    pub fn permits(&self, tool: &str) -> bool {
        match self {
            Allow::Nothing => false,
            Allow::Everything => true,
            Allow::Tools(t) => t.contains(tool),
        }
    }

    /// What gets recorded in a stamp or a statement: `["*"]`, the sorted
    /// names, or nothing at all.
    pub fn recorded(&self) -> Vec<String> {
        match self {
            Allow::Nothing => Vec::new(),
            Allow::Everything => vec!["*".to_string()],
            Allow::Tools(t) => t.iter().cloned().collect(),
        }
    }
}

/// The text of `[shim] passthrough`, shared by every line that reports it.
pub fn describe_allow(recorded: &[String]) -> String {
    if recorded.iter().any(|t| t == "*") {
        "every tool the layer does not carry (`*`)".to_string()
    } else {
        recorded.join(", ")
    }
}

#[derive(serde::Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct UserConfig {
    #[serde(default)]
    shim: ShimSection,
}

#[derive(serde::Deserialize, Default)]
#[serde(deny_unknown_fields)]
struct ShimSection {
    #[serde(default)]
    passthrough: Vec<String>,
}

/// Parse the user configuration. Unknown keys are an error, not ignored: a
/// misspelt `passthru` that silently allowed nothing is a setting that looks
/// applied and is not.
pub fn parse_config(text: &str) -> Result<Allow, String> {
    let cfg: UserConfig = toml::from_str(text).map_err(|e| e.to_string())?;
    let mut tools = std::collections::BTreeSet::new();
    for name in cfg.shim.passthrough {
        if name == "*" {
            return Ok(Allow::Everything);
        }
        if name.is_empty() || name.contains('/') || name.contains('\\') {
            return Err(format!(
                "passthrough entry {name:?} is not a tool name (a bare name, or `*`)"
            ));
        }
        tools.insert(name);
    }
    Ok(if tools.is_empty() {
        Allow::Nothing
    } else {
        Allow::Tools(tools)
    })
}

/// Where the user configuration would be: `$XDG_CONFIG_HOME/varve/config.toml`
/// when that variable is an ABSOLUTE path (the XDG rule: a relative one is
/// invalid and ignored, and it would otherwise resolve against the working
/// directory, which is the repository), else `$HOME/.config/varve/config.toml`.
pub fn config_path(xdg: Option<&OsStr>, home: Option<&OsStr>) -> Option<PathBuf> {
    let base = match xdg.map(Path::new) {
        Some(x) if x.is_absolute() => x.to_path_buf(),
        _ => {
            let home = Path::new(home?);
            if !home.is_absolute() {
                return None;
            }
            home.join(".config")
        }
    };
    Some(base.join(USER_CONFIG_FILE))
}

/// What makes a directory a repository root: varve's own pin, and the marker
/// of each version-control system a project is likely to live in.
const REPOSITORY_MARKERS: [&str; 5] = ["varve.toml", ".git", ".hg", ".jj", ".svn"];

/// The repository root above `cwd` that `config` lies inside, if any: the
/// nearest ancestor holding a `varve.toml` or a version-control marker
/// (`.git`, `.hg`, `.jj`, `.svn`) that contains it.
/// Both sides are canonicalized, so a symlink (or a `..`) cannot launder a
/// repository file into a "user" one.
pub fn repository_holding(config: &Path, cwd: &Path) -> Option<PathBuf> {
    let config = std::fs::canonicalize(config).ok()?;
    repository_roots(cwd)
        .into_iter()
        .find(|dir| config.starts_with(dir))
}

/// Every ancestor of `cwd` (canonical, `cwd` itself included) that holds a
/// repository marker. Empty when `cwd` cannot be resolved.
fn repository_roots(cwd: &Path) -> Vec<PathBuf> {
    let Ok(cwd) = std::fs::canonicalize(cwd) else {
        return Vec::new();
    };
    cwd.ancestors()
        .filter(|dir| REPOSITORY_MARKERS.iter().any(|m| dir.join(m).exists()))
        .map(Path::to_path_buf)
        .collect()
}

/// Why the user configuration did not take effect.
#[derive(Debug, PartialEq, Eq)]
pub enum ConfigProblem {
    InRepository { config: PathBuf, repo: PathBuf },
    Unreadable { config: PathBuf, why: String },
    Invalid { config: PathBuf, why: String },
}

impl std::fmt::Display for ConfigProblem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConfigProblem::InRepository { config, repo } => write!(
                f,
                "the user configuration {} is inside the repository {}, so it is ignored: \
                 passthrough can only be enabled from a file outside every repository \
                 (a committed file would switch it on for everyone who clones)",
                config.display(),
                repo.display()
            ),
            ConfigProblem::Unreadable { config, why } => {
                write!(
                    f,
                    "cannot read the user configuration {}: {why}",
                    config.display()
                )
            }
            ConfigProblem::Invalid { config, why } => write!(
                f,
                "the user configuration {} is not valid, so passthrough is off: {why}",
                config.display()
            ),
        }
    }
}

/// A loaded user configuration: what it allows and the file that said so.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct UserPassthrough {
    pub allow: Allow,
    pub source: Option<PathBuf>,
}

/// Read the user configuration. No file is no passthrough; a file that is
/// inside the repository, unreadable or invalid is a [`ConfigProblem`] and
/// grants nothing.
pub fn load(
    xdg: Option<&OsStr>,
    home: Option<&OsStr>,
    cwd: &Path,
) -> Result<UserPassthrough, ConfigProblem> {
    let Some(config) = config_path(xdg, home) else {
        return Ok(UserPassthrough::default());
    };
    // The repository check comes BEFORE the read: a repository's file is
    // never even opened as configuration.
    if let Some(repo) = repository_holding(&config, cwd) {
        return Err(ConfigProblem::InRepository { config, repo });
    }
    let text = match std::fs::read_to_string(&config) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Ok(UserPassthrough::default());
        }
        Err(e) => {
            return Err(ConfigProblem::Unreadable {
                config,
                why: e.to_string(),
            });
        }
    };
    match parse_config(&text) {
        Ok(allow) => Ok(UserPassthrough {
            allow,
            source: Some(config),
        }),
        Err(why) => Err(ConfigProblem::Invalid { config, why }),
    }
}

/// Whether `candidate` is the varve binary itself (a shim is a link to it).
fn is_varve(candidate: &Path, self_exe: Option<&Path>) -> bool {
    let Some(me) = self_exe else { return false };
    match (std::fs::canonicalize(candidate), std::fs::canonicalize(me)) {
        (Ok(a), Ok(b)) => a == b,
        _ => false,
    }
}

/// The executable a passed-through shim would run: the first `tool` on PATH
/// that is neither inside `shim_dir` nor varve itself. Skipping only the shim
/// directory is not enough: another varve root's shim directory is a different
/// path to the same binary, and running it would dispatch back through varve.
pub fn ambient_binary(
    path_var: Option<&OsStr>,
    tool: &str,
    shim_dir: &Path,
    self_exe: Option<&Path>,
    cwd: &Path,
) -> Option<PathBuf> {
    // ABSOLUTE entries only. An empty entry means the working directory, and
    // so does `.` or any relative one — and the working directory is the
    // repository, which could plant a `ghost` for the user to run unknowingly.
    // An absolute entry inside a repository above `cwd` is skipped for the
    // same reason (the rule that refuses a repository's configuration).
    search_path(path_var, tool, shim_dir, Some(cwd))
        .into_iter()
        .find(|p| !is_varve(p, self_exe))
}

/// How many passthroughs of one tool a single chain of processes may make.
/// The landing check catches a passthrough that lands on varve itself; a
/// wrapper script in between hides that, so every chain is also bounded by
/// count. Legitimate nesting (a recursive `make`) is a handful of levels.
pub const MAX_PASSTHROUGH_HOPS: u32 = 64;

/// The key an entry of the hop counter is filed under: the name with every
/// control character escaped, so one name is exactly one line.
fn hop_key(tool: &str) -> String {
    tool.escape_default().to_string()
}

/// The entries of a hop-counter value: (count, key), unparsable lines dropped.
fn hop_entries(env: Option<&OsStr>) -> Vec<(u32, String)> {
    let text = env.map(|e| e.to_string_lossy().into_owned());
    text.as_deref()
        .unwrap_or("")
        .lines()
        .filter_map(|line| {
            let (n, key) = line.split_once(' ')?;
            Some((n.parse::<u32>().ok()?, key.to_string()))
        })
        .collect()
}

/// Passthroughs of `tool` already made by the chain that `env` (the value of
/// the hop-counter variable) describes.
pub fn hops(env: Option<&OsStr>, tool: &str) -> u32 {
    let key = hop_key(tool);
    hop_entries(env)
        .into_iter()
        .find(|(_, k)| *k == key)
        .map_or(0, |(n, _)| n)
}

/// The hop-counter value to hand to the next process: `env` with `tool`'s
/// count one higher. Other tools' counts are kept, so A -> B -> A -> B climbs.
pub fn with_hop(env: Option<&OsStr>, tool: &str) -> String {
    let key = hop_key(tool);
    let mut entries = hop_entries(env);
    match entries.iter_mut().find(|(_, k)| *k == key) {
        Some((n, _)) => *n = n.saturating_add(1),
        None => entries.push((1, key)),
    }
    entries
        .iter()
        .map(|(n, k)| format!("{n} {k}"))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Format and separator characters that are not `char::is_control` but still
/// reorder (bidi embeddings, overrides, isolates, marks) or split or hide
/// (zero-width, line and paragraph separators, the byte-order mark) displayed
/// text.
fn reorders_or_splits(c: char) -> bool {
    matches!(
        c,
        '\u{200b}'..='\u{200f}'
            | '\u{202a}'..='\u{202e}'
            | '\u{2028}'
            | '\u{2029}'
            | '\u{2066}'..='\u{2069}'
            | '\u{feff}'
            | '\u{061c}'
            | '\u{00ad}'
            | '\u{180e}'
            | '\u{2060}'..='\u{2064}'
            | '\u{fff9}'..='\u{fffb}'
            | '\u{e0000}'..='\u{e007f}'
    )
}

/// `text` with every control character (a newline above all) written as an
/// escape, so a path or a name cannot split a line it is printed in.
fn one_line(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        if c.is_control() || reorders_or_splits(c) {
            out.extend(c.escape_default());
        } else {
            out.push(c);
        }
    }
    out
}

/// The one stderr line a passed-through run prints (REQ-PASSTHROUGH-001
/// clause 3): the binary, and that it is not the layer's. Everything that
/// came from the environment is escaped so the line stays ONE line.
pub fn notice(tool: &str, binary: &Path, layer: &str, config: Option<&Path>) -> String {
    let by = match config {
        Some(c) => format!("allowed by {}", one_line(&c.display().to_string())),
        None => "allowed by your user configuration".to_string(),
    };
    format!(
        "varve: passthrough: '{}' is not part of layer {}; running {} outside the \
         layer (not verified by varve; {by})",
        one_line(tool),
        one_line(layer),
        one_line(&binary.display().to_string())
    )
}

/// One tool whose shim would currently pass through.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Active {
    pub tool: String,
    /// What it would run, or `None` when nothing on PATH answers to the name.
    pub binary: Option<PathBuf>,
}

/// The passthroughs in force: every allowed tool the layer does not carry.
/// Under `*` the candidates are the installed shims (there is no other finite
/// list), and only those that actually resolve to something are reported.
pub fn active(
    allow: &Allow,
    carried: &[String],
    shim_names: &[String],
    path_var: Option<&OsStr>,
    shim_dir: &Path,
    self_exe: Option<&Path>,
    cwd: &Path,
) -> Vec<Active> {
    // Folding is ASCII only: with a non-ASCII carried name nothing can be said
    // to be uncarried, and a non-ASCII candidate has no sound comparison. Both
    // fail closed, as the shim does.
    if carried.iter().any(|c| !c.is_ascii()) {
        return Vec::new();
    }
    let mut names: Vec<String> = match allow {
        Allow::Nothing => Vec::new(),
        Allow::Everything => shim_names.to_vec(),
        Allow::Tools(t) => t.iter().cloned().collect(),
    };
    names.sort();
    names.dedup();
    names
        .into_iter()
        .filter(|n| n.is_ascii() && !carried.iter().any(|c| c.eq_ignore_ascii_case(n)))
        .map(|tool| {
            let binary = ambient_binary(path_var, &tool, shim_dir, self_exe, cwd);
            Active { tool, binary }
        })
        .filter(|a| a.binary.is_some() || !matches!(allow, Allow::Everything))
        .collect()
}

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

    fn exe(dir: &Path, name: &str) -> PathBuf {
        let p = dir.join(name);
        std::fs::write(&p, "#!/bin/sh\n").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
        p
    }

    fn joined(dirs: &[&Path]) -> std::ffi::OsString {
        std::env::join_paths(dirs).unwrap()
    }

    fn carrier(layer: &str, channel: &str, in_pin: bool, partition: Option<&str>) -> Carrier {
        Carrier {
            partition: partition.map(str::to_string),
            in_pin_partition: in_pin,
            layer: layer.into(),
            channel: channel.into(),
            digest: format!("sha256:{layer}"),
        }
    }

    // rivet: verifies REQ-SHIMFALLBACK-001
    // rivet: verifies REQ-SHIMFALLBACK-001
    #[test]
    fn the_direct_command_survives_a_path_with_a_space() {
        let p = PathBuf::from("/opt/my tools/ghost");
        let s = describe(
            "ghost",
            "'--version'",
            Path::new("/p/varve.toml"),
            std::slice::from_ref(&p),
            &[],
            Channel::Rolling,
            None,
        );
        assert!(
            s.contains("outside the layer: '/opt/my tools/ghost' '--version'"),
            "the command must paste into a shell as one word: {s}"
        );
    }

    #[test]
    fn on_path_skips_the_shim_directory_however_it_is_spelled() {
        let shims = tempfile::tempdir().unwrap();
        let other = tempfile::tempdir().unwrap();
        exe(shims.path(), "ghost");
        let real = exe(other.path(), "ghost");
        let spelled = shims
            .path()
            .join("..")
            .join(shims.path().file_name().unwrap());
        let path = joined(&[&spelled, shims.path(), other.path()]);
        assert_eq!(on_path(Some(&path), "ghost", shims.path()), vec![real]);
    }

    // rivet: verifies REQ-SHIMFALLBACK-001
    #[test]
    fn on_path_lists_each_executable_once_in_path_order_and_skips_non_executables() {
        let shims = tempfile::tempdir().unwrap();
        let a = tempfile::tempdir().unwrap();
        let b = tempfile::tempdir().unwrap();
        let data = tempfile::tempdir().unwrap();
        std::fs::write(data.path().join("ghost"), "not executable").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(
                data.path().join("ghost"),
                std::fs::Permissions::from_mode(0o644),
            )
            .unwrap();
        }
        let first = exe(a.path(), "ghost");
        let second = exe(b.path(), "ghost");
        let path = joined(&[data.path(), a.path(), b.path(), a.path()]);
        assert_eq!(
            on_path(Some(&path), "ghost", shims.path()),
            vec![first, second]
        );
    }

    // rivet: verifies REQ-SHIMFALLBACK-001
    #[test]
    fn on_path_refuses_names_that_are_paths_or_empty_and_no_path() {
        let d = tempfile::tempdir().unwrap();
        exe(d.path(), "ghost");
        let path = joined(&[d.path()]);
        let none = tempfile::tempdir().unwrap();
        assert!(on_path(Some(&path), "", none.path()).is_empty());
        assert!(on_path(Some(&path), "./ghost", none.path()).is_empty());
        assert!(on_path(Some(&path), "a\\ghost", none.path()).is_empty());
        assert!(on_path(None, "ghost", none.path()).is_empty());
        assert_eq!(on_path(Some(&path), "ghost", none.path()).len(), 1);
    }

    // rivet: verifies REQ-SHIMFALLBACK-001
    #[test]
    fn describe_says_so_when_nothing_else_provides_the_tool() {
        let s = describe(
            "ghost",
            "",
            Path::new("/p/varve.toml"),
            &[],
            &[],
            Channel::Qualified,
            None,
        );
        assert!(s.contains("Nothing else provides 'ghost'"), "{s}");
        assert!(!s.contains("Options"), "{s}");
    }

    // rivet: verifies REQ-SHIMFALLBACK-001
    #[test]
    fn describe_gives_the_direct_command_with_its_arguments() {
        let s = describe(
            "ghost",
            "'--version'",
            Path::new("/p/varve.toml"),
            &[PathBuf::from("/opt/bin/ghost")],
            &[],
            Channel::Qualified,
            None,
        );
        assert!(s.contains("varve ran nothing"), "{s}");
        assert!(s.contains("'/opt/bin/ghost' '--version'"), "{s}");
        assert!(!s.contains("Nothing else"), "{s}");
        let bare = describe(
            "ghost",
            "",
            Path::new("/p/varve.toml"),
            &[PathBuf::from("/opt/bin/ghost")],
            &[],
            Channel::Qualified,
            None,
        );
        assert!(
            bare.ends_with("directly, outside the layer: '/opt/bin/ghost'"),
            "{bare}"
        );
    }

    // rivet: verifies REQ-SHIMFALLBACK-001
    #[test]
    fn pin_change_names_channel_and_realm_only_when_they_differ() {
        let same = carrier("2026.09.0", "qualified", true, None);
        assert_eq!(
            pin_change(&same, Channel::Qualified, None),
            "layer = \"2026.09.0\""
        );
        let chan = carrier("2026.09.0", "rolling", true, None);
        assert_eq!(
            pin_change(&chan, Channel::Qualified, None),
            "layer = \"2026.09.0\"; channel = \"rolling\""
        );
        let unlabelled = carrier("2026.09.0", "", true, None);
        assert_eq!(
            pin_change(&unlabelled, Channel::Rolling, None),
            "layer = \"2026.09.0\""
        );
        let realmless = carrier("2026.09.0", "qualified", false, None);
        let s = pin_change(&realmless, Channel::Qualified, Some("acme"));
        assert!(s.contains("remove the `realm = \"acme\"` line"), "{s}");
        let other = carrier("2026.09.0", "qualified", false, Some("ab12"));
        let s = pin_change(&other, Channel::Qualified, Some("acme"));
        assert!(s.contains("fingerprint is ab12"), "{s}");
        let s = pin_change(&other, Channel::Qualified, None);
        assert!(s.contains("fingerprint is ab12"), "{s}");
        // Not in the pin's partition, no realm on either side: nothing to say.
        let odd = carrier("2026.09.0", "qualified", false, None);
        assert_eq!(
            pin_change(&odd, Channel::Qualified, None),
            "layer = \"2026.09.0\""
        );
    }

    // rivet: verifies REQ-SHIMFALLBACK-001
    #[test]
    fn describe_lists_every_carrier_with_the_pin_line() {
        let s = describe(
            "ghost",
            "",
            Path::new("/p/varve.toml"),
            &[],
            &[
                carrier("2026.08.0", "qualified", true, None),
                carrier("2026.09.0", "rolling", true, None),
            ],
            Channel::Qualified,
            None,
        );
        assert!(
            s.contains("installed layer 2026.08.0 (qualified) carries 'ghost'"),
            "{s}"
        );
        assert!(
            s.contains("set in /p/varve.toml: layer = \"2026.08.0\"\n"),
            "{s}"
        );
        assert!(
            s.contains("layer = \"2026.09.0\"; channel = \"rolling\""),
            "{s}"
        );
        assert!(!s.contains("Nothing else"), "{s}");
        assert!(!s.contains("on PATH"), "{s}");
    }

    // rivet: verifies REQ-SHIMFALLBACK-001
    #[test]
    fn carriers_are_sorted_exclude_the_pinned_layer_and_span_partitions() {
        let tmp = tempfile::tempdir().unwrap();
        let store = Store::at(tmp.path());
        let manifest = |layer: &str, ch: &str| {
            format!(
                r#"{{"schemaVersion":2,"annotations":{{"eu.pulseengine.varve.layer":"{layer}","eu.pulseengine.varve.channel":"{ch}"}},"manifests":[]}}"#
            )
        };
        let late = store
            .lay_down(
                manifest("2026.09.0", "rolling").as_bytes(),
                &[("ghost", b"x")],
            )
            .unwrap();
        let early = store
            .lay_down(
                manifest("2026.08.0", "qualified").as_bytes(),
                &[("ghost", b"x")],
            )
            .unwrap();
        store
            .lay_down(
                manifest("2026.07.0", "qualified").as_bytes(),
                &[("other", b"x")],
            )
            .unwrap();
        let realm = Store::at(tmp.path().join("realms").join("ab12"));
        let in_realm = realm
            .lay_down(
                manifest("2026.06.0", "qualified").as_bytes(),
                &[("ghost", b"x")],
            )
            .unwrap();

        let got = carriers(&store, "ghost", "sha256:none");
        let layers: Vec<&str> = got.iter().map(|c| c.layer.as_str()).collect();
        assert_eq!(layers, ["2026.06.0", "2026.08.0", "2026.09.0"]);
        assert_eq!(got[0].digest, in_realm);
        assert_eq!(got[0].partition.as_deref(), Some("ab12"));
        assert!(!got[0].in_pin_partition);
        assert_eq!(got[1].digest, early);
        assert!(got[1].in_pin_partition && got[1].partition.is_none());
        assert_eq!(got[2].channel, "rolling");

        // From the realm partition's point of view the pin partition flips.
        let from_realm = carriers(&realm, "ghost", "sha256:none");
        let flags: Vec<(&str, bool)> = from_realm
            .iter()
            .map(|c| (c.layer.as_str(), c.in_pin_partition))
            .collect();
        assert_eq!(
            flags,
            [
                ("2026.06.0", true),
                ("2026.08.0", false),
                ("2026.09.0", false)
            ]
        );

        // The layer the pin already resolves is never offered back.
        let without = carriers(&store, "ghost", &late);
        assert_eq!(without.len(), 2);
        assert!(without.iter().all(|c| c.digest != late));
        assert!(carriers(&store, "nobody-has-this", "x").is_empty());
    }
}

#[cfg(test)]
mod passthrough_tests {

    // rivet: verifies REQ-PASSTHROUGH-001
    #[test]
    fn hops_are_counted_per_tool_and_survive_interleaving() {
        let os = |s: &str| std::ffi::OsString::from(s);
        assert_eq!(hops(None, "ghost"), 0);
        let one = with_hop(None, "ghost");
        assert_eq!(hops(Some(&os(&one)), "ghost"), 1);
        assert_eq!(hops(Some(&os(&one)), "other"), 0);
        // A -> B -> A -> B: each tool's count keeps climbing.
        let mut env = String::new();
        for _ in 0..3 {
            env = with_hop(Some(&os(&env)), "a");
            env = with_hop(Some(&os(&env)), "b");
        }
        assert_eq!(hops(Some(&os(&env)), "a"), 3);
        assert_eq!(hops(Some(&os(&env)), "b"), 3);
        assert_eq!(hops(Some(&os(&env)), "c"), 0);
        // A name that would split an entry is escaped, not parsed as two.
        let odd = with_hop(None, "x\n5 y");
        assert_eq!(hops(Some(&os(&odd)), "x\n5 y"), 1);
        assert_eq!(hops(Some(&os(&odd)), "y"), 0);
        // Garbage is ignored, not trusted and not fatal.
        assert_eq!(hops(Some(&os("junk\n\n-3 ghost\nx ghost")), "ghost"), 0);
        // The bound is reached after exactly MAX_PASSTHROUGH_HOPS hops.
        let mut env = String::new();
        for i in 0..MAX_PASSTHROUGH_HOPS {
            assert!(hops(Some(&os(&env)), "t") < MAX_PASSTHROUGH_HOPS, "{i}");
            env = with_hop(Some(&os(&env)), "t");
        }
        assert_eq!(hops(Some(&os(&env)), "t"), MAX_PASSTHROUGH_HOPS);
    }
    use super::*;
    use std::ffi::OsString;

    fn tools(names: &[&str]) -> Allow {
        Allow::Tools(names.iter().map(|s| s.to_string()).collect())
    }

    #[cfg(unix)]
    fn exe(dir: &Path, name: &str) -> PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let p = dir.join(name);
        std::fs::write(&p, "#!/bin/sh\n").unwrap();
        std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
        p
    }

    fn os(p: &Path) -> OsString {
        p.as_os_str().to_os_string()
    }

    fn write_config(home: &Path, body: &str) -> PathBuf {
        let cfg = home.join(USER_CONFIG_FILE);
        std::fs::create_dir_all(cfg.parent().unwrap()).unwrap();
        std::fs::write(&cfg, body).unwrap();
        cfg
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[test]
    fn the_config_names_tools_or_star_and_nothing_else() {
        assert_eq!(parse_config("").unwrap(), Allow::Nothing);
        assert_eq!(parse_config("[shim]\n").unwrap(), Allow::Nothing);
        assert_eq!(
            parse_config("[shim]\npassthrough = []\n").unwrap(),
            Allow::Nothing
        );
        assert_eq!(
            parse_config("[shim]\npassthrough = [\"b\", \"a\", \"b\"]\n").unwrap(),
            tools(&["a", "b"])
        );
        assert_eq!(
            parse_config("[shim]\npassthrough = [\"*\"]\n").unwrap(),
            Allow::Everything
        );
        assert_eq!(
            parse_config("[shim]\npassthrough = [\"a\", \"*\"]\n").unwrap(),
            Allow::Everything
        );
        for bad in [
            "[shim]\npassthrough = [\"\"]\n",
            "[shim]\npassthrough = [\"a/b\"]\n",
            "[shim]\npassthrough = [\"a\\\\b\"]\n",
            "[shim]\npassthru = [\"a\"]\n",
            "[shim]\npassthrough = [\"a\"]\nextra = 1\n",
            "[other]\nx = 1\n",
            "passthrough = [\"a\"]\n",
            "[shim\n",
        ] {
            assert!(parse_config(bad).is_err(), "accepted {bad:?}");
        }
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[test]
    fn what_is_allowed_is_recorded_as_star_or_sorted_names() {
        assert!(!Allow::Nothing.permits("a"));
        assert!(Allow::Everything.permits("anything"));
        assert!(tools(&["a"]).permits("a"));
        assert!(!tools(&["a"]).permits("b"));
        assert!(Allow::Nothing.recorded().is_empty());
        assert_eq!(Allow::Everything.recorded(), ["*"]);
        assert_eq!(tools(&["b", "a"]).recorded(), ["a", "b"]);
        assert!(describe_allow(&["*".to_string()]).contains("every tool"));
        assert_eq!(describe_allow(&["a".to_string(), "b".to_string()]), "a, b");
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[test]
    fn the_config_home_is_absolute_xdg_else_home_dot_config() {
        let abs = OsString::from("/x/cfg");
        let home = OsString::from("/h");
        let rel = OsString::from("rel");
        let want = |base: &str| PathBuf::from(base).join(USER_CONFIG_FILE);
        assert_eq!(config_path(Some(&abs), Some(&home)), Some(want("/x/cfg")));
        assert_eq!(config_path(Some(&abs), None), Some(want("/x/cfg")));
        assert_eq!(config_path(None, Some(&home)), Some(want("/h/.config")));
        // A relative or empty XDG_CONFIG_HOME is invalid: fall back, never use it.
        assert_eq!(
            config_path(Some(&rel), Some(&home)),
            Some(want("/h/.config"))
        );
        assert_eq!(
            config_path(Some(OsStr::new("")), Some(&home)),
            Some(want("/h/.config"))
        );
        assert_eq!(config_path(Some(&rel), None), None);
        assert_eq!(config_path(None, None), None);
        assert_eq!(config_path(None, Some(&rel)), None);
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[test]
    fn a_config_is_in_the_repository_when_an_ancestor_marker_contains_it() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        let sub = repo.join("a/b");
        std::fs::create_dir_all(&sub).unwrap();
        let canon = std::fs::canonicalize(&repo).unwrap();
        let inside = write_config(&repo.join(".cfg"), "");
        let outside = write_config(&tmp.path().join("home"), "");

        // No marker yet: not a repository.
        assert_eq!(repository_holding(&inside, &sub), None);
        // `.git` marks it, and a file outside it is not inside it.
        std::fs::create_dir(repo.join(".git")).unwrap();
        assert_eq!(repository_holding(&inside, &sub), Some(canon.clone()));
        assert_eq!(repository_holding(&outside, &sub), None);
        // `varve.toml` marks one too.
        std::fs::remove_dir(repo.join(".git")).unwrap();
        assert_eq!(repository_holding(&inside, &sub), None);
        std::fs::write(repo.join("varve.toml"), "").unwrap();
        assert_eq!(repository_holding(&inside, &sub), Some(canon));
        // A marker NEARER the config than the cwd is not an ancestor of cwd.
        std::fs::remove_file(repo.join("varve.toml")).unwrap();
        std::fs::create_dir(repo.join(".cfg/.git")).unwrap();
        assert_eq!(repository_holding(&inside, &sub), None);
        // A missing config cannot be placed.
        assert_eq!(repository_holding(&repo.join("nope"), &sub), None);
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[cfg(unix)]
    #[test]
    fn a_symlink_cannot_launder_a_repository_config() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        std::fs::create_dir_all(repo.join("cfg")).unwrap();
        std::fs::create_dir(repo.join(".git")).unwrap();
        let real = write_config(&repo.join("cfg"), "");
        let link = tmp.path().join("link");
        std::os::unix::fs::symlink(repo.join("cfg"), &link).unwrap();
        let spelled = link.join(USER_CONFIG_FILE);
        assert!(spelled.exists() && real.exists());
        assert!(repository_holding(&spelled, &repo).is_some());
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[test]
    fn load_grants_only_from_a_valid_file_outside_the_repository() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        std::fs::write(repo.join("varve.toml"), "").unwrap();
        let home = tmp.path().join("home");

        // No file at all, and no variable at all.
        assert_eq!(
            load(Some(&os(&home)), None, &repo).unwrap(),
            UserPassthrough::default()
        );
        assert_eq!(load(None, None, &repo).unwrap(), UserPassthrough::default());

        // A good file.
        let cfg = write_config(&home, "[shim]\npassthrough = [\"a\"]\n");
        let got = load(Some(&os(&home)), None, &repo).unwrap();
        assert_eq!(got.allow, tools(&["a"]));
        assert_eq!(got.source, Some(cfg));

        // The same kind of file named through HOME.
        let h = tmp.path().join("h2");
        write_config(&h.join(".config"), "[shim]\npassthrough = [\"*\"]\n");
        assert_eq!(
            load(None, Some(&os(&h)), &repo).unwrap().allow,
            Allow::Everything
        );

        // A bad file grants nothing and says why.
        let bad = tmp.path().join("bad");
        let badcfg = write_config(&bad, "[shim]\npassthru = []\n");
        match load(Some(&os(&bad)), None, &repo).unwrap_err() {
            ConfigProblem::Invalid { config, why } => {
                assert_eq!(config, badcfg);
                assert!(why.contains("unknown field"), "{why}");
            }
            other => panic!("{other:?}"),
        }

        // A directory where the file should be is unreadable, not absent.
        let dir = tmp.path().join("dirhome");
        std::fs::create_dir_all(dir.join(USER_CONFIG_FILE)).unwrap();
        assert!(matches!(
            load(Some(&os(&dir)), None, &repo).unwrap_err(),
            ConfigProblem::Unreadable { .. }
        ));

        // Inside the repository: never read, even though it is valid.
        let in_repo = repo.join("xdg");
        write_config(&in_repo, "[shim]\npassthrough = [\"*\"]\n");
        match load(Some(&os(&in_repo)), None, &repo).unwrap_err() {
            ConfigProblem::InRepository { repo: r, .. } => {
                assert_eq!(r, std::fs::canonicalize(&repo).unwrap());
            }
            other => panic!("{other:?}"),
        }
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[test]
    fn each_problem_says_what_it_is() {
        let c = PathBuf::from("/c/config.toml");
        let in_repo = ConfigProblem::InRepository {
            config: c.clone(),
            repo: PathBuf::from("/r"),
        }
        .to_string();
        assert!(in_repo.contains("inside the repository /r"), "{in_repo}");
        assert!(in_repo.contains("/c/config.toml"), "{in_repo}");
        let bad = ConfigProblem::Invalid {
            config: c.clone(),
            why: "boom".into(),
        }
        .to_string();
        assert!(
            bad.contains("boom") && bad.contains("passthrough is off"),
            "{bad}"
        );
        let unreadable = ConfigProblem::Unreadable {
            config: c,
            why: "denied".into(),
        }
        .to_string();
        assert!(unreadable.contains("denied") && unreadable.contains("cannot read"));
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[cfg(unix)]
    #[test]
    fn the_ambient_binary_is_never_a_shim_of_any_root() {
        let shims = tempfile::tempdir().unwrap();
        let other_shims = tempfile::tempdir().unwrap();
        let real = tempfile::tempdir().unwrap();
        let varve = exe(real.path(), "varve");
        std::os::unix::fs::symlink(&varve, shims.path().join("ghost")).unwrap();
        std::os::unix::fs::symlink(&varve, other_shims.path().join("ghost")).unwrap();
        let path = std::env::join_paths([shims.path(), other_shims.path()]).unwrap();

        // Only shims on PATH: nothing to run.
        assert_eq!(
            ambient_binary(
                Some(&path),
                "ghost",
                shims.path(),
                Some(&varve),
                Path::new("/")
            ),
            None
        );
        // Another root's shim is skipped by identity, the real one is found.
        let ghost = exe(real.path(), "ghost");
        let path = std::env::join_paths([other_shims.path(), real.path()]).unwrap();
        assert_eq!(
            ambient_binary(
                Some(&path),
                "ghost",
                shims.path(),
                Some(&varve),
                Path::new("/")
            ),
            Some(ghost.clone())
        );
        // Without a known self, only the shim directory itself is skipped.
        assert_eq!(
            ambient_binary(
                Some(&path),
                "ghost",
                other_shims.path(),
                None,
                Path::new("/")
            ),
            Some(ghost)
        );
        assert_eq!(
            ambient_binary(None, "ghost", shims.path(), None, Path::new("/")),
            None
        );
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[test]
    fn the_notice_names_the_tool_the_binary_the_layer_and_the_grant() {
        let n = notice(
            "ghost",
            Path::new("/opt/ghost"),
            "2026.07.0",
            Some(Path::new("/u/config.toml")),
        );
        assert!(n.starts_with("varve: passthrough: 'ghost'"), "{n}");
        assert!(n.contains("2026.07.0"), "{n}");
        assert!(n.contains("running /opt/ghost outside the layer"), "{n}");
        assert!(n.contains("allowed by /u/config.toml"), "{n}");
        assert!(!n.contains('\n'));
        let anon = notice("ghost", Path::new("/opt/ghost"), "l", None);
        assert!(
            anon.contains("allowed by your user configuration"),
            "{anon}"
        );
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[cfg(unix)]
    #[test]
    fn active_passthroughs_are_the_allowed_tools_the_layer_does_not_carry() {
        let shims = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        let ghost = exe(bin.path(), "ghost");
        exe(bin.path(), "probe");
        let path = os(bin.path());
        let carried = vec!["probe".to_string()];
        let names = vec!["ghost".to_string(), "probe".to_string(), "mute".to_string()];
        let act = |allow: &Allow| {
            active(
                allow,
                &carried,
                &names,
                Some(&path),
                shims.path(),
                None,
                Path::new("/"),
            )
        };

        assert!(act(&Allow::Nothing).is_empty());
        // Listed: carried tools drop out (clause 2); an unanswered name stays.
        assert_eq!(
            act(&tools(&["probe", "ghost", "absent"])),
            vec![
                Active {
                    tool: "absent".into(),
                    binary: None
                },
                Active {
                    tool: "ghost".into(),
                    binary: Some(ghost.clone())
                },
            ]
        );
        // `*`: the shims, minus carried, minus those nothing answers to.
        assert_eq!(
            act(&Allow::Everything),
            vec![Active {
                tool: "ghost".into(),
                binary: Some(ghost)
            }]
        );
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[cfg(unix)]
    #[test]
    fn a_name_that_is_not_ascii_is_never_active() {
        let shims = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        exe(bin.path(), "ghost");
        exe(bin.path(), "\u{d1}");
        let path = os(bin.path());
        let act = |carried: &[&str], names: &[&str]| {
            active(
                &Allow::Everything,
                &carried.iter().map(|c| c.to_string()).collect::<Vec<_>>(),
                &names.iter().map(|c| c.to_string()).collect::<Vec<_>>(),
                Some(&path),
                shims.path(),
                None,
                Path::new("/"),
            )
            .into_iter()
            .map(|a| a.tool)
            .collect::<Vec<_>>()
        };
        // A non-ASCII candidate is skipped, an ASCII one stays.
        assert_eq!(act(&[], &["ghost", "\u{d1}"]), ["ghost"]);
        // A non-ASCII carried name makes nothing certain: nothing is active.
        assert!(act(&["\u{f1}"], &["ghost"]).is_empty());
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[cfg(unix)]
    #[test]
    fn a_carried_name_blocks_a_spelling_in_another_case() {
        let shims = tempfile::tempdir().unwrap();
        let bin = tempfile::tempdir().unwrap();
        exe(bin.path(), "PROBE");
        let path = os(bin.path());
        let carried = vec!["probe".to_string()];
        let names = vec!["PROBE".to_string()];
        assert!(
            active(
                &Allow::Everything,
                &carried,
                &names,
                Some(&path),
                shims.path(),
                None,
                Path::new("/")
            )
            .is_empty()
        );
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[test]
    fn the_notice_escapes_control_characters_and_stays_one_line() {
        let n = notice(
            "gh\nost",
            Path::new("/opt/a\nb\r/ghost\u{1b}[0m"),
            "2026\n.07",
            Some(Path::new("/u/c\nonfig.toml")),
        );
        assert!(!n.chars().any(char::is_control), "{n:?}");
        assert!(n.contains("/opt/a\\nb\\r/ghost\\u{1b}[0m"), "{n}");
        assert!(n.contains("gh\\nost"), "{n}");
        assert!(n.contains("2026\\n.07"), "{n}");
        assert!(n.contains("/u/c\\nonfig.toml"), "{n}");
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[test]
    fn the_notice_escapes_format_and_separator_characters_too() {
        // Bidi controls reorder what a terminal shows; zero-width and line or
        // paragraph separators split or hide text. None is `is_control`.
        let hostile = [
            '\u{200b}', '\u{200c}', '\u{200d}', '\u{200e}', '\u{200f}', '\u{202a}', '\u{202b}',
            '\u{202c}', '\u{202d}', '\u{202e}', '\u{2028}', '\u{2029}', '\u{2066}', '\u{2067}',
            '\u{2068}', '\u{2069}', '\u{feff}',
        ];
        // Also: the Arabic letter mark, the soft hyphen, the word joiner and
        // invisible operators, the Mongolian vowel separator, the interlinear
        // annotation controls, and the whole tag block (invisible "ASCII").
        let more = [0x61c_u32, 0xad, 0x180e]
            .into_iter()
            .chain(0x2060..=0x2064)
            .chain(0xfff9..=0xfffb)
            .chain(0xe0000..=0xe007f)
            .map(|u| char::from_u32(u).unwrap());
        for c in hostile.into_iter().chain(more) {
            let name = format!("a{c}b");
            let n = notice(&name, Path::new("/opt/x"), "2026.07.0", None);
            assert!(!n.contains(c), "U+{:04X} survived: {n:?}", c as u32);
            assert!(n.contains(&format!("a{}b", c.escape_default())), "{n}");
        }
        // The sets end where they end: neighbours are ordinary text.
        for u in [
            0x61b_u32, 0x61d, 0xac, 0xae, 0x180d, 0x180f, 0x205f, 0x2065, 0xfff8, 0xfffc, 0xe0080,
        ] {
            let c = char::from_u32(u).unwrap();
            let n = notice(&format!("a{c}b"), Path::new("/opt/x"), "2026.07.0", None);
            assert!(n.contains(c), "U+{u:04X} was escaped: {n:?}");
        }
        // Ordinary non-ASCII text is left readable.
        let n = notice("g\u{f1}", Path::new("/opt/x"), "2026.07.0", None);
        assert!(n.contains("g\u{f1}"), "{n}");
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[cfg(unix)]
    #[test]
    fn the_ambient_search_skips_absolute_entries_inside_the_repository() {
        let shims = tempfile::tempdir().unwrap();
        let repo = tempfile::tempdir().unwrap();
        std::fs::write(repo.path().join("varve.toml"), "").unwrap();
        let inside = repo.path().join("bin");
        std::fs::create_dir_all(&inside).unwrap();
        exe(&inside, "ghost");
        let outside = tempfile::tempdir().unwrap();
        let real = exe(outside.path(), "ghost");
        let link = outside.path().join("link");
        std::os::unix::fs::symlink(&inside, &link).unwrap();
        let find = |dirs: &[&Path], cwd: &Path| {
            ambient_binary(
                Some(&std::env::join_paths(dirs).unwrap()),
                "ghost",
                shims.path(),
                None,
                cwd,
            )
        };
        // Inside the repository: skipped, whether spelt directly or by a link;
        // the next entry is used.
        assert_eq!(
            find(&[&inside, outside.path()], repo.path()),
            Some(real.clone())
        );
        assert_eq!(find(&[&link, outside.path()], repo.path()), Some(real));
        assert_eq!(find(&[&inside], repo.path()), None);
        assert_eq!(find(&[&link], &inside), None);
        // The same directory is searched when cwd is in no repository.
        assert_eq!(find(&[&inside], Path::new("/")), Some(inside.join("ghost")));
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[cfg(unix)]
    #[test]
    fn the_ambient_search_skips_relative_path_entries() {
        // A relative entry that DOES resolve to a real ghost (it climbs to the
        // root and back down) is still the working directory's business, not
        // PATH's: only the absolute spelling of the same directory is used.
        let shims = tempfile::tempdir().unwrap();
        let real = tempfile::tempdir().unwrap();
        let ghost = exe(real.path(), "ghost");
        let climb = format!(
            "{}{}",
            "../".repeat(64),
            real.path().to_str().unwrap().trim_start_matches('/')
        );
        assert!(Path::new(&climb).join("ghost").exists());
        let relative = OsString::from(&climb);
        assert_eq!(
            ambient_binary(Some(&relative), "ghost", shims.path(), None, Path::new("/")),
            None
        );
        let both = std::env::join_paths([OsString::from(&climb), os(real.path())]).unwrap();
        assert_eq!(
            ambient_binary(Some(&both), "ghost", shims.path(), None, Path::new("/")),
            Some(ghost)
        );
    }

    // rivet: verifies REQ-PASSTHROUGH-001
    #[test]
    fn every_common_version_control_marker_makes_a_directory_a_repository() {
        for marker in [".git", ".hg", ".jj", ".svn", "varve.toml"] {
            let repo = tempfile::tempdir().unwrap();
            let repo_path = std::fs::canonicalize(repo.path()).unwrap();
            let cfg = write_config(&repo_path.join("home/.config"), "");
            let work = repo_path.join("work");
            std::fs::create_dir_all(&work).unwrap();
            assert_eq!(repository_holding(&cfg, &work), None, "no marker yet");
            std::fs::create_dir(repo_path.join(marker)).unwrap();
            assert_eq!(
                repository_holding(&cfg, &work),
                Some(repo_path.clone()),
                "{marker} was not recognised as a repository"
            );
        }
    }
}