phora 0.6.0

A git-based artifact package manager and multiplexer for content-addressed file distribution
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
//! The `phora trust` command: inspect, approve, and revoke transitive-dep hooks.
//!
//! Before approving, both `--list` and the interactive flow render the file-level paths changed in
//! the dep between the last trusted commit and the current candidate commit (R8), so a consumer can
//! verify the hook's surrounding tree was not tampered. A synced mirror holds both commits; a
//! discovery-only mirror that lacks the prior commit degrades to a "run `phora sync` first" note.

use std::io::IsTerminal;
use std::path::Path;
use std::time::Duration;

use crate::config::transitive::{Member, TransitiveManifest};
use crate::error::{Error, Result};
use crate::lock::{CandidateHookRecord, Lock, TrustedHook};
use crate::source::{
    Commit, GitBackend, ResolvePolicy, ResolveRequest, RevisionSpec, SourceDirectoryEntryKind,
    SourceError, SourceLocation, SourcePath, SourceStore,
};
use crate::sync::transitive::ResolvedGraph;

use super::{load_config, lock_project_registry};

/// A discovery-only candidate carries no real preimage: it is resolved on first sync.
const UNRESOLVED_PREIMAGE: &str = "";

pub(super) fn run_trust(
    source: Option<&str>,
    list: bool,
    revoke: bool,
    show: Option<&str>,
    lock_timeout: Duration,
) -> Result<()> {
    let mut config = load_config()?;
    config.lower_transitive();
    let _locked = lock_project_registry(&config, lock_timeout)?;

    let cwd = std::env::current_dir()?;
    let cache_git = crate::paths::cache_root_for(config.paths.cache.as_deref(), &cwd)?.join("git");
    let (mut base_lock, local_lock) = super::sync::load_locks(&cwd)?;

    if revoke {
        let source = source.ok_or_else(|| {
            Error::Config("`phora trust --revoke` needs a source name".to_owned())
        })?;
        return revoke_source_hooks(&cwd, base_lock.as_mut(), local_lock.as_ref(), source);
    }

    if let Some(path) = show {
        let (source, targets) = resolve_show_targets(base_lock.as_ref(), source)?;
        let backend = GitBackend::new(cache_git.clone());
        for line in render_first_show(&backend, &source, &targets, Path::new(path))? {
            println!("{line}");
        }
        return Ok(());
    }

    let candidates = discover_candidates(&config, &cwd, base_lock.as_ref(), source)?;
    let mut differ = TrustDiff::open(&cache_git, base_lock.as_ref());
    differ.attach_surface(&config, base_lock.as_ref());
    if list || !std::io::stdin().is_terminal() {
        print_candidates(&candidates, &differ);
        return Ok(());
    }

    let approved = approve(&candidates, &differ, &StdinConfirm);
    persist_approvals(&cwd, &mut base_lock, local_lock.as_ref(), approved)
}

/// Renders the file-level diff between a candidate's commit and the commit a prior approval trusted.
struct TrustDiff {
    backend: Option<GitBackend>,
    trusted_hooks: Vec<TrustedHook>,
    dep_urls: Vec<String>,
    surface: Option<(ResolvedGraph, Lock)>,
    lock: Option<Lock>,
    hosts: std::collections::BTreeMap<String, crate::config::Host>,
}

impl TrustDiff {
    fn open(cache_git: &std::path::Path, base_lock: Option<&Lock>) -> Self {
        let backend = Some(GitBackend::new(cache_git.to_path_buf()));
        let (trusted_hooks, dep_urls) = base_lock.map_or_else(
            || (Vec::new(), Vec::new()),
            |lock| {
                let mut urls: Vec<String> = lock.sources.iter().map(|s| s.git.clone()).collect();
                urls.sort_unstable();
                urls.dedup();
                (lock.trusted_hooks.clone(), urls)
            },
        );
        Self {
            backend,
            trusted_hooks,
            dep_urls,
            surface: None,
            lock: base_lock.cloned(),
            hosts: std::collections::BTreeMap::new(),
        }
    }

    /// Where the candidate's hook is written, at the commit under review.
    fn definition(&self, candidate: &CandidateHookRecord) -> Option<String> {
        let (head, _) = candidate.hook_id.split_once('#')?;
        let Some(Member::Named(target)) = Member::of(head) else {
            return None;
        };
        let package = self.lock.as_ref()?.sources.iter().find(|s| {
            s.instance.as_deref() == Some(candidate.dep_instance.as_str())
                && matches!(Member::of(&s.name), Some(Member::Files | Member::Repo))
        })?;
        let manifest = if package.resolved == "link" {
            std::fs::read_to_string(Path::new(&package.git).join("phora.toml")).ok()?
        } else {
            let backend = self.backend.as_ref()?;
            show_entry(
                backend,
                &candidate.source,
                &package.git,
                &candidate.commit,
                Path::new("phora.toml"),
            )
            .ok()??
            .join("\n")
        };
        let line = crate::config::link::hook_line(&manifest, &target, &candidate.command);
        Some(format!(
            "  defined: {}",
            crate::config::link::file_link(
                &self.hosts,
                &package.git,
                &candidate.commit,
                "phora.toml",
                line
            )
        ))
    }

    fn attach_surface(&mut self, config: &crate::config::Config, base_lock: Option<&Lock>) {
        self.hosts.clone_from(&config.hosts);
        let Some(lock) = base_lock else { return };
        let Some(backend) = self.backend.as_ref() else {
            return;
        };
        let Ok(parsed) = config.parsed_sources() else {
            return;
        };
        if let Ok(graph) = crate::sync::transitive::resolve_transitive_graph_offline(
            config, &parsed, backend, lock,
        ) {
            self.surface = Some((graph, lock.clone()));
        }
    }

    fn lines_for(&self, candidate: &CandidateHookRecord) -> Vec<String> {
        self.definition(candidate)
            .into_iter()
            .chain(self.review_lines(candidate))
            .collect()
    }

    fn review_lines(&self, candidate: &CandidateHookRecord) -> Vec<String> {
        let candidate_key = commit_stable_hook_key(&candidate.hook_id);
        let priors: Vec<&TrustedHook> = self
            .trusted_hooks
            .iter()
            .filter(|h| {
                h.source == candidate.source
                    && commit_stable_hook_key(&h.hook_id) == candidate_key
                    && !h.commit.is_empty()
            })
            .collect();
        if priors.is_empty() {
            return self.first_trust_lines(candidate);
        }
        if candidate.commit.is_empty() {
            return vec![
                "  diff unavailable — candidate has no recorded commit; run `phora sync` first"
                    .to_owned(),
            ];
        }
        if priors.iter().any(|p| p.commit == candidate.commit) {
            return vec!["  unchanged since last trusted".to_owned()];
        }
        self.changed_paths(candidate, &priors)
    }

    fn changed_paths(
        &self,
        candidate: &CandidateHookRecord,
        priors: &[&TrustedHook],
    ) -> Vec<String> {
        let Some(backend) = &self.backend else {
            return vec![diff_unavailable()];
        };
        let name = crate::source::SourceName::trusted(candidate.source.clone());
        // The dep is the mirror holding BOTH commits; this resolves nested deps and discriminates colliding (source, stripped-key) pairs that the lock can't.
        for url in &self.dep_urls {
            for prior in priors {
                if let Ok(paths) =
                    backend.file_diff_between(&name, url, &prior.commit, &candidate.commit)
                {
                    let mut out = vec![format!(
                        "  changed since last trusted ({}..{}):",
                        short(&prior.commit),
                        short(&candidate.commit)
                    )];
                    out.extend(paths.into_iter().map(|p| format!("    {p}")));
                    return out;
                }
            }
        }
        vec![diff_unavailable()]
    }

    fn first_trust_lines(&self, candidate: &CandidateHookRecord) -> Vec<String> {
        if candidate.commit.is_empty() {
            return vec![surface_unavailable()];
        }
        let (Some((graph, lock)), Some(backend)) = (&self.surface, &self.backend) else {
            return vec![surface_unavailable()];
        };
        let Some(target) = graph.targets.iter().find(|t| {
            candidate.hook_id == format!("{}#on_change", t.name)
                || candidate
                    .hook_id
                    .starts_with(&format!("{}#on_change#", t.name))
        }) else {
            return vec![surface_unavailable()];
        };
        match graph.composed_files(&target.name, backend, lock) {
            Ok(paths) if !paths.is_empty() => {
                let mut out = vec![format!("  composed files at {}:", short(&candidate.commit))];
                out.extend(paths.into_iter().map(|p| format!("    {p}")));
                out
            }
            _ => vec![surface_unavailable()],
        }
    }
}

fn surface_unavailable() -> String {
    "  composed surface unavailable — run `phora sync` first".to_owned()
}

/// Drops the instance key, which differs per consumer binding, so a hook matches across commits.
fn commit_stable_hook_key(hook_id: &str) -> String {
    let (head, tail) = hook_id.split_once('#').unwrap_or((hook_id, ""));
    match Member::of(head) {
        Some(Member::Named(dep_target)) => format!("{dep_target}#{tail}"),
        Some(Member::Files | Member::Repo) | None => format!("{head}#{tail}"),
    }
}

fn diff_unavailable() -> String {
    "  diff unavailable — run `phora sync` first".to_owned()
}

fn short(commit: &str) -> &str {
    commit.get(..12).unwrap_or(commit)
}

fn persist_approvals(
    cwd: &std::path::Path,
    base_lock: &mut Option<Lock>,
    local_lock: Option<&Lock>,
    approved: Vec<CandidateHookRecord>,
) -> Result<()> {
    if approved.is_empty() {
        println!("phora: no transitive hooks approved");
        return Ok(());
    }
    let lock = base_lock.get_or_insert_with(empty_lock);
    let now = chrono::Utc::now().to_rfc3339();
    for candidate in approved {
        lock.trusted_hooks.push(TrustedHook {
            dep_instance: candidate.dep_instance,
            hook_id: candidate.hook_id,
            preimage: candidate.preimage,
            approved_at: now.clone(),
            source: candidate.source,
            commit: candidate.commit,
        });
    }
    super::sync::write_locks(cwd, lock, local_lock)?;
    Ok(())
}

fn revoke_source_hooks(
    cwd: &std::path::Path,
    base_lock: Option<&mut Lock>,
    local_lock: Option<&Lock>,
    source: &str,
) -> Result<()> {
    let Some(lock) = base_lock else {
        println!("phora: no lock — nothing to revoke for `{source}`");
        return Ok(());
    };
    let before = lock.trusted_hooks.len();
    lock.trusted_hooks.retain(|h| h.source != source);
    let removed = before - lock.trusted_hooks.len();
    super::sync::write_locks(cwd, lock, local_lock)?;
    println!("phora: revoked {removed} transitive hook approval(s) for `{source}`");
    Ok(())
}

/// The `(url, commit)` entries a `--show` for `source` may read, from the lock entries of the
/// source's candidate (else prior trusted) hook instance: its own files first, then its bound
/// sources by name. Instances resolving to different entries are ambiguous and refused.
pub(super) fn resolve_show_targets(
    lock: Option<&Lock>,
    source: Option<&str>,
) -> Result<(String, Vec<(String, String)>)> {
    let source = source
        .ok_or_else(|| Error::Config("`phora trust --show` needs a source name".to_owned()))?;
    let lock = lock.ok_or_else(|| {
        Error::Config(format!(
            "no commit recorded for `{source}` — run `phora sync` first"
        ))
    })?;

    let mut instances: Vec<&str> = lock
        .candidate_hooks
        .iter()
        .filter(|c| c.source == source)
        .map(|c| c.dep_instance.as_str())
        .collect();
    if instances.is_empty() {
        instances = lock
            .trusted_hooks
            .iter()
            .filter(|h| h.source == source)
            .map(|h| h.dep_instance.as_str())
            .collect();
    }

    let mut candidates: Vec<Vec<(String, String)>> = Vec::new();
    for instance in instances {
        let targets: Vec<(String, String)> = locked_targets(lock, instance, source)
            .into_iter()
            .filter(|(_, commit)| !commit.is_empty())
            .collect();
        if !targets.is_empty() && !candidates.contains(&targets) {
            candidates.push(targets);
        }
    }
    let targets = match candidates.as_slice() {
        [] => {
            return Err(Error::Config(format!(
                "no commit recorded for `{source}` — run `phora sync` first"
            )));
        }
        [targets] => targets.clone(),
        many => {
            let commits = many
                .iter()
                .flatten()
                .map(|(_, c)| short(c))
                .collect::<Vec<_>>()
                .join(", ");
            return Err(Error::Config(format!(
                "`{source}` has several recorded commits ({commits}); sync to pin one before --show"
            )));
        }
    };
    Ok((source.to_owned(), targets))
}

/// The `(git, commit)` entries for `instance` (a transitive node), its own files first; falls back
/// to the consumer source named `source`. Both fields of each pair come from the SAME entry, so a
/// `--show` reads a dep's files at the commit its own mirror actually holds.
fn locked_targets(lock: &Lock, instance: &str, source: &str) -> Vec<(String, String)> {
    let mut entries: Vec<&crate::lock::LockedSource> = lock
        .sources
        .iter()
        .filter(|s| s.instance.as_deref() == Some(instance))
        .collect();
    entries.sort_by_key(|s| (Member::of(&s.name) != Some(Member::Files), s.name.clone()));
    if entries.is_empty() {
        entries.extend(lock.sources.iter().find(|s| s.name == source));
    }
    entries
        .into_iter()
        .map(|s| (s.git.clone(), s.commit.clone()))
        .collect()
}

/// Renders `path` from the first target that holds it; absent from all of them is an error.
fn render_first_show(
    backend: &dyn SourceStore,
    source: &str,
    targets: &[(String, String)],
    path: &Path,
) -> Result<Vec<String>> {
    for (url, commit) in targets {
        if let Some(lines) = show_entry(backend, source, url, commit, path)? {
            return Ok(lines);
        }
    }
    let commits = targets
        .iter()
        .map(|(_, c)| short(c))
        .collect::<Vec<_>>()
        .join(", ");
    Err(Error::Source(format!(
        "{} is absent at {commits} in `{source}`",
        path.display()
    )))
}

/// Renders a dep `path` at `commit` from the mirror, offline: a UTF-8 file as its text lines, a
/// directory as an ls-style listing (subdirectories suffixed `/`), refusing binary content; an
/// absent path is `None`. Dispatch is by source-capability outcome, never by matching error strings.
fn show_entry(
    backend: &dyn SourceStore,
    source: &str,
    url: &str,
    commit: &str,
    path: &Path,
) -> Result<Option<Vec<String>>> {
    let name = crate::source::SourceName::trusted(source.to_owned());
    let commit_id = commit.parse::<Commit>().map_err(|_| {
        Error::Source(format!(
            "`{}` cannot be shown — its commit `{}` is invalid; run `phora sync` first",
            path.display(),
            short(commit)
        ))
    })?;
    let resolved = backend
        .resolve(
            &ResolveRequest {
                name,
                location: SourceLocation::Git {
                    url: url.to_owned(),
                },
                revision: RevisionSpec::Commit(commit_id),
            },
            ResolvePolicy::CachedOnly,
        )
        .map_err(|_| {
            Error::Source(format!(
                "`{}` cannot be shown — its commit `{}` is not in the mirror; run `phora sync` first",
                path.display(),
                short(commit)
            ))
        })?;
    let source_path = if path.as_os_str().is_empty() {
        None
    } else {
        Some(SourcePath::new(&path.to_string_lossy().replace('\\', "/"))?)
    };
    let read = match source_path.as_ref() {
        Some(path) => backend.read(&resolved.snapshot, path),
        None => Err(SourceError::RootNotFound {
            root: Path::new("").to_path_buf(),
        }),
    };
    match read {
        Ok(entry) => match std::str::from_utf8(&entry.bytes) {
            Ok(text) => Ok(Some(text.lines().map(str::to_owned).collect())),
            Err(_) => Err(Error::Source(format!(
                "{} at {} is not UTF-8 text — binary content is not shown",
                path.display(),
                short(commit)
            ))),
        },
        Err(_) => match backend.list_directory(&resolved.snapshot, source_path.as_ref()) {
            Ok(entries) => Ok(Some(
                entries
                    .into_iter()
                    .map(|e| {
                        let name = e
                            .path
                            .as_str()
                            .rsplit('/')
                            .next()
                            .unwrap_or(e.path.as_str());
                        if e.kind == SourceDirectoryEntryKind::Directory {
                            format!("{name}/")
                        } else {
                            name.to_owned()
                        }
                    })
                    .collect(),
            )),
            Err(SourceError::RootNotFound { .. }) => Ok(None),
            Err(_) => Err(Error::Source(format!(
                "`{}` cannot be shown — its commit `{}` is not in the mirror; run `phora sync` first",
                path.display(),
                short(commit)
            ))),
        },
    }
}

fn discover_candidates(
    config: &crate::config::Config,
    cwd: &std::path::Path,
    base_lock: Option<&Lock>,
    source: Option<&str>,
) -> Result<Vec<CandidateHookRecord>> {
    if let Some(lock) = base_lock {
        let recorded = match source {
            Some(name) => candidates_for_source(lock, name),
            None => lock.candidate_hooks.clone(),
        };
        if !recorded.is_empty() {
            return Ok(recorded);
        }
    }
    match source {
        Some(name) => discover_via_fetch(config, cwd, name),
        None => Ok(Vec::new()),
    }
}

fn discover_via_fetch(
    config: &crate::config::Config,
    cwd: &std::path::Path,
    name: &str,
) -> Result<Vec<CandidateHookRecord>> {
    use crate::source::{GitBackend, Protocol as SourceProtocol, SourceError};

    let sources = config.parsed_sources()?;
    let Some(source) = sources.get(name) else {
        return Ok(Vec::new());
    };
    if source.mode() != crate::config::SourceMode::Git {
        return Ok(Vec::new());
    }
    let protocol = source
        .protocol()
        .or(config.protocol)
        .unwrap_or(SourceProtocol::Https);
    let remote = source
        .resolved_remote(&config.hosts, protocol)
        .map_err(|e| Error::Config(format!("source `{name}`: {e}")))?;
    let git_dir = crate::paths::cache_root_for(config.paths.cache.as_deref(), cwd)?.join("git");
    let backend = GitBackend::new(git_dir);
    let source_name = crate::source::SourceName::trusted(name.to_owned());
    let bytes = match backend.fetch_root_manifest(&source_name, &remote, &source.refspec()) {
        Ok(bytes) => bytes,
        Err(SourceError::FileAbsent { .. }) => return Ok(Vec::new()),
        Err(e) => return Err(Error::Source(format!("inspect `{name}`: {e}"))),
    };
    let text = std::str::from_utf8(&bytes)
        .map_err(|e| Error::Config(format!("source `{name}`: phora.toml is not utf8: {e}")))?;
    let manifest = TransitiveManifest::parse(text)?;
    Ok(fetched_candidates(name, &manifest))
}

fn fetched_candidates(name: &str, manifest: &TransitiveManifest) -> Vec<CandidateHookRecord> {
    let Some(targets) = manifest.hooks().and_then(toml::Value::as_table) else {
        return Vec::new();
    };
    let offered: std::collections::BTreeSet<String> = manifest
        .offer_names()
        .filter_map(|offer| manifest.offer(offer).ok())
        .flat_map(|offer| offer.targets.into_keys())
        .collect();
    let mut out = Vec::new();
    for (target, block) in targets.iter().filter(|(t, _)| offered.contains(*t)) {
        let Some(on_change) = block.get("on_change") else {
            continue;
        };
        for command in hook_commands(on_change) {
            out.push(CandidateHookRecord {
                dep_instance: name.to_owned(),
                hook_id: format!("{name}#{target}#on_change"),
                preimage: UNRESOLVED_PREIMAGE.to_owned(),
                command,
                source: name.to_owned(),
                commit: String::new(),
            });
        }
    }
    out
}

fn hook_commands(value: &toml::Value) -> Vec<String> {
    match value {
        toml::Value::String(run) => vec![run.clone()],
        toml::Value::Array(items) => items
            .iter()
            .filter_map(|item| match item {
                toml::Value::String(run) => Some(run.clone()),
                toml::Value::Table(table) => table
                    .get("run")
                    .and_then(toml::Value::as_str)
                    .map(str::to_owned),
                _ => None,
            })
            .collect(),
        toml::Value::Table(table) => table
            .get("run")
            .and_then(toml::Value::as_str)
            .map(|run| vec![run.to_owned()])
            .unwrap_or_default(),
        _ => Vec::new(),
    }
}

/// Candidates recorded under `source` (the consumer-facing import name). An unknown source scopes
/// to EMPTY — never to every dep's candidates — so `--revoke`/`--list` cannot over-reach.
fn candidates_for_source(lock: &Lock, source: &str) -> Vec<CandidateHookRecord> {
    lock.candidate_hooks
        .iter()
        .filter(|c| c.source == source)
        .cloned()
        .collect()
}

fn print_candidates(candidates: &[CandidateHookRecord], differ: &TrustDiff) {
    if candidates.is_empty() {
        println!("phora: no transitive hooks");
        return;
    }
    for candidate in candidates {
        println!("hook {} (on_change)", candidate.hook_id);
        println!("  command: {}", candidate.command);
        println!("  preimage: {}", preimage_display(&candidate.preimage));
        println!("  env: PHORA_TARGET=<composed target path>");
        println!(
            "  note: the hook inherits the FULL process environment, not only the PHORA_* variables"
        );
        for line in differ.lines_for(candidate) {
            println!("{line}");
        }
    }
}

fn preimage_display(preimage: &str) -> String {
    if preimage == UNRESOLVED_PREIMAGE {
        "(preimage resolved on first sync — run sync, then trust)".to_owned()
    } else {
        preimage.to_owned()
    }
}

/// Per-candidate trust confirmation; lets a test drive approve→persist without a real TTY.
trait Confirm {
    fn confirm(&self, candidate: &CandidateHookRecord) -> bool;
}

struct StdinConfirm;

impl Confirm for StdinConfirm {
    fn confirm(&self, candidate: &CandidateHookRecord) -> bool {
        super::prompt_yes_on_stdin(
            &format!(
                "phora: trust `{}` (runs `{}`)? ",
                candidate.hook_id, candidate.command
            ),
            false,
        )
    }
}

fn approve(
    candidates: &[CandidateHookRecord],
    differ: &TrustDiff,
    confirm: &dyn Confirm,
) -> Vec<CandidateHookRecord> {
    let mut approved = Vec::new();
    for candidate in candidates {
        if candidate.preimage == UNRESOLVED_PREIMAGE {
            continue;
        }
        for line in differ.lines_for(candidate) {
            eprintln!("{line}");
        }
        if confirm.confirm(candidate) {
            approved.push(candidate.clone());
        }
    }
    approved
}

fn empty_lock() -> Lock {
    Lock {
        version: crate::lock::LOCK_SCHEMA_VERSION,
        sources: Vec::new(),
        trusted_hooks: Vec::new(),
        candidate_hooks: Vec::new(),
    }
}

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

    #[test]
    fn discovery_lists_hooks_only_of_targets_an_offer_composes() {
        let manifest = TransitiveManifest::parse(
            "[sources.nvim]\ngit = \"https://github.com/dep/nvim.git\"\n\n\
             [targets.editor]\npath = \"nvim\"\nsources = [\"nvim\"]\nhooks.on_change = \"./offered.sh\"\n\n\
             [targets.home]\npath = \"~/.config/nvim\"\nsources = [\"nvim\"]\nhooks.on_change = \"./local.sh\"\n",
        )
        .expect("manifest parses");
        let commands: Vec<String> = fetched_candidates("dep", &manifest)
            .into_iter()
            .map(|candidate| candidate.command)
            .collect();
        assert_eq!(commands, vec!["./offered.sh".to_owned()]);
    }

    fn candidate(source: &str, preimage: &str) -> CandidateHookRecord {
        CandidateHookRecord {
            dep_instance: format!("{source}-instance"),
            hook_id: format!("{source}#editor#on_change"),
            preimage: preimage.to_owned(),
            command: "touch sentinel".to_owned(),
            source: source.to_owned(),
            commit: String::new(),
        }
    }

    fn no_diff() -> TrustDiff {
        TrustDiff::open(std::path::Path::new("/nonexistent/git"), None)
    }

    struct Canned(bool);

    impl Confirm for Canned {
        fn confirm(&self, _candidate: &CandidateHookRecord) -> bool {
            self.0
        }
    }

    #[test]
    fn offline_transitive_resolve_is_reachable_from_the_trust_layer() {
        use crate::sync::transitive::{
            ComposedTarget, ResolvedGraph, resolve_transitive_graph_offline,
        };

        let config =
            crate::config::Config::parse("version = 1\n\n[targets.x]\npath = \"/home/me/x\"\n")
                .expect("import-free config parses");
        let parsed: std::collections::BTreeMap<String, crate::config::ParsedSource> =
            std::collections::BTreeMap::new();
        let lock = empty_lock();
        let git_dir = tempfile::TempDir::new().expect("temp git dir");
        let backend = crate::source::GitBackend::new(git_dir.path().to_path_buf());

        let graph: ResolvedGraph =
            resolve_transitive_graph_offline(&config, &parsed, &backend, &lock)
                .expect("the offline transitive resolve must be callable from the CLI/trust layer");

        let names: Vec<&str> = graph
            .targets
            .iter()
            .map(|t: &ComposedTarget| t.name.as_str())
            .collect();
        assert!(
            names.is_empty(),
            "REACHABILITY: an import-free config composes no transitive targets, reached offline with no fetch — and the trust layer can see resolve_transitive_graph_offline, ResolvedGraph, ComposedTarget, and the `name` field"
        );
    }

    #[test]
    fn approve_yes_yields_a_record_matching_the_candidate_addressing() {
        let cand = candidate("depA", "blake3:real");

        let approved = approve(std::slice::from_ref(&cand), &no_diff(), &Canned(true));

        assert_eq!(
            approved.len(),
            1,
            "a yes confirmation must approve the hook"
        );
        let got = &approved[0];
        assert_eq!(got.source, cand.source, "approval keeps the source scope");
        assert_eq!(got.dep_instance, cand.dep_instance);
        assert_eq!(got.hook_id, cand.hook_id);
        assert_eq!(
            got.preimage, cand.preimage,
            "the approval must pin the candidate's commit-bound preimage verbatim"
        );
    }

    #[test]
    fn approve_no_persists_nothing() {
        let cand = candidate("depA", "blake3:real");

        let approved = approve(std::slice::from_ref(&cand), &no_diff(), &Canned(false));

        assert!(
            approved.is_empty(),
            "anti-TOFU: declining the prompt must approve nothing"
        );
    }

    #[test]
    fn approve_skips_an_unresolved_preimage_candidate() {
        let cand = candidate("depA", UNRESOLVED_PREIMAGE);

        let approved = approve(std::slice::from_ref(&cand), &no_diff(), &Canned(true));

        assert!(
            approved.is_empty(),
            "a discovery-only candidate has no real preimage to pin; a yes must NOT mint an \
             approval that can never match the commit-bound sync preimage"
        );
    }

    #[test]
    fn candidates_for_source_scopes_to_the_named_source_only() {
        let lock = Lock {
            candidate_hooks: vec![candidate("depA", "blake3:a"), candidate("depB", "blake3:b")],
            ..empty_lock()
        };

        let scoped = candidates_for_source(&lock, "depA");

        assert_eq!(scoped.len(), 1, "only depA's candidate is in scope");
        assert_eq!(scoped[0].source, "depA");
    }

    #[test]
    fn candidates_for_unknown_source_is_empty_never_everything() {
        let lock = Lock {
            candidate_hooks: vec![candidate("depA", "blake3:a"), candidate("depB", "blake3:b")],
            ..empty_lock()
        };

        let scoped = candidates_for_source(&lock, "nonesuch");

        assert!(
            scoped.is_empty(),
            "an unknown source must scope to EMPTY, never fall back to every dep's candidates"
        );
    }

    use crate::source::{
        MirrorKey, NormalizedUrl, ResolvedRevision, ResolvedSource, SnapshotId,
        SourceDirectoryEntry, SourceDirectoryEntryKind, SourceEntry, SourceEntryKind,
        SourceEntryMeta, SourceError, SourceIdentity, SourceInventory, SourceTimestamp,
    };
    use std::path::{Path, PathBuf};

    /// What the mocked mirror reader should hand back for `<path>` at the pinned commit.
    enum FileOutcome {
        Bytes(Vec<u8>),
        Absent,
        NotRegular,
        MirrorError,
    }

    enum TreeOutcome {
        Entries(Vec<SourceDirectoryEntry>),
        Absent,
        MirrorError,
    }

    /// A source store whose configured outcomes exercise the offline reads `--show` drives.
    struct ShowStore {
        file: FileOutcome,
        tree: TreeOutcome,
    }

    impl SourceStore for ShowStore {
        fn resolve(
            &self,
            request: &ResolveRequest,
            policy: ResolvePolicy,
        ) -> std::result::Result<ResolvedSource, SourceError> {
            assert_eq!(
                policy,
                ResolvePolicy::CachedOnly,
                "`trust --show` must resolve the pinned snapshot without refreshing"
            );
            let SourceLocation::Git { url } = &request.location else {
                unreachable!("`trust --show` resolves a Git mirror")
            };
            let RevisionSpec::Commit(commit) = &request.revision else {
                unreachable!("`trust --show` resolves an exact lock-pinned commit")
            };
            let normalized = NormalizedUrl::parse(url);
            Ok(ResolvedSource {
                name: request.name.clone(),
                snapshot: SnapshotId::Git {
                    mirror: MirrorKey::from_url(&normalized),
                    commit: commit.clone(),
                },
                revision: ResolvedRevision::Commit(commit.clone()),
                authored_at: SourceTimestamp::from_unix_seconds(0),
                normalized_location: SourceIdentity::Git(normalized),
            })
        }

        fn inventory(
            &self,
            _snapshot: &SnapshotId,
            _root: Option<&SourcePath>,
        ) -> std::result::Result<SourceInventory, SourceError> {
            Ok(SourceInventory::default())
        }

        fn read(
            &self,
            snapshot: &SnapshotId,
            path: &SourcePath,
        ) -> std::result::Result<SourceEntry, SourceError> {
            let commit = snapshot.commit().as_str();
            match &self.file {
                FileOutcome::Bytes(bytes) => Ok(SourceEntry {
                    meta: SourceEntryMeta {
                        path: path.clone(),
                        kind: SourceEntryKind::File,
                    },
                    bytes: bytes.clone(),
                }),
                FileOutcome::Absent => Err(SourceError::FileAbsent {
                    source_name: "nvim-kit".to_owned(),
                    commit: commit.to_owned(),
                    path: Path::new(path.as_str()).to_path_buf(),
                }),
                FileOutcome::NotRegular => Err(SourceError::Source(format!(
                    "{} is not a regular file",
                    path.as_str()
                ))),
                FileOutcome::MirrorError => Err(SourceError::Source(format!(
                    "open mirror for {commit}: missing"
                ))),
            }
        }

        fn list_directory(
            &self,
            snapshot: &SnapshotId,
            path: Option<&SourcePath>,
        ) -> std::result::Result<Vec<SourceDirectoryEntry>, SourceError> {
            let commit = snapshot.commit().as_str();
            match &self.tree {
                TreeOutcome::Entries(entries) => Ok(entries.clone()),
                TreeOutcome::Absent => Err(SourceError::RootNotFound {
                    root: path.map_or_else(PathBuf::new, |path| PathBuf::from(path.as_str())),
                }),
                TreeOutcome::MirrorError => Err(SourceError::Source(format!(
                    "commit {commit} in mirror: missing"
                ))),
            }
        }
    }

    const COMMIT_A: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    const COMMIT_B: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
    const COMMIT_ONE: &str = "111111111111111111111111111111111111aaaa";
    const COMMIT_TWO: &str = "222222222222222222222222222222222222bbbb";

    fn cand_commit(source: &str, instance: &str, commit: &str) -> CandidateHookRecord {
        CandidateHookRecord {
            dep_instance: instance.to_owned(),
            hook_id: format!("{source}#editor#on_change"),
            preimage: "blake3:p".to_owned(),
            command: "touch sentinel".to_owned(),
            source: source.to_owned(),
            commit: commit.to_owned(),
        }
    }

    fn trusted_commit(source: &str, instance: &str, commit: &str) -> TrustedHook {
        TrustedHook {
            dep_instance: instance.to_owned(),
            hook_id: format!("{source}#editor#on_change"),
            preimage: "blake3:p".to_owned(),
            approved_at: "2026-01-01T00:00:00Z".to_owned(),
            source: source.to_owned(),
            commit: commit.to_owned(),
        }
    }

    fn locked_dep(
        name: &str,
        instance: &str,
        git: &str,
        commit: &str,
    ) -> crate::lock::LockedSource {
        crate::lock::LockedSource {
            name: name.to_owned(),
            git: git.to_owned(),
            resolved: "main".to_owned(),
            commit: commit.to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: "blake3:cfg".to_owned(),
            r#ref: None,
            instance: Some(instance.to_owned()),
            build: None,
        }
    }

    #[test]
    fn render_show_prints_utf8_file_contents() {
        let backend = ShowStore {
            file: FileOutcome::Bytes(b"hello\nworld\n".to_vec()),
            tree: TreeOutcome::Absent,
        };

        let lines = render_first_show(
            &backend,
            "nvim-kit",
            &[(
                "https://github.com/dep/nvim-kit.git".to_owned(),
                COMMIT_A.to_owned(),
            )],
            Path::new("README.md"),
        )
        .expect("a tracked UTF-8 file must render its contents");

        let body = lines.join("\n");
        assert!(
            body.contains("hello") && body.contains("world"),
            "the file's text must be printed verbatim, got: {body:?}"
        );
    }

    #[test]
    fn render_show_refuses_non_utf8_binary_content() {
        let backend = ShowStore {
            file: FileOutcome::Bytes(vec![0xff, 0xfe, 0x00]),
            tree: TreeOutcome::Absent,
        };

        let err = render_first_show(
            &backend,
            "nvim-kit",
            &[(
                "https://github.com/dep/nvim-kit.git".to_owned(),
                COMMIT_A.to_owned(),
            )],
            Path::new("logo.png"),
        )
        .expect_err("binary content must be refused, never dumped as raw bytes");

        let msg = err.to_string().to_lowercase();
        assert!(
            msg.contains("utf-8") || msg.contains("utf8") || msg.contains("binary"),
            "the refusal must name the binary / non-UTF-8 reason, got: {msg:?}"
        );
        assert!(
            !msg.contains('\u{0}'),
            "the refusal must not leak the raw NUL byte of the content"
        );
    }

    #[test]
    fn render_show_errors_when_path_is_absent_at_commit() {
        let backend = ShowStore {
            file: FileOutcome::Absent,
            tree: TreeOutcome::Absent,
        };

        let err = render_first_show(
            &backend,
            "nvim-kit",
            &[(
                "https://github.com/dep/nvim-kit.git".to_owned(),
                COMMIT_A.to_owned(),
            )],
            Path::new("missing/thing.txt"),
        )
        .expect_err("a path absent at the commit must error, not print nothing");

        let msg = err.to_string();
        assert!(
            msg.contains("missing/thing.txt"),
            "the not-found error must name the requested path, got: {msg:?}"
        );
        assert!(
            msg.to_lowercase().contains("absent"),
            "a genuinely-absent path must report absence, got: {msg:?}"
        );
    }

    #[test]
    fn render_show_directs_to_sync_when_the_mirror_or_commit_is_missing() {
        let backend = ShowStore {
            file: FileOutcome::MirrorError,
            tree: TreeOutcome::MirrorError,
        };

        let err = render_first_show(
            &backend,
            "nvim-kit",
            &[(
                "https://github.com/dep/nvim-kit.git".to_owned(),
                COMMIT_A.to_owned(),
            )],
            Path::new("README.md"),
        )
        .expect_err("a missing mirror / commit must error, not pretend the path is absent");

        let msg = err.to_string();
        let lower = msg.to_lowercase();
        assert!(
            lower.contains("sync"),
            "a commit not yet in the mirror must direct the user to run `phora sync`, got: {msg:?}"
        );
        assert!(
            !lower.contains("absent"),
            "a missing mirror / commit is not a genuinely-absent path and must not be reported as absent, got: {msg:?}"
        );
    }

    #[test]
    fn render_show_lists_direct_directory_entries_ls_style() {
        let backend = ShowStore {
            file: FileOutcome::NotRegular,
            tree: TreeOutcome::Entries(vec![
                SourceDirectoryEntry {
                    path: SourcePath::new("d/a.txt").expect("safe fixture path"),
                    kind: SourceDirectoryEntryKind::File,
                },
                SourceDirectoryEntry {
                    path: SourcePath::new("d/sub").expect("safe fixture path"),
                    kind: SourceDirectoryEntryKind::Directory,
                },
                SourceDirectoryEntry {
                    path: SourcePath::new("d/weird name.txt").expect("safe fixture path"),
                    kind: SourceDirectoryEntryKind::File,
                },
            ]),
        };

        let lines = render_first_show(
            &backend,
            "nvim-kit",
            &[(
                "https://github.com/dep/nvim-kit.git".to_owned(),
                COMMIT_A.to_owned(),
            )],
            Path::new("d"),
        )
        .expect("a directory path must list its direct children");

        let body = lines.join("\n");
        let file_idx = lines
            .iter()
            .position(|l| l.contains("a.txt"))
            .unwrap_or_else(|| panic!("the listing must include the file `a.txt`, got: {body:?}"));
        let dir_idx = lines
            .iter()
            .position(|l| l.contains("sub"))
            .unwrap_or_else(|| {
                panic!("the listing must include the directory `sub`, got: {body:?}")
            });
        let file_line = &lines[file_idx];
        let dir_line = &lines[dir_idx];
        assert!(
            dir_line.trim_end().ends_with('/'),
            "an ls-style directory entry must be marked with a trailing slash, got: {dir_line:?}"
        );
        assert!(
            !file_line.trim_end().ends_with('/'),
            "a regular-file entry must NOT carry the directory slash, got: {file_line:?}"
        );
        assert!(
            file_idx < dir_idx,
            "the renderer must preserve the order `list_tree_at` returned (a.txt before sub), got: {body:?}"
        );
        assert!(
            lines.iter().any(|l| l.contains("weird name.txt")),
            "the renderer must emit each returned entry verbatim, including names with spaces, got: {body:?}"
        );
    }

    #[test]
    fn resolve_show_targets_requires_a_source_name() {
        let err = resolve_show_targets(None, None)
            .expect_err("`--show` without a source must error cleanly, mirroring `--revoke`");

        assert!(
            matches!(err, Error::Config(_)),
            "the missing-source failure must be a clean Error::Config, got: {err:?}"
        );
        let msg = err.to_string();
        assert!(
            msg.contains("--show") && msg.contains("source"),
            "the message must name `--show` and the missing source, got: {msg:?}"
        );
    }

    #[test]
    fn resolve_show_targets_prefers_the_candidate_commit_over_trusted() {
        let lock = Lock {
            candidate_hooks: vec![cand_commit("nvim-kit", "cand-inst", COMMIT_ONE)],
            trusted_hooks: vec![trusted_commit("nvim-kit", "trust-inst", COMMIT_B)],
            sources: vec![
                locked_dep(
                    "nvim-kit",
                    "cand-inst",
                    "https://github.com/dep/nvim-kit.git",
                    COMMIT_A,
                ),
                locked_dep(
                    "nvim-kit",
                    "trust-inst",
                    "https://github.com/dep/prior.git",
                    COMMIT_B,
                ),
            ],
            ..empty_lock()
        };

        let (_source, targets) = resolve_show_targets(Some(&lock), Some("nvim-kit"))
            .expect("a candidate commit must resolve a show target");
        let [(url, commit)] = targets.as_slice() else {
            panic!("one locked entry resolves one target, got: {targets:?}");
        };

        assert_eq!(
            commit, COMMIT_A,
            "the commit must come from the LockedSource of the CANDIDATE's dep_instance (COMMIT_A), \
             never from the candidate hook record's own commit field (COMMIT_ONE) — a present \
             candidate wins over the prior trusted instance"
        );
        assert_ne!(
            commit, COMMIT_ONE,
            "reading the candidate HOOK's commit instead of its LockedSource's is a regression"
        );
        assert_eq!(
            url, "https://github.com/dep/nvim-kit.git",
            "the remote URL must come from the LockedSource matching the candidate's dep_instance"
        );
    }

    #[test]
    fn resolve_show_targets_with_no_commit_directs_to_sync() {
        let lock = Lock {
            candidate_hooks: vec![cand_commit("nvim-kit", "inst", COMMIT_A)],
            trusted_hooks: Vec::new(),
            sources: vec![locked_dep(
                "nvim-kit",
                "inst",
                "https://github.com/dep/nvim-kit.git",
                "",
            )],
            ..empty_lock()
        };

        let err = resolve_show_targets(Some(&lock), Some("nvim-kit"))
            .expect_err("a LockedSource with no pinned commit cannot be shown offline");

        assert!(
            err.to_string().contains("sync"),
            "the user must be told to run `phora sync`, got: {err}"
        );
    }

    #[test]
    fn resolve_show_targets_refuses_to_guess_between_distinct_commits() {
        let lock = Lock {
            candidate_hooks: vec![
                cand_commit("nvim-kit", "inst-one", COMMIT_ONE),
                cand_commit("nvim-kit", "inst-two", COMMIT_TWO),
            ],
            sources: vec![
                locked_dep(
                    "nvim-kit",
                    "inst-one",
                    "https://github.com/dep/one.git",
                    COMMIT_ONE,
                ),
                locked_dep(
                    "nvim-kit",
                    "inst-two",
                    "https://github.com/dep/two.git",
                    COMMIT_TWO,
                ),
            ],
            ..empty_lock()
        };

        let err = resolve_show_targets(Some(&lock), Some("nvim-kit"))
            .expect_err("two distinct locked commits for one source must not be silently picked");

        let msg = err.to_string();
        assert!(
            msg.contains(&COMMIT_ONE[..12]) && msg.contains(&COMMIT_TWO[..12]),
            "the error must list BOTH locked commits so the user can disambiguate, got: {msg:?}"
        );
    }

    #[test]
    fn resolve_show_targets_treats_distinct_remotes_at_one_commit_as_ambiguous() {
        let lock = Lock {
            candidate_hooks: vec![
                cand_commit("nvim-kit", "inst-one", COMMIT_A),
                cand_commit("nvim-kit", "inst-two", COMMIT_A),
            ],
            sources: vec![
                locked_dep(
                    "nvim-kit",
                    "inst-one",
                    "https://github.com/dep/one.git",
                    COMMIT_A,
                ),
                locked_dep(
                    "nvim-kit",
                    "inst-two",
                    "https://github.com/dep/two.git",
                    COMMIT_A,
                ),
            ],
            ..empty_lock()
        };

        let err = resolve_show_targets(Some(&lock), Some("nvim-kit")).expect_err(
            "two distinct remotes at the SAME commit are genuinely ambiguous; --show must not \
             silently read the first mirror",
        );

        assert!(
            matches!(err, Error::Config(_)),
            "the ambiguity must be a clean Error::Config, got: {err:?}"
        );
    }

    #[test]
    fn resolve_show_targets_reads_own_files_first_then_bound_sources() {
        let lock = Lock {
            candidate_hooks: vec![cand_commit("tropos", "inst", COMMIT_A)],
            sources: vec![
                locked_dep(
                    "inst%loqui",
                    "inst",
                    "https://github.com/srnnkls/loqui.git",
                    COMMIT_B,
                ),
                locked_dep(
                    "inst%",
                    "inst",
                    "https://github.com/srnnkls/tropos.git",
                    COMMIT_A,
                ),
            ],
            ..empty_lock()
        };

        let (_source, targets) = resolve_show_targets(Some(&lock), Some("tropos"))
            .expect("one instance with several entries is not ambiguous");

        assert_eq!(
            targets,
            vec![
                (
                    "https://github.com/srnnkls/tropos.git".to_owned(),
                    COMMIT_A.to_owned()
                ),
                (
                    "https://github.com/srnnkls/loqui.git".to_owned(),
                    COMMIT_B.to_owned()
                ),
            ]
        );
    }
}