stegobench-cli 1.0.0

The stegobench command
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
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
// Author:  Daniel Iwugo
// Comment: Christ is King
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Daniel Iwugo
//
// Running a registered detector over images the user brought.
//
// WHY THIS EXISTS, GIVEN THAT THE PROJECT USED TO REFUSE IT
//
// `check` and `scan` were signposts that said Stegobench measures detectors
// against labelled images and cannot tell you whether something is hidden in
// an image of yours, and sent the reader to `describe` to copy a container
// command out by hand. The argument behind the refusal is sound and is kept
// in `help scope`: a detector run raw over one photograph prints pages of
// confident-looking candidate hits that are nearly all noise, and a detector
// right nine times in ten still calls one clean image in ten a hit.
//
// But that is an argument about how an answer must be presented, not about
// whether the command should exist, and `embed` had already crossed the same
// line in the other direction: it takes the user's own image and runs a
// registered embedder on it. So the project accepted "run one registered tool
// on one file of yours" for hiding and refused it for detecting, and the
// refusal was the only thing standing between a reader and the registry's
// whole point, which is not having to go and find these tools one at a time.
//
// WHAT KEEPS IT HONEST
//
// No result document. A `result-v1` is the output of a measurement against
// images whose answers were known in advance, and an examination is not one:
// there are no labels here, so there is no accuracy to report and nothing to
// put a confidence interval around. Keeping the two apart in the type system
// rather than in a warning is what stops an examination being quoted as a
// benchmark figure.

use std::path::{Path, PathBuf};
use std::time::Duration;

use stegobench_core::registry::{Entry, Kind};
use stegobench_plugin::{runner, Record, WorkItem};

/// What one detector said about one image.
#[derive(Debug, Clone, PartialEq)]
pub enum Answer {
    /// A number. Higher means more suspicious, and the scale is the tool's
    /// own: two detectors' numbers are not comparable with each other.
    Score(f64),
    /// Yes or no, from a tool that gives no number.
    Verdict(bool),
    /// The tool ran and produced nothing readable about this image.
    Failed(String),
}

/// What this file actually is, as a lowercase format name matching the
/// vocabulary a registry entry's `accepts.formats` uses.
///
/// Read from the first bytes rather than the extension, because an exhibit
/// arrives named however it arrived: a forensic examiner's `.jpg` from an
/// email attachment is whatever the sender made, and renaming a file does not
/// change what a detector will find when it opens it.
///
/// `None` where the bytes say nothing recognisable, and a `None` is treated
/// as applicable everywhere. Withholding a detector on a guess would be the
/// same fault in the other direction.
fn format_of(path: &Path) -> Option<String> {
    use std::io::Read;
    let mut head = [0u8; 12];
    let read = std::fs::File::open(path)
        .and_then(|mut f| f.read(&mut head))
        .ok()?;
    let head = &head[..read];
    let starts = |magic: &[u8]| head.starts_with(magic);
    if starts(b"\x89PNG\r\n\x1a\n") {
        return Some("png".into());
    }
    if starts(&[0xFF, 0xD8, 0xFF]) {
        return Some("jpeg".into());
    }
    if starts(b"BM") {
        return Some("bmp".into());
    }
    if starts(b"GIF8") {
        return Some("gif".into());
    }
    if starts(b"II*\x00") || starts(b"MM\x00*") {
        return Some("tiff".into());
    }
    if head.len() >= 12 && starts(b"RIFF") && &head[8..12] == b"WEBP" {
        return Some("webp".into());
    }
    if starts(b"P5") || starts(b"P6") {
        return Some("pnm".into());
    }
    None
}

/// Does this entry's own declaration say it reads this format?
///
/// An entry declaring nothing is asked about everything, which is the honest
/// reading of an empty list: nobody has written down what it reads.
fn reads_format(entry: &stegobench_core::registry::Entry, format: Option<&String>) -> bool {
    if entry.accepts.formats.is_empty() {
        return true;
    }
    let Some(format) = format else {
        return true;
    };
    entry.accepts.formats.iter().any(|declared| {
        let declared = declared.to_ascii_lowercase();
        declared == *format || (declared == "jpg" && format == "jpeg")
    })
}

impl Answer {
    /// The cell as a reader sees it.
    fn cell(&self) -> String {
        match self {
            Answer::Score(s) => format!("{s:.4}"),
            Answer::Verdict(true) => "stego".to_string(),
            Answer::Verdict(false) => "clean".to_string(),
            Answer::Failed(_) => "failed".to_string(),
        }
    }
}

/// One detector's column.
#[derive(Debug, Clone)]
pub struct Column {
    pub detector: String,
    /// `None` when the detector is not installed here, carrying why. The
    /// column is kept rather than dropped: a reader has to see that the tool
    /// was asked and could not answer, which is different from not asking.
    pub unavailable: Option<String>,
    /// One per image, in the order the images were given. Empty when the
    /// detector was unavailable.
    pub answers: Vec<Answer>,
}

/// Everything a run of this command produced.
#[derive(Debug, Clone)]
pub struct Examination {
    pub images: Vec<PathBuf>,
    pub columns: Vec<Column>,
    /// Detectors asked about an image whose format their own entry does not
    /// declare: the name, what it declares, and how many such images.
    ///
    /// Kept rather than refused, because the one real detection a forensic
    /// examiner got out of this command came from exactly that case. The
    /// answer stands and the caveat goes under the table.
    pub undeclared: Vec<(String, String, usize)>,
}

#[derive(Debug, thiserror::Error)]
pub enum ExamineError {
    #[error(
        "no detector called {name} is registered. `stegobench list detectors` \
         shows the ones that are"
    )]
    NotRegistered { name: String },
    #[error(
        "{name} is registered as an embedder, which hides a payload in an \
         image rather than answering questions about one. `stegobench list \
         detectors` shows what can answer"
    )]
    NotADetector { name: String },
    #[error("{} is not a file or a directory here", path.display())]
    NotAFile { path: PathBuf },
    #[error("could not read the directory {}: {source}", path.display())]
    UnreadableDirectory {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    #[error(
        "{} holds no image files, so there is nothing to ask about. Name the \
         images themselves if they are somewhere else, or check the extension: \
         a file this does not recognise as an image is skipped rather than \
         guessed at",
        path.display()
    )]
    NoImagesInDirectory { path: PathBuf },
    #[error(
        "{} holds more than {most} images. That is more than this will start a \
         detector for on one command, because a run of that size belongs in \
         `score` against a labelled corpus where it can be resumed. Name fewer \
         images, or a subdirectory",
        path.display()
    )]
    TooManyImages { path: PathBuf, most: usize },
    #[error("the same detector was asked for twice: {name}")]
    AskedTwice { name: String },
    #[error(
        "name at least one detector with --detector, because nothing here \
         guesses which tool you meant. `stegobench list detectors` names \
         every one registered"
    )]
    NoDetectorNamed,
    #[error("could not make a scratch directory for the run: {source}")]
    NoScratch {
        #[source]
        source: std::io::Error,
    },
    #[error(transparent)]
    Run(#[from] runner::RunError),
}

impl ExamineError {
    pub fn exit_code(&self) -> i32 {
        use stegobench_core::exit;
        match self {
            ExamineError::NotRegistered { .. }
            | ExamineError::NotADetector { .. }
            | ExamineError::AskedTwice { .. }
            | ExamineError::NoDetectorNamed => exit::USAGE,
            ExamineError::NotAFile { .. }
            | ExamineError::NoImagesInDirectory { .. }
            | ExamineError::TooManyImages { .. } => exit::PREFLIGHT_REFUSED,
            ExamineError::UnreadableDirectory { .. } => exit::FAILURE,
            ExamineError::NoScratch { .. } => exit::FAILURE,
            ExamineError::Run(_) => exit::PLUGIN_FAILED,
        }
    }

    /// A stable word a script can branch on, since the prose will be reworded
    /// the first time somebody is confused by it.
    pub fn reason(&self) -> &'static str {
        match self {
            ExamineError::NotRegistered { .. } => "not-registered",
            ExamineError::NotADetector { .. } => "not-a-detector",
            ExamineError::AskedTwice { .. } => "asked-twice",
            ExamineError::NoDetectorNamed => "no-detector-named",
            ExamineError::NotAFile { .. } => "not-a-file",
            ExamineError::UnreadableDirectory { .. } => "unreadable-directory",
            ExamineError::NoImagesInDirectory { .. } => "no-images-there",
            ExamineError::TooManyImages { .. } => "too-many-images",
            ExamineError::NoScratch { .. } => "no-scratch",
            ExamineError::Run(_) => "run-failed",
        }
    }
}

/// Everything the run needs that is not the images themselves.
pub struct Request<'a> {
    pub detectors: &'a [String],
    pub images: &'a [PathBuf],
    pub timeout: Duration,
    pub jobs: usize,
    pub adapter_roots: &'a [PathBuf],
    /// Where to keep what the tools printed, if anywhere.
    pub raw: Option<&'a Path>,
}

/// Collects the records in memory.
///
/// An examination is a handful of images rather than a corpus, so holding the
/// answers is bounded by what the user typed on the command line. A scoring
/// run streams to a file precisely because it is not.
struct Collect(Vec<Record>);

impl runner::Sink for Collect {
    fn write(&mut self, record: &Record) -> std::io::Result<()> {
        self.0.push(record.clone());
        Ok(())
    }
}

/// What a cell says when the detector could not be asked.
///
/// Not "not installed", because that is only one of the reasons: a tool can
/// also be here and unable to run on this machine, or here and declare no
/// command to drive it. The footnote under the table carries the specific
/// reason; the cell says only that there is no answer in it.
const UNAVAILABLE: &str = "unavailable";

/// How many entries a named directory is read before it is refused.
///
/// Bounded because a detector may take a second an image and somebody can
/// name a directory holding a hundred thousand of them by accident. The limit
/// refuses loudly rather than silently examining a prefix, which would be a
/// table that looks complete and is not.
const MOST_IMAGES_IN_A_DIRECTORY: usize = 10_000;

/// The images a named path stands for.
///
/// A file is itself. A directory is the image files directly inside it, in
/// sorted order, and nothing from any subdirectory: somebody who names a
/// folder means the pictures in it, and walking into subdirectories turns one
/// mistyped path into an hour of container starts.
///
/// Sorted so two runs over one directory produce the same table in the same
/// order, which readdir alone does not promise.
fn images_under(path: &Path) -> Result<Vec<PathBuf>, ExamineError> {
    if path.is_file() {
        return Ok(vec![path.to_path_buf()]);
    }
    if !path.is_dir() {
        return Err(ExamineError::NotAFile {
            path: path.to_path_buf(),
        });
    }
    let entries = std::fs::read_dir(path).map_err(|source| ExamineError::UnreadableDirectory {
        path: path.to_path_buf(),
        source,
    })?;
    let mut found = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|source| ExamineError::UnreadableDirectory {
            path: path.to_path_buf(),
            source,
        })?;
        let candidate = entry.path();
        if !candidate.is_file() {
            continue;
        }
        let looks_right = candidate
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| e.to_ascii_lowercase())
            .is_some_and(|e| crate::LOOKS_LIKE_AN_IMAGE.contains(&e.as_str()));
        if looks_right {
            found.push(candidate);
        }
        if found.len() > MOST_IMAGES_IN_A_DIRECTORY {
            return Err(ExamineError::TooManyImages {
                path: path.to_path_buf(),
                most: MOST_IMAGES_IN_A_DIRECTORY,
            });
        }
    }
    if found.is_empty() {
        return Err(ExamineError::NoImagesInDirectory {
            path: path.to_path_buf(),
        });
    }
    found.sort();
    Ok(found)
}

/// Checks the names and the files before any tool is started.
fn preflight<'r>(
    registry: &'r stegobench_core::registry::Registry,
    request: &Request<'_>,
) -> Result<Vec<&'r Entry>, ExamineError> {
    if request.detectors.is_empty() {
        return Err(ExamineError::NoDetectorNamed);
    }
    let mut entries = Vec::new();
    let mut seen: Vec<&str> = Vec::new();
    for name in request.detectors {
        if seen.contains(&name.as_str()) {
            return Err(ExamineError::AskedTwice { name: name.clone() });
        }
        seen.push(name);
        let Some(entry) = registry.entries.get(name) else {
            return Err(ExamineError::NotRegistered { name: name.clone() });
        };
        if entry.kind != Kind::Detector {
            return Err(ExamineError::NotADetector { name: name.clone() });
        }
        entries.push(entry);
    }
    Ok(entries)
}

/// Every path the user named, expanded, with duplicates kept out.
///
/// A duplicate is dropped rather than refused: naming a file and the
/// directory holding it is an easy thing to type and asking twice about one
/// image would put the same row in the table twice, which reads as two pieces
/// of evidence.
fn expand(named: &[PathBuf]) -> Result<Vec<PathBuf>, ExamineError> {
    let mut images: Vec<PathBuf> = Vec::new();
    for path in named {
        for image in images_under(path)? {
            let canonical = image.canonicalize().unwrap_or_else(|_| image.clone());
            if !images
                .iter()
                .any(|seen| seen.canonicalize().unwrap_or_else(|_| seen.clone()) == canonical)
            {
                images.push(image);
            }
        }
    }
    Ok(images)
}

/// Runs every named detector over every named image.
///
/// `progress` is called with a line per detector as it starts, because a
/// container pull or a cold start is long enough that silence reads as a hang.
pub fn run<P>(
    registry: &stegobench_core::registry::Registry,
    request: Request<'_>,
    mut progress: P,
) -> Result<Examination, ExamineError>
where
    P: FnMut(&str),
{
    let entries = preflight(registry, &request)?;
    let images = expand(request.images)?;

    let scratch = tempfile::tempdir().map_err(|source| ExamineError::NoScratch { source })?;
    let mut columns = Vec::with_capacity(entries.len());
    // Sniffed once for the whole run rather than once per detector: it opens
    // every file, and a seven detector examination would otherwise do it
    // seven times for no new information.
    let formats: Vec<Option<String>> = images.iter().map(|p| format_of(p)).collect();
    // Detector, what it declares, and how many images were outside that.
    let mut undeclared: Vec<(String, String, usize)> = Vec::new();

    for entry in entries {
        // The same question `score` and `doctor` ask, through the same
        // function, which also catches the tool that IS here and declares no
        // command to drive it. Asking only whether the code is present would
        // start that one once per image and record nothing against every one.
        if let Some(why) = crate::unavailable_reason(entry, request.adapter_roots) {
            // Shortened because this is a sentence, not a command to paste.
            let why = crate::shorten_digests(&why);
            progress(&format!("{} {why}, so it answered nothing", entry.name));
            columns.push(Column {
                detector: entry.name.clone(),
                unavailable: Some(why),
                answers: Vec::new(),
            });
            continue;
        }

        // A path inside a fresh scratch directory, so nothing resumes: an
        // examination is never continued from a previous one, and a stale
        // record would answer about a file the user is not asking about now.
        let records = scratch.path().join(format!("{}.records.jsonl", entry.name));
        // ASKED ABOUT EVERY IMAGE, AND WARNED ABOUT THE ONES OUTSIDE ITS
        // DECLARATION. Skipping them was tried first and it was wrong: zsteg
        // declares png and bmp, and the thing it found in the examiner's
        // JPEG exhibit was real, so refusing to ask threw away a true
        // detection to avoid an undefendable one. The reader needs both
        // facts, which means the answer and the caveat, not one of them.
        let outside: Vec<&PathBuf> = images
            .iter()
            .zip(&formats)
            .filter(|(_, f)| !reads_format(entry, f.as_ref()))
            .map(|(path, _)| path)
            .collect();
        let items: Vec<WorkItem> = images
            .iter()
            .map(|path| WorkItem {
                id: path.display().to_string(),
                path: path.clone(),
            })
            .collect();
        if outside.is_empty() {
            progress(&format!("{} over {} image(s)", entry.name, images.len()));
        } else {
            progress(&format!(
                "{} over {} image(s); it declares {} and {} of them are not",
                entry.name,
                images.len(),
                entry.accepts.formats.join(", "),
                outside.len()
            ));
        }
        undeclared.push((
            entry.name.clone(),
            entry.accepts.formats.join(", "),
            outside.len(),
        ));

        let items_asked = items.len();
        let mut sink = Collect(Vec::with_capacity(items_asked));
        let tally = runner::score(
            runner::Run {
                entry,
                already: &records,
                timeout: request.timeout,
                jobs: request.jobs,
                adapter_roots: request.adapter_roots,
                raw: runner::RawPolicy {
                    path: request.raw,
                    every: request.raw.is_some(),
                },
            },
            items,
            &mut sink,
            // The runner calls this at most once every thirty seconds, so a
            // handful of images never prints it and a directory of ten
            // thousand does not go silent for hours. Discarding it was the
            // whole observability rule missed in one empty closure.
            |t| progress(&heartbeat(&entry.name, t.seen(), items_asked, t.errored)),
        )?;
        if let Some(problem) = &tally.raw_problem {
            progress(problem);
        }

        columns.push(Column {
            detector: entry.name.clone(),
            unavailable: None,
            answers: sink.0.iter().map(answer_of).collect(),
        });
    }

    Ok(Examination {
        images,
        columns,
        undeclared: undeclared.into_iter().filter(|(_, _, n)| *n > 0).collect(),
    })
}

/// The line a long examination prints while it works.
///
/// A function rather than a closure body so it can be read and tested. The
/// wiring behind it cannot be unit tested without waiting thirty seconds for
/// the runner's heartbeat, so it was verified by running: forty images
/// against a detector sleeping a second each printed exactly one of these, at
/// thirty, reading "slow: 30 of 40 answered, 0 errored".
fn heartbeat(name: &str, answered: u64, total: usize, errored: u64) -> String {
    // "still working" because it reads as a summary otherwise, and it only
    // appears for a detector slow enough to need one. A forensic analyst saw
    // this line for one of four detectors, took it for that detector's final
    // tally, and had no idea why the other three had none.
    format!("still working: {name}, {answered} of {total} answered, {errored} errored")
}

/// The SHA-256 of a file, or `None` where it could not be read.
///
/// Unreadable is recorded rather than skipped: an exhibit that vanished
/// between the examination and the write is a thing the record should say.
fn digest_of(path: &Path) -> Option<String> {
    use sha2::{Digest, Sha256};
    let mut file = std::fs::File::open(path).ok()?;
    let mut hasher = Sha256::new();
    std::io::copy(&mut file, &mut hasher).ok()?;
    Some(format!("{:x}", hasher.finalize()))
}

/// A record as one cell.
///
/// A record carrying neither an answer nor an error cannot be written by the
/// runner, which treats that as incomplete, so the last arm is the record
/// having said only that it failed without saying why.
fn answer_of(record: &Record) -> Answer {
    match (record.score, record.verdict, &record.error) {
        (Some(s), _, _) => Answer::Score(s),
        (None, Some(v), _) => Answer::Verdict(v),
        (None, None, Some(e)) => Answer::Failed(e.clone()),
        (None, None, None) => Answer::Failed("no answer and no reason".to_string()),
    }
}

impl Examination {
    /// Whether every detector answered about every image.
    pub fn complete(&self) -> bool {
        self.columns.iter().all(|c| {
            c.unavailable.is_none()
                && c.answers.len() == self.images.len()
                && !c.answers.iter().any(|a| matches!(a, Answer::Failed(_)))
        })
    }

    /// The exit code this examination earns.
    ///
    /// A detector that is not here is a refusal: nothing is broken and
    /// installing it fixes it. A detector that ran and answered nothing is a
    /// failure, and the two are not the same thing to anybody automating this.
    ///
    /// NONE OF THEM BEING HERE IS A THIRD THING, AND IT USED TO LOOK LIKE THE
    /// FIRST.
    ///
    /// One detector of five missing and all five missing both returned 3, so
    /// a script could not tell a partial answer from an empty table. The
    /// empty table is the machine being unfit for the request rather than the
    /// request being partly refused, which is what 8 already means elsewhere
    /// in this binary: `doctor` returns it when nothing here is usable.
    pub fn exit_code(&self) -> i32 {
        use stegobench_core::exit;
        if self.columns.iter().any(|c| {
            c.answers.iter().any(|a| matches!(a, Answer::Failed(_)))
                || (c.unavailable.is_none() && c.answers.len() != self.images.len())
        }) {
            return exit::PLUGIN_FAILED;
        }
        let unavailable = self
            .columns
            .iter()
            .filter(|c| c.unavailable.is_some())
            .count();
        if unavailable > 0 && unavailable == self.columns.len() {
            return exit::ENVIRONMENT_UNFIT;
        }
        if unavailable > 0 {
            return exit::PREFLIGHT_REFUSED;
        }
        exit::OK
    }

    /// What each row of the table is called.
    ///
    /// The bare filename where that identifies the file, and as much of the
    /// path as it takes where it does not.
    ///
    /// RAISED BY A JOURNEY, 2026-10-02: a corpus names its samples by position
    /// inside each arm, so examining one cover and one stego image printed two
    /// rows both labelled `000000.png` and nothing said which was which. A
    /// table whose rows cannot be told apart is worse than one that prints
    /// long paths, because the reader does not know they are looking at two
    /// different files.
    fn row_labels(images: &[PathBuf]) -> Vec<String> {
        let base = |p: &PathBuf| {
            p.file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_else(|| p.display().to_string())
        };
        let mut labels: Vec<String> = images.iter().map(base).collect();
        // Decided on the ORIGINAL names and applied to every member of a
        // colliding group. Testing against the vector while mutating it
        // qualified one row of each pair and left the other bare, so the pair
        // that needed telling apart still read `covers/000000.png` beside a
        // plain `000000.png`.
        let colliding = |labels: &[String]| -> Vec<bool> {
            labels
                .iter()
                .map(|l| labels.iter().filter(|o| *o == l).count() > 1)
                .collect()
        };
        // One pass fits the shape that produces this: samples under one
        // directory per arm. Anything still colliding falls back to the whole
        // path, which is unambiguous by construction.
        for (i, _) in colliding(&labels)
            .into_iter()
            .enumerate()
            .filter(|(_, c)| *c)
            .collect::<Vec<_>>()
        {
            let path = &images[i];
            labels[i] = match path.parent().and_then(|p| p.file_name()) {
                Some(dir) => format!("{}/{}", dir.to_string_lossy(), base(path)),
                None => path.display().to_string(),
            };
        }
        for (i, _) in colliding(&labels)
            .into_iter()
            .enumerate()
            .filter(|(_, c)| *c)
            .collect::<Vec<_>>()
        {
            labels[i] = images[i].display().to_string();
        }
        labels
    }

    /// The table, one row per image and one column per detector.
    pub fn table(&self) -> String {
        let mut name_width = "image".len();
        let labels = Self::row_labels(&self.images);
        for label in &labels {
            name_width = name_width.max(label.chars().count());
        }

        let mut widths = Vec::with_capacity(self.columns.len());
        for column in &self.columns {
            let mut w = column.detector.chars().count();
            if column.unavailable.is_some() {
                w = w.max(UNAVAILABLE.len());
            }
            for answer in &column.answers {
                w = w.max(answer.cell().chars().count());
            }
            widths.push(w);
        }

        // Every line is trimmed at its end. Padding the last column leaves
        // trailing spaces on every row, which a diff flags, a linter flags,
        // and a reader copying the table out carries with them.
        let mut out = String::new();
        let mut line = format!("{:<name_width$}", "image");
        for (column, width) in self.columns.iter().zip(&widths) {
            line.push_str(&format!("  {:<width$}", column.detector, width = width));
        }
        out.push_str(line.trim_end());
        out.push('\n');

        for (row, label) in labels.iter().enumerate() {
            let mut line = format!("{label:<name_width$}");
            for (column, width) in self.columns.iter().zip(&widths) {
                let cell = match (&column.unavailable, column.answers.get(row)) {
                    (Some(_), _) => UNAVAILABLE.to_string(),
                    (None, Some(answer)) => answer.cell(),
                    (None, None) => "failed".to_string(),
                };
                line.push_str(&format!("  {cell:<width$}"));
            }
            out.push_str(line.trim_end());
            out.push('\n');
        }
        out
    }

    /// Whether any detector answered about any image.
    ///
    /// The caveat under the table is about what a number is worth, so a run
    /// where nothing ran must not carry it: a journey saw every cell read
    /// `unavailable` and the full "nothing above is an accuracy" paragraph
    /// printed underneath, and a caveat about a number nobody produced is how
    /// a reader learns to skip the caveat.
    pub fn answered_anything(&self) -> bool {
        self.columns
            .iter()
            .any(|c| c.answers.iter().any(|a| !matches!(a, Answer::Failed(_))))
    }

    /// The detectors that gave one answer to every image, where there was
    /// more than one image to answer about.
    ///
    /// RAISED BY A JOURNEY, 2026-10-02. zsteg answered the same thing in every
    /// row, and the persona could not tell "it found nothing in any of them"
    /// from "the adapter is not reading its output". Both produce an identical
    /// column, one is a result and the other is a broken tool, and the table
    /// said nothing. A column like this is not evidence either way until
    /// somebody has looked at what the tool actually printed, which is what
    /// `--raw` is for.
    ///
    /// Not raised for a single image, where one answer is the only possible
    /// shape, and not for a column that failed or was unavailable, which the
    /// cells already say.
    fn one_answer_for_everything(&self) -> Vec<&str> {
        if self.images.len() < 2 {
            return Vec::new();
        }
        self.columns
            .iter()
            .filter(|c| c.unavailable.is_none())
            .filter(|c| {
                let mut answered = c
                    .answers
                    .iter()
                    .filter(|a| !matches!(a, Answer::Failed(_)))
                    .map(|a| a.cell());
                match answered.next() {
                    Some(first) => {
                        c.answers.len() == self.images.len()
                            && answered.clone().count() + 1 == self.images.len()
                            && answered.all(|a| a == first)
                    }
                    None => false,
                }
            })
            .map(|c| c.detector.as_str())
            .collect()
    }

    /// The lines that go under the table.
    ///
    /// Short on purpose. The argument for why an examination is weak evidence
    /// is long and it lives in `help scope`, where somebody can read it when
    /// they want it; repeating it under every table trains people to skip it.
    pub fn footnotes(&self) -> Vec<String> {
        let mut notes = Vec::new();
        if self.answered_anything() {
            notes.push(
                "NOT A MEASUREMENT. No image here was labelled, so nothing above is an \
                 accuracy, and a figure from it is not quotable. `stegobench help scope` \
                 says why, and `stegobench score` is what produces a number you can defend."
                    .to_string(),
            );
        } else {
            notes.push(
                "NOTHING RAN, so the table above says nothing about these images. Not \
                 that they are clean: that nobody looked."
                    .to_string(),
            );
        }
        if self
            .columns
            .iter()
            .filter(|c| c.unavailable.is_none())
            .count()
            > 1
        {
            notes.push(
                "Each column is on its own scale. A higher number means more suspicious \
                 to that one detector, and two detectors' numbers do not compare with \
                 each other."
                    .to_string(),
            );
        }
        for column in &self.columns {
            if let Some(why) = &column.unavailable {
                notes.push(format!("{}: {why}", column.detector));
            }
        }
        for column in &self.columns {
            let failures = column
                .answers
                .iter()
                .filter(|a| matches!(a, Answer::Failed(_)))
                .count();
            if failures > 0 {
                notes.push(format!(
                    "{}: answered nothing about {failures} of {} image(s). \
                     `--raw <FILE>` keeps what it printed.",
                    column.detector,
                    self.images.len()
                ));
            }
        }
        for (detector, declares, count) in &self.undeclared {
            notes.push(format!(
                "{detector} reads {declares}, and {count} of these {} image(s) \
                 are not that. Its answers about those are outside what its \
                 own entry claims it supports, so treat them as a pointer to \
                 look rather than as a result.",
                self.images.len()
            ));
        }
        let flat = self.one_answer_for_everything();
        if !flat.is_empty() {
            notes.push(format!(
                "{} gave one answer to all {} image(s). That is what finding \
                 nothing looks like, and it is also what a misread output \
                 looks like; the table cannot tell you which. `--raw <FILE>` \
                 keeps what the tool printed, which can.",
                flat.join(", "),
                self.images.len()
            ));
        }
        notes
    }

    /// The JSON block, which is deliberately not a result document.
    pub fn to_json(&self) -> serde_json::Value {
        // EACH IMAGE BY PATH AND BY DIGEST.
        //
        // RAISED BY A JOURNEY, 2026-10-02. A forensic analyst listed "nothing
        // here hashes the exhibits" as one of two things that would stop this
        // command being used on casework: a table of filenames says nothing
        // about which bytes were examined, and a filename is the one piece of
        // an exhibit that changes most easily. They computed SHA-256 by hand
        // afterwards, which is work the tool was already doing nothing with.
        //
        // In `--json` rather than under the table, because a case file wants
        // a record and a terminal reader wants six rows they can read. A
        // digest that cannot be computed is recorded as null rather than
        // omitted, so a consumer can tell "not hashed" from "not present".
        let images: Vec<serde_json::Value> = self
            .images
            .iter()
            .map(|p| {
                serde_json::json!({
                    "path": p.display().to_string(),
                    "sha256": digest_of(p),
                })
            })
            .collect();
        let columns: Vec<serde_json::Value> = self
            .columns
            .iter()
            .map(|column| {
                let answers: Vec<serde_json::Value> = column
                    .answers
                    .iter()
                    .map(|a| match a {
                        Answer::Score(s) => serde_json::json!({ "score": s }),
                        Answer::Verdict(v) => serde_json::json!({ "verdict": v }),
                        Answer::Failed(why) => serde_json::json!({ "error": why }),
                    })
                    .collect();
                serde_json::json!({
                    "detector": column.detector,
                    "unavailable": column.unavailable,
                    "answers": answers,
                })
            })
            .collect();
        serde_json::json!({
            // Named so nothing mistakes this for a `result-v1`, which is the
            // output of a measurement against labelled images and carries an
            // accuracy. This carries answers and no accuracy.
            "kind": "examination",
            "measurement": false,
            // What asked, so a record read months later says which build
            // produced it. The same two facts a result document carries.
            "tool": env!("CARGO_PKG_NAME"),
            "tool_version": env!("CARGO_PKG_VERSION"),
            "images": images,
            "columns": columns,
            "undeclared_formats": self
                .undeclared
                .iter()
                .map(|(detector, declares, count)| {
                    serde_json::json!({
                        "detector": detector,
                        "declares": declares,
                        "images_outside": count,
                    })
                })
                .collect::<Vec<_>>(),
        })
    }
}

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

    fn examination(columns: Vec<Column>, images: usize) -> Examination {
        Examination {
            images: (0..images)
                .map(|i| PathBuf::from(format!("img{i}.png")))
                .collect(),
            columns,
            undeclared: Vec::new(),
        }
    }

    fn answered(detector: &str, answers: Vec<Answer>) -> Column {
        Column {
            detector: detector.to_string(),
            unavailable: None,
            answers,
        }
    }

    #[test]
    fn the_heartbeat_names_the_detector_and_both_counts() {
        // All four values, because a progress line that drops the total is
        // the one that leaves somebody unable to tell a slow run from a
        // stuck one.
        let line = heartbeat("zsteg", 30, 40, 2);
        assert!(line.contains("zsteg"), "{line}");
        assert!(line.contains("30 of 40"), "{line}");
        assert!(line.contains("2 errored"), "{line}");
    }

    #[test]
    fn a_score_and_a_verdict_render_differently() {
        assert_eq!(Answer::Score(0.5).cell(), "0.5000");
        assert_eq!(Answer::Verdict(true).cell(), "stego");
        assert_eq!(Answer::Verdict(false).cell(), "clean");
        assert_eq!(Answer::Failed("why".into()).cell(), "failed");
    }

    #[test]
    fn a_record_becomes_the_answer_it_carries() {
        let base = Record {
            id: "a".into(),
            score: None,
            verdict: None,
            error: None,
            elapsed_ms: None,
        };
        assert_eq!(
            answer_of(&Record {
                score: Some(0.25),
                ..base.clone()
            }),
            Answer::Score(0.25)
        );
        assert_eq!(
            answer_of(&Record {
                verdict: Some(true),
                ..base.clone()
            }),
            Answer::Verdict(true)
        );
        assert_eq!(
            answer_of(&Record {
                error: Some("boom".into()),
                ..base.clone()
            }),
            Answer::Failed("boom".into())
        );
        // A record with neither cannot be written by the runner, and if one
        // ever is, it says so rather than reading as an answer.
        assert_eq!(
            answer_of(&base),
            Answer::Failed("no answer and no reason".into())
        );
    }

    #[test]
    fn a_score_wins_over_a_verdict_in_the_same_record() {
        // A plugin should send one or the other. Given both, the number is
        // kept, because a number carries strictly more than the yes or no a
        // threshold would turn it into.
        let both = Record {
            id: "a".into(),
            score: Some(0.9),
            verdict: Some(false),
            error: None,
            elapsed_ms: None,
        };
        assert_eq!(answer_of(&both), Answer::Score(0.9));
    }

    #[test]
    fn every_detector_answering_exits_zero() {
        let e = examination(
            vec![
                answered("alfa", vec![Answer::Score(0.1), Answer::Score(0.2)]),
                answered("bravo", vec![Answer::Verdict(true), Answer::Verdict(false)]),
            ],
            2,
        );
        assert!(e.complete());
        assert_eq!(e.exit_code(), stegobench_core::exit::OK);
    }

    #[test]
    fn a_detector_that_is_not_here_is_a_refusal_rather_than_a_failure() {
        let e = examination(
            vec![
                answered("alfa", vec![Answer::Score(0.1)]),
                Column {
                    detector: "bravo".to_string(),
                    unavailable: Some("no container runtime".to_string()),
                    answers: Vec::new(),
                },
            ],
            1,
        );
        assert!(!e.complete());
        assert_eq!(e.exit_code(), stegobench_core::exit::PREFLIGHT_REFUSED);
        assert!(e
            .footnotes()
            .iter()
            .any(|n| n.contains("no container runtime")));
    }

    #[test]
    fn a_detector_that_answered_nothing_is_a_failure() {
        let e = examination(
            vec![answered(
                "alfa",
                vec![Answer::Score(0.1), Answer::Failed("timed out".into())],
            )],
            2,
        );
        assert!(!e.complete());
        assert_eq!(e.exit_code(), stegobench_core::exit::PLUGIN_FAILED);
    }

    #[test]
    fn a_short_column_is_a_failure_even_with_no_error_recorded() {
        // Fewer answers than images means the run stopped early, and reading
        // the missing rows as "nothing suspicious" is the worst thing this
        // command could do.
        let e = examination(vec![answered("alfa", vec![Answer::Score(0.1)])], 3);
        assert!(!e.complete());
        assert_eq!(e.exit_code(), stegobench_core::exit::PLUGIN_FAILED);
    }

    /// The distinction a script needs and did not have: some missing against
    /// all missing.
    #[test]
    fn nothing_being_installed_is_told_apart_from_something_being_installed() {
        let missing = |name: &str| Column {
            detector: name.to_string(),
            unavailable: Some("not installed".to_string()),
            answers: Vec::new(),
        };

        let some = examination(
            vec![answered("alfa", vec![Answer::Score(0.1)]), missing("bravo")],
            1,
        );
        assert_eq!(some.exit_code(), stegobench_core::exit::PREFLIGHT_REFUSED);

        let none = examination(vec![missing("alfa"), missing("bravo")], 1);
        assert_eq!(none.exit_code(), stegobench_core::exit::ENVIRONMENT_UNFIT);
        assert_ne!(some.exit_code(), none.exit_code());
    }

    #[test]
    fn a_failure_outranks_an_unavailable_detector_in_the_exit_code() {
        let e = examination(
            vec![
                answered("alfa", vec![Answer::Failed("boom".into())]),
                Column {
                    detector: "bravo".to_string(),
                    unavailable: Some("not installed".to_string()),
                    answers: Vec::new(),
                },
            ],
            1,
        );
        assert_eq!(e.exit_code(), stegobench_core::exit::PLUGIN_FAILED);
    }

    /// A corpus names its samples by position inside each arm, so two files
    /// from two arms share a basename and the table had two rows called
    /// `000000.png`.
    #[test]
    fn two_images_sharing_a_basename_get_rows_a_reader_can_tell_apart() {
        let e = Examination {
            images: vec![
                PathBuf::from("corpus/covers/000000.png"),
                PathBuf::from("corpus/lsb-0400/000000.png"),
                PathBuf::from("corpus/covers/000001.png"),
            ],
            columns: vec![answered(
                "alfa",
                vec![Answer::Score(0.1), Answer::Score(0.2), Answer::Score(0.3)],
            )],
            undeclared: Vec::new(),
        };
        let table = e.table();
        assert!(
            table.contains("covers/000000.png") && table.contains("lsb-0400/000000.png"),
            "BOTH sides of the collision have to be qualified, or the reader \
             still cannot tell which row is which:\n{table}"
        );
        // The row that was never ambiguous keeps its short name: qualifying
        // everything would make every table longer to fix two rows.
        assert!(
            table
                .lines()
                .any(|l| l.starts_with("000001.png") || l.starts_with("000001.png ")),
            "a name that collided with nothing was lengthened anyway:\n{table}"
        );
    }

    /// An identical column is a result and a broken parser at the same time,
    /// and the table cannot tell them apart. Saying so is the whole fix.
    #[test]
    fn one_answer_for_every_image_is_called_out_under_the_table() {
        let flat = examination(
            vec![answered(
                "zsteg",
                vec![Answer::Verdict(false), Answer::Verdict(false)],
            )],
            2,
        );
        let note = flat
            .footnotes()
            .into_iter()
            .find(|n| n.contains("one answer to all"))
            .expect("a column with one answer in every row is called out");
        assert!(note.contains("zsteg"), "{note}");
        assert!(
            note.contains("--raw"),
            "the note has to say what to do next"
        );

        // A column that varies is not called out, or the note becomes
        // furniture nobody reads.
        let varied = examination(
            vec![answered(
                "zsteg",
                vec![Answer::Verdict(false), Answer::Verdict(true)],
            )],
            2,
        );
        assert!(
            !varied
                .footnotes()
                .iter()
                .any(|n| n.contains("one answer to all")),
            "a column with two different answers was called out as flat"
        );

        // One image is one answer by necessity, and saying so would be noise
        // on every single-image examination.
        let alone = examination(vec![answered("zsteg", vec![Answer::Verdict(false)])], 1);
        assert!(
            !alone
                .footnotes()
                .iter()
                .any(|n| n.contains("one answer to all")),
            "a single image examination carried the flat-column note"
        );
    }

    /// A tool asked about a format its own entry does not claim has not given
    /// an answer anybody can defend, and the table used to say nothing.
    ///
    /// RAISED BY A JOURNEY, 2026-10-02. zsteg declares png and bmp and was
    /// handed two JPEGs; a forensic analyst listed it as the second thing a
    /// defence expert would open with. The answer is KEPT rather than
    /// withheld, because the one real detection that examination produced was
    /// zsteg finding appended bytes in one of those JPEGs. Refusing to ask
    /// would have thrown away a true positive to avoid an awkward one.
    #[test]
    fn an_answer_outside_a_detector_s_declared_formats_is_caveated_not_hidden() {
        let e = Examination {
            images: vec![
                PathBuf::from("EXH-003-scan.png"),
                PathBuf::from("EXH-005-attachment.jpg"),
            ],
            columns: vec![answered(
                "zsteg",
                vec![Answer::Verdict(true), Answer::Verdict(true)],
            )],
            undeclared: vec![("zsteg".to_string(), "png, bmp".to_string(), 1)],
        };
        // The answer is still there. This is the half that matters most and
        // the half an over-strict fix would have removed.
        let table = e.table();
        assert!(
            table.lines().filter(|l| l.contains("stego")).count() >= 2,
            "the detection was dropped instead of caveated:\n{table}"
        );
        let note = e
            .footnotes()
            .into_iter()
            .find(|n| n.contains("png, bmp"))
            .expect("the caveat names what the detector actually declares");
        assert!(note.contains("zsteg"), "{note}");
        assert!(
            note.contains("1 of these 2"),
            "it has to say how many were outside: {note}"
        );

        // Nothing outside the declaration means no note at all, or the caveat
        // becomes furniture under every table.
        let clean = Examination {
            images: vec![PathBuf::from("a.png")],
            columns: vec![answered("zsteg", vec![Answer::Verdict(false)])],
            undeclared: Vec::new(),
        };
        assert!(
            !clean.footnotes().iter().any(|n| n.contains("outside what")),
            "a run entirely inside the declarations carried the caveat anyway"
        );
    }

    /// An examination that names its exhibits only by filename is not a
    /// record of anything.
    ///
    /// RAISED BY A JOURNEY, 2026-10-02: a forensic analyst named the absence
    /// of exhibit hashes as one of two things that would stop this command
    /// being used on casework, and hashed the six files by hand afterwards.
    #[test]
    fn the_json_record_names_every_image_by_digest_and_says_what_produced_it() {
        let dir = tempfile::tempdir().expect("tmp");
        let image = dir.path().join("EXH-001.png");
        std::fs::write(&image, b"\x89PNG\r\n\x1a\nexhibit bytes").expect("written");
        let e = Examination {
            images: vec![image.clone()],
            columns: vec![answered("zsteg", vec![Answer::Verdict(false)])],
            undeclared: Vec::new(),
        };
        let json = e.to_json();
        let first = &json["images"][0];
        assert_eq!(
            first["path"].as_str().expect("a path"),
            image.display().to_string()
        );
        // The digest of those exact bytes, computed independently of the
        // code under test rather than copied from its output.
        let expected = {
            use sha2::{Digest, Sha256};
            let mut h = Sha256::new();
            h.update(std::fs::read(&image).expect("read"));
            format!("{:x}", h.finalize())
        };
        assert_eq!(
            first["sha256"].as_str().expect("a digest"),
            expected,
            "the record has to name the bytes, not the filename"
        );
        assert_eq!(json["tool_version"], env!("CARGO_PKG_VERSION"));

        // A file that went away between the examination and the write is
        // recorded as unhashed rather than dropped.
        let gone = Examination {
            images: vec![dir.path().join("never-existed.png")],
            columns: vec![answered("zsteg", vec![Answer::Verdict(false)])],
            undeclared: Vec::new(),
        };
        assert!(
            gone.to_json()["images"][0]["sha256"].is_null(),
            "an unreadable exhibit must be null, not missing"
        );
    }

    #[test]
    fn the_table_aligns_on_the_longest_name_and_cell() {
        let e = Examination {
            images: vec![
                PathBuf::from("/some/where/a-long-filename.png"),
                PathBuf::from("/some/where/b.png"),
            ],
            columns: vec![answered(
                "aletheia-spa",
                vec![Answer::Score(0.1234), Answer::Verdict(true)],
            )],
            undeclared: Vec::new(),
        };
        let table = e.table();
        let lines: Vec<&str> = table.lines().collect();
        assert_eq!(lines.len(), 3);
        // The row label is the file name, not the whole path: a reader gave
        // these paths and a column of identical directory prefixes is noise.
        assert!(lines[1].starts_with("a-long-filename.png"));
        assert!(lines[2].starts_with("b.png"));
        // Every line is padded to the same width before the first cell.
        let at = |line: &str| line.find("0.1234").or_else(|| line.find("stego"));
        assert_eq!(at(lines[1]), at(lines[2]));
        // And no line carries trailing whitespace, which the last column's
        // padding produced until it was trimmed.
        for line in &lines {
            assert_eq!(*line, line.trim_end(), "trailing space on {line:?}");
        }
    }

    #[test]
    fn the_not_a_measurement_note_is_always_there() {
        let e = examination(vec![answered("alfa", vec![Answer::Score(0.1)])], 1);
        let notes = e.footnotes();
        assert!(notes[0].contains("NOT A MEASUREMENT"));
        assert!(notes[0].contains("not quotable"));
        // One detector needs no warning about comparing scales.
        assert!(!notes.iter().any(|n| n.contains("own scale")));
    }

    /// A table where nothing ran must not carry the caveat about what a
    /// number is worth, and must say what it actually means.
    #[test]
    fn a_table_where_nothing_ran_says_so_instead_of_quoting_the_caveat() {
        let e = examination(
            vec![Column {
                detector: "alfa".to_string(),
                unavailable: Some("not pulled".to_string()),
                answers: Vec::new(),
            }],
            2,
        );
        assert!(!e.answered_anything());
        let notes = e.footnotes();
        assert!(notes[0].contains("NOTHING RAN"), "{notes:?}");
        // The dangerous misreading is "no hits, so they are clean", and this
        // is the one sentence standing between a reader and it.
        assert!(notes[0].contains("Not that they are clean"), "{notes:?}");
        assert!(
            !notes.iter().any(|n| n.contains("NOT A MEASUREMENT")),
            "a caveat about a number nobody produced: {notes:?}"
        );
    }

    #[test]
    fn a_table_with_one_real_answer_still_carries_the_caveat() {
        let e = examination(
            vec![
                answered("alfa", vec![Answer::Score(0.1), Answer::Score(0.2)]),
                Column {
                    detector: "bravo".to_string(),
                    unavailable: Some("not pulled".to_string()),
                    answers: Vec::new(),
                },
            ],
            2,
        );
        assert!(e.answered_anything());
        assert!(e.footnotes()[0].contains("NOT A MEASUREMENT"));
    }

    /// A column of failures is not an answer either.
    #[test]
    fn errors_alone_do_not_count_as_having_answered() {
        let e = examination(
            vec![answered("alfa", vec![Answer::Failed("boom".into())])],
            1,
        );
        assert!(!e.answered_anything());
        assert!(e.footnotes()[0].contains("NOTHING RAN"));
    }

    /// Naming no detector reaches our refusal, through the code that makes
    /// it, rather than being asserted about a value constructed in the test.
    ///
    /// The first version of this test built `ExamineError::NoDetectorNamed`
    /// by hand and checked its wording, and a mutation check found that
    /// deleting the guard in `preflight` broke nothing: the test passed while
    /// the behaviour was gone. This one runs the command.
    #[test]
    fn naming_no_detector_is_our_refusal_rather_than_claps() {
        let registry = stegobench_core::registry::Registry::default();
        let error = run(
            &registry,
            Request {
                detectors: &[],
                images: &[PathBuf::from("some-image.png")],
                timeout: Duration::from_secs(1),
                jobs: 1,
                adapter_roots: &[],
                raw: None,
            },
            |_| {},
        )
        .expect_err("naming no detector is refused");

        assert!(
            matches!(error, ExamineError::NoDetectorNamed),
            "refused for the wrong reason: {error}"
        );
        assert_eq!(error.exit_code(), stegobench_core::exit::USAGE);
        assert_eq!(error.reason(), "no-detector-named");
        let said = error.to_string();
        assert!(said.contains("--detector"), "{said}");
        assert!(said.contains("list detectors"), "{said}");
        assert!(
            !said.contains("required arguments"),
            "still clap's wording: {said}"
        );
    }

    /// And it is refused BEFORE the images are looked at, so a reader who
    /// typed neither is told about the detector rather than about a path.
    #[test]
    fn the_missing_detector_is_named_before_a_missing_file_is() {
        let registry = stegobench_core::registry::Registry::default();
        let error = run(
            &registry,
            Request {
                detectors: &[],
                images: &[PathBuf::from("/no/such/file.png")],
                timeout: Duration::from_secs(1),
                jobs: 1,
                adapter_roots: &[],
                raw: None,
            },
            |_| {},
        )
        .expect_err("refused");
        assert_eq!(error.reason(), "no-detector-named", "{error}");
    }

    #[test]
    fn two_detectors_are_warned_not_to_be_compared_directly() {
        let e = examination(
            vec![
                answered("alfa", vec![Answer::Score(0.1)]),
                answered("bravo", vec![Answer::Score(0.9)]),
            ],
            1,
        );
        assert!(e.footnotes().iter().any(|n| n.contains("own scale")));
    }

    #[test]
    fn one_detector_plus_an_unavailable_one_is_not_two_scales() {
        // The warning is about comparing numbers, and a column with no
        // numbers in it gives nobody anything to compare.
        let e = examination(
            vec![
                answered("alfa", vec![Answer::Score(0.1)]),
                Column {
                    detector: "bravo".to_string(),
                    unavailable: Some("not installed".to_string()),
                    answers: Vec::new(),
                },
            ],
            1,
        );
        assert!(!e.footnotes().iter().any(|n| n.contains("own scale")));
    }

    #[test]
    fn the_json_says_it_is_not_a_measurement() {
        let e = examination(vec![answered("alfa", vec![Answer::Score(0.1)])], 1);
        let json = e.to_json();
        assert_eq!(json["kind"], "examination");
        assert_eq!(json["measurement"], false);
        // And carries no field a result document would carry.
        assert!(json.get("metrics").is_none());
        assert!(json.get("auc").is_none());
    }

    #[test]
    fn every_error_carries_its_own_exit_code_and_stable_word() {
        use stegobench_core::exit;
        let cases = [
            (
                ExamineError::NotRegistered { name: "x".into() },
                exit::USAGE,
                "not-registered",
            ),
            (
                ExamineError::NotADetector { name: "x".into() },
                exit::USAGE,
                "not-a-detector",
            ),
            (
                ExamineError::AskedTwice { name: "x".into() },
                exit::USAGE,
                "asked-twice",
            ),
            (
                ExamineError::NotAFile {
                    path: PathBuf::from("x"),
                },
                exit::PREFLIGHT_REFUSED,
                "not-a-file",
            ),
        ];
        for (error, code, reason) in cases {
            assert_eq!(error.exit_code(), code, "{error}");
            assert_eq!(error.reason(), reason);
            // And every one says something, since a refusal with no reason is
            // the same as a crash to whoever reads it.
            assert!(!error.to_string().is_empty());
        }
    }

    #[test]
    fn asking_for_a_detector_twice_is_refused_rather_than_run_twice() {
        // Two identical columns would make the table look like corroboration
        // from two independent tools.
        let e = ExamineError::AskedTwice {
            name: "zsteg".into(),
        };
        assert!(e.to_string().contains("twice"));
        assert_eq!(e.exit_code(), stegobench_core::exit::USAGE);
    }
}

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

    fn tree(files: &[&str]) -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tmp");
        for name in files {
            let path = dir.path().join(name);
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).expect("mkdir");
            }
            std::fs::write(&path, b"x").expect("write");
        }
        dir
    }

    #[test]
    fn a_named_file_is_itself() {
        let dir = tree(&["a.png"]);
        let file = dir.path().join("a.png");
        assert_eq!(images_under(&file).expect("found"), vec![file.clone()]);
    }

    #[test]
    fn a_named_directory_becomes_the_images_in_it_sorted() {
        let dir = tree(&["c.png", "a.jpg", "b.bmp", "notes.txt", "run.sh"]);
        let found = images_under(dir.path()).expect("found");
        let names: Vec<String> = found
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().to_string())
            .collect();
        // Sorted, so two runs over one directory give the same table in the
        // same order. Readdir alone does not promise that.
        assert_eq!(names, vec!["a.jpg", "b.bmp", "c.png"]);
    }

    #[test]
    fn an_extension_in_capitals_is_still_an_image() {
        let dir = tree(&["PHOTO.JPG", "other.PNG"]);
        assert_eq!(images_under(dir.path()).expect("found").len(), 2);
    }

    #[test]
    fn a_subdirectory_is_not_walked_into() {
        // One mistyped path should not become an hour of container starts.
        let dir = tree(&["top.png", "deeper/inside.png"]);
        let found = images_under(dir.path()).expect("found");
        assert_eq!(found.len(), 1);
        assert!(found[0].ends_with("top.png"));
    }

    #[test]
    fn a_directory_with_no_images_is_refused_rather_than_examined_as_empty() {
        let dir = tree(&["notes.txt"]);
        let e = images_under(dir.path()).expect_err("refused");
        assert_eq!(e.reason(), "no-images-there");
        assert_eq!(e.exit_code(), stegobench_core::exit::PREFLIGHT_REFUSED);
    }

    #[test]
    fn a_path_that_is_neither_is_the_same_refusal_as_before() {
        let dir = tree(&[]);
        let e = images_under(&dir.path().join("nothing-here.png")).expect_err("refused");
        assert_eq!(e.reason(), "not-a-file");
    }

    #[test]
    fn naming_a_file_and_its_directory_asks_about_it_once() {
        // Twice in the table would read as two pieces of evidence.
        let dir = tree(&["a.png", "b.png"]);
        let images =
            expand(&[dir.path().to_path_buf(), dir.path().join("a.png")]).expect("expanded");
        assert_eq!(images.len(), 2, "{images:?}");
    }

    #[test]
    fn the_same_file_named_twice_is_asked_about_once() {
        let dir = tree(&["a.png"]);
        let file = dir.path().join("a.png");
        let images = expand(&[file.clone(), file]).expect("expanded");
        assert_eq!(images.len(), 1);
    }

    #[test]
    fn two_directories_are_both_expanded_in_the_order_they_were_named() {
        let first = tree(&["z.png"]);
        let second = tree(&["a.png"]);
        let images =
            expand(&[first.path().to_path_buf(), second.path().to_path_buf()]).expect("expanded");
        // Within a directory it sorts; across directories it keeps what the
        // user typed, because that is the order they listed them in.
        assert!(images[0].ends_with("z.png"), "{images:?}");
        assert!(images[1].ends_with("a.png"), "{images:?}");
    }

    #[test]
    fn one_bad_path_refuses_the_whole_command_rather_than_examining_the_rest() {
        // A partial table that looks complete is the worst outcome here.
        let dir = tree(&["a.png"]);
        let e = expand(&[dir.path().to_path_buf(), PathBuf::from("/no/such/place")])
            .expect_err("refused");
        assert_eq!(e.reason(), "not-a-file");
    }
}