flpdf-cli 0.10.0

Command-line tools for flpdf, mirroring qpdf inspection and rewrite subcommands.
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
//! Shared test harness for compat matrix tests.
//!
//! Provides types and helpers to run (fixture, flag-set) tuples through both
//! `qpdf` and `flpdf`, route outputs through [`Comparator`]s, and collect
//! structured [`MatrixReport`]s.

pub mod comparators;
pub mod json_diff;
pub use comparators::{QpdfJsonComparator, StructuralComparator};

use std::path::{Path, PathBuf};
use std::process::Command as ShellCommand;

use assert_cmd::Command as CargoCommand;
use tempfile::TempDir;

// ---------------------------------------------------------------------------
// Fixture
// ---------------------------------------------------------------------------

/// A named PDF fixture under `tests/fixtures/compat/`.
#[derive(Debug, Clone)]
pub struct Fixture {
    /// Short name used in reports (e.g. `"one-page.pdf"`).
    pub name: String,
    /// Absolute path to the fixture file.
    pub path: PathBuf,
}

impl Fixture {
    /// Construct a fixture from its file name, resolved relative to
    /// `CARGO_MANIFEST_DIR/../../tests/fixtures/compat/`.
    pub fn new(name: impl Into<String>) -> Self {
        let name = name.into();
        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/compat")
            .join(&name);
        Self { name, path }
    }
}

// ---------------------------------------------------------------------------
// FlagSet
// ---------------------------------------------------------------------------

/// A named group of flags to pass to both tools.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FlagSet {
    /// No extra flags — plain rewrite.
    Plain,
    /// `--static-id` (deterministic ID for testing).
    StaticId,
    /// `--linearize` (fast web view).
    Linearize,
}

impl FlagSet {
    /// Human-readable identifier used in reports.
    pub fn name(&self) -> &'static str {
        match self {
            FlagSet::Plain => "plain",
            FlagSet::StaticId => "static-id",
            FlagSet::Linearize => "linearize",
        }
    }

    /// Extra CLI args to append to `flpdf rewrite <in> <out>`.
    pub fn flpdf_args(&self) -> Vec<&'static str> {
        match self {
            FlagSet::Plain => vec![],
            FlagSet::StaticId => vec!["--static-id"],
            FlagSet::Linearize => vec!["--linearize"],
        }
    }

    /// Extra CLI args to append to `qpdf <in> <out>`.
    pub fn qpdf_args(&self) -> Vec<&'static str> {
        match self {
            FlagSet::Plain => vec![],
            FlagSet::StaticId => vec!["--static-id"],
            FlagSet::Linearize => vec!["--linearize"],
        }
    }
}

// ---------------------------------------------------------------------------
// Tuple
// ---------------------------------------------------------------------------

/// A single (fixture, flag-set) pair that forms one row in the matrix.
#[derive(Debug, Clone)]
pub struct Tuple {
    pub fixture: Fixture,
    pub flag_set: FlagSet,
}

// ---------------------------------------------------------------------------
// RunOutputs
// ---------------------------------------------------------------------------

/// The output produced when running one tool on one tuple.
// Different matrix tests inspect different output fields; retain the complete
// shared record rather than duplicating one narrower record per binary.
#[derive(Debug, Clone)]
pub struct ToolOutput {
    /// Whether the process exited successfully.
    #[allow(dead_code)]
    pub success: bool,
    /// The process exit code (None if the process could not be spawned).
    #[allow(dead_code)]
    pub exit_code: Option<i32>,
    /// stdout captured from the process.
    #[allow(dead_code)]
    pub stdout: Vec<u8>,
    /// stderr captured from the process.
    #[allow(dead_code)]
    pub stderr: Vec<u8>,
    /// Bytes of the output file, if the process succeeded and produced one.
    pub output_bytes: Option<Vec<u8>>,
}

/// Both tools' outputs for one tuple.
#[derive(Debug, Clone)]
pub struct RunOutputs {
    pub qpdf: ToolOutput,
    pub flpdf: ToolOutput,
}

// ---------------------------------------------------------------------------
// Comparator trait
// ---------------------------------------------------------------------------

/// The outcome of one comparator's evaluation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ComparatorResult {
    /// The outputs matched according to this comparator's criterion.
    Match,
    /// The outputs differed.  `reason` describes the divergence.
    Diverge { reason: String },
    /// The comparator could not run (e.g. one or both tools failed).
    Skipped { reason: String },
}

impl ComparatorResult {
    // Some matrix binaries use structural matching directly and do not need
    // this convenience predicate.
    #[allow(dead_code)]
    pub fn is_pass(&self) -> bool {
        matches!(self, Self::Match)
    }
}

/// A named comparator that compares `RunOutputs` for a single tuple.
pub trait Comparator {
    /// Stable, human-readable identifier (e.g. `"byte-equal"`).
    fn name(&self) -> &str;
    /// Evaluate the outputs and return a result.
    fn compare(&self, outputs: &RunOutputs) -> ComparatorResult;
}

// ---------------------------------------------------------------------------
// Built-in comparators
// ---------------------------------------------------------------------------

/// Checks that both tools produced exactly the same output bytes.
pub struct ByteComparator;

impl Comparator for ByteComparator {
    fn name(&self) -> &str {
        "byte-equal"
    }

    fn compare(&self, outputs: &RunOutputs) -> ComparatorResult {
        let (Some(qpdf_bytes), Some(flpdf_bytes)) = (
            outputs.qpdf.output_bytes.as_ref(),
            outputs.flpdf.output_bytes.as_ref(),
        ) else {
            let reason =
                if outputs.qpdf.output_bytes.is_none() && outputs.flpdf.output_bytes.is_none() {
                    "both tools produced no output".to_string()
                } else if outputs.qpdf.output_bytes.is_none() {
                    "qpdf produced no output".to_string()
                } else {
                    "flpdf produced no output".to_string()
                };
            return ComparatorResult::Skipped { reason };
        };

        if qpdf_bytes == flpdf_bytes {
            return ComparatorResult::Match;
        }

        let reason = if qpdf_bytes.len() != flpdf_bytes.len() {
            format!(
                "byte lengths differ: qpdf={} flpdf={}",
                qpdf_bytes.len(),
                flpdf_bytes.len()
            )
        } else {
            let first_diff = qpdf_bytes
                .iter()
                .zip(flpdf_bytes.iter())
                .position(|(q, f)| q != f)
                .expect("byte slices are unequal but no differing position found");
            format!(
                "bytes differ at offset {} (len={}): qpdf=0x{:02x} flpdf=0x{:02x}",
                first_diff,
                qpdf_bytes.len(),
                qpdf_bytes[first_diff],
                flpdf_bytes[first_diff]
            )
        };
        ComparatorResult::Diverge { reason }
    }
}

// ---------------------------------------------------------------------------
// Verdict
// ---------------------------------------------------------------------------

/// Overall verdict for one tuple (across all comparators).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
    /// All comparators returned `Match`.
    Pass,
    /// At least one comparator returned `Diverge`.
    Fail,
    /// All comparators were `Skipped` (e.g. one tool did not produce output).
    Skipped,
}

// ---------------------------------------------------------------------------
// TupleReport
// ---------------------------------------------------------------------------

/// Per-comparator finding for one tuple.
#[derive(Debug, Clone)]
pub struct ComparatorFinding {
    /// Name of the comparator (mirrors [`Comparator::name`]).
    pub comparator: String,
    /// This comparator's result.
    pub result: ComparatorResult,
}

/// The full report for a single (fixture, flag-set) tuple.
#[derive(Debug, Clone)]
pub struct TupleReport {
    pub fixture: String,
    pub flag_set: String,
    pub verdict: Verdict,
    pub findings: Vec<ComparatorFinding>,
}

// ---------------------------------------------------------------------------
// MatrixReport
// ---------------------------------------------------------------------------

/// The aggregated report over all (fixture, flag-set) tuples.
#[derive(Debug, Clone)]
pub struct MatrixReport {
    pub tuple_reports: Vec<TupleReport>,
}

impl MatrixReport {
    /// Number of tuples that passed.
    pub fn pass_count(&self) -> usize {
        self.tuple_reports
            .iter()
            .filter(|r| r.verdict == Verdict::Pass)
            .count()
    }

    /// Number of tuples that failed.
    pub fn fail_count(&self) -> usize {
        self.tuple_reports
            .iter()
            .filter(|r| r.verdict == Verdict::Fail)
            .count()
    }

    /// Number of tuples that were skipped.
    pub fn skip_count(&self) -> usize {
        self.tuple_reports
            .iter()
            .filter(|r| r.verdict == Verdict::Skipped)
            .count()
    }

    // -----------------------------------------------------------------------
    // Formatters
    // -----------------------------------------------------------------------

    /// Render the report as a Markdown table.
    pub fn to_markdown(&self) -> String {
        let mut out = String::new();
        out.push_str("# Compat Matrix Report\n\n");
        out.push_str(&format!(
            "pass={} fail={} skip={}\n\n",
            self.pass_count(),
            self.fail_count(),
            self.skip_count()
        ));
        out.push_str("| fixture | flag_set | verdict | details |\n");
        out.push_str("|---------|----------|---------|----------|\n");

        for report in &self.tuple_reports {
            let verdict_str = match report.verdict {
                Verdict::Pass => "PASS",
                Verdict::Fail => "FAIL",
                Verdict::Skipped => "SKIP",
            };
            let details = report
                .findings
                .iter()
                .map(|f| {
                    let tag = match &f.result {
                        ComparatorResult::Match => format!("{}:match", f.comparator),
                        ComparatorResult::Diverge { reason } => {
                            format!("{}:diverge({})", f.comparator, reason)
                        }
                        ComparatorResult::Skipped { reason } => {
                            format!("{}:skip({})", f.comparator, reason)
                        }
                    };
                    tag
                })
                .collect::<Vec<_>>()
                .join("; ");
            out.push_str(&format!(
                "| {} | {} | {} | {} |\n",
                report.fixture, report.flag_set, verdict_str, details
            ));
        }

        out
    }

    /// Render the report as a JSON string (no external dependencies).
    pub fn to_json(&self) -> String {
        let mut out = String::new();
        out.push_str("{\n");
        out.push_str(&format!("  \"pass\": {},\n", self.pass_count()));
        out.push_str(&format!("  \"fail\": {},\n", self.fail_count()));
        out.push_str(&format!("  \"skip\": {},\n", self.skip_count()));
        out.push_str("  \"tuples\": [\n");

        for (idx, report) in self.tuple_reports.iter().enumerate() {
            let verdict_str = match report.verdict {
                Verdict::Pass => "pass",
                Verdict::Fail => "fail",
                Verdict::Skipped => "skip",
            };
            out.push_str("    {\n");
            out.push_str(&format!(
                "      \"fixture\": {},\n",
                json_string(&report.fixture)
            ));
            out.push_str(&format!(
                "      \"flag_set\": {},\n",
                json_string(&report.flag_set)
            ));
            out.push_str(&format!(
                "      \"verdict\": {},\n",
                json_string(verdict_str)
            ));
            out.push_str("      \"findings\": [\n");

            for (fidx, finding) in report.findings.iter().enumerate() {
                let (result_tag, reason_field) = match &finding.result {
                    ComparatorResult::Match => ("match", None),
                    ComparatorResult::Diverge { reason } => ("diverge", Some(reason.as_str())),
                    ComparatorResult::Skipped { reason } => ("skip", Some(reason.as_str())),
                };
                out.push_str("        {\n");
                out.push_str(&format!(
                    "          \"comparator\": {},\n",
                    json_string(&finding.comparator)
                ));
                out.push_str(&format!(
                    "          \"result\": {}",
                    json_string(result_tag)
                ));
                if let Some(r) = reason_field {
                    out.push_str(",\n");
                    out.push_str(&format!("          \"reason\": {}", json_string(r)));
                }
                out.push('\n');
                out.push_str("        }");
                if fidx + 1 < report.findings.len() {
                    out.push(',');
                }
                out.push('\n');
            }

            out.push_str("      ]\n");
            out.push_str("    }");
            if idx + 1 < self.tuple_reports.len() {
                out.push(',');
            }
            out.push('\n');
        }

        out.push_str("  ]\n");
        out.push('}');
        out
    }
}

// ---------------------------------------------------------------------------
// JSON helper
// ---------------------------------------------------------------------------

/// Minimal JSON string escaper (no external deps).
fn json_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                out.push_str(&format!("\\u{:04x}", c as u32));
            }
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

// ---------------------------------------------------------------------------
// qpdf availability
// ---------------------------------------------------------------------------

/// Returns `true` if `qpdf` is found on `PATH` and responds to `--version`.
pub fn is_qpdf_available() -> bool {
    ShellCommand::new("qpdf")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

// ---------------------------------------------------------------------------
// Internal runner helpers
// ---------------------------------------------------------------------------

fn run_qpdf_for_tuple(fixture_path: &Path, flag_set: &FlagSet, out_dir: &Path) -> ToolOutput {
    let output_path = out_dir.join("qpdf-out.pdf");
    let out_path_str = output_path.to_str().unwrap_or("").to_string();
    let fixture_str = fixture_path.to_str().unwrap_or("").to_string();

    let mut cmd_args: Vec<String> = flag_set.qpdf_args().iter().map(|s| s.to_string()).collect();
    cmd_args.push(fixture_str);
    cmd_args.push(out_path_str);

    let result = ShellCommand::new("qpdf").args(&cmd_args).output();

    match result {
        Err(e) => ToolOutput {
            success: false,
            exit_code: None,
            stdout: vec![],
            stderr: e.to_string().into_bytes(),
            output_bytes: None,
        },
        Ok(out) => {
            let output_bytes = if out.status.success() {
                std::fs::read(&output_path).ok()
            } else {
                None
            };
            ToolOutput {
                success: out.status.success(),
                exit_code: out.status.code(),
                stdout: out.stdout,
                stderr: out.stderr,
                output_bytes,
            }
        }
    }
}

fn run_flpdf_for_tuple(fixture_path: &Path, flag_set: &FlagSet, out_dir: &Path) -> ToolOutput {
    let output_path = out_dir.join("flpdf-out.pdf");
    let fixture_str = fixture_path.to_str().unwrap_or("").to_string();
    let out_path_str = output_path.to_str().unwrap_or("").to_string();

    // Build args: rewrite <in> <out> [extra flags...]
    let mut cmd = CargoCommand::cargo_bin("flpdf").expect("flpdf binary must exist");
    cmd.arg("rewrite");
    for arg in flag_set.flpdf_args() {
        cmd.arg(arg);
    }
    cmd.arg(&fixture_str);
    cmd.arg(&out_path_str);

    let result = cmd.output();

    match result {
        Err(e) => ToolOutput {
            success: false,
            exit_code: None,
            stdout: vec![],
            stderr: e.to_string().into_bytes(),
            output_bytes: None,
        },
        Ok(out) => {
            let output_bytes = if out.status.success() {
                std::fs::read(&output_path).ok()
            } else {
                None
            };
            ToolOutput {
                success: out.status.success(),
                exit_code: out.status.code(),
                stdout: out.stdout,
                stderr: out.stderr,
                output_bytes,
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Matrix runner
// ---------------------------------------------------------------------------

/// Run the full matrix of `(fixture × flag_set)` tuples, evaluate each with
/// all supplied `comparators`, and return a [`MatrixReport`].
///
/// If `qpdf` is not available, all tuples are recorded as `Verdict::Skipped`.
pub fn run_matrix(
    fixtures: &[Fixture],
    flag_sets: &[FlagSet],
    comparators: &[&dyn Comparator],
) -> MatrixReport {
    let qpdf_present = is_qpdf_available();

    let mut tuple_reports = Vec::new();

    for fixture in fixtures {
        for flag_set in flag_sets {
            let tuple_key = Tuple {
                fixture: fixture.clone(),
                flag_set: flag_set.clone(),
            };

            if !qpdf_present {
                let findings = comparators
                    .iter()
                    .map(|c| ComparatorFinding {
                        comparator: c.name().to_string(),
                        result: ComparatorResult::Skipped {
                            reason: "qpdf not available".to_string(),
                        },
                    })
                    .collect::<Vec<_>>();
                tuple_reports.push(TupleReport {
                    fixture: tuple_key.fixture.name.clone(),
                    flag_set: tuple_key.flag_set.name().to_string(),
                    verdict: Verdict::Skipped,
                    findings,
                });
                continue;
            }

            // Create a temporary directory for this tuple's outputs.
            let tmp: TempDir = tempfile::tempdir().expect("failed to create tempdir");

            let qpdf_output = run_qpdf_for_tuple(&fixture.path, flag_set, tmp.path());
            let flpdf_output = run_flpdf_for_tuple(&fixture.path, flag_set, tmp.path());

            let run_outputs = RunOutputs {
                qpdf: qpdf_output,
                flpdf: flpdf_output,
            };

            let (findings, verdict) = evaluate_tuple(comparators, &run_outputs);

            tuple_reports.push(TupleReport {
                fixture: tuple_key.fixture.name.clone(),
                flag_set: tuple_key.flag_set.name().to_string(),
                verdict,
                findings,
            });
        }
    }

    MatrixReport { tuple_reports }
}

/// Evaluate one tuple's `RunOutputs` against the supplied `comparators` and
/// derive its [`Verdict`].
///
/// If either tool reported `success == false`, prepend a synthetic
/// `tool-execution` finding so a tool crash or non-zero exit is surfaced as
/// `Verdict::Fail` even when every comparator skipped (which is the natural
/// behaviour when output bytes are missing). Without this, a `flpdf` crash
/// would be silently absorbed into `Verdict::Skipped` and a real regression
/// would slip past the matrix.
fn evaluate_tuple(
    comparators: &[&dyn Comparator],
    run_outputs: &RunOutputs,
) -> (Vec<ComparatorFinding>, Verdict) {
    let mut findings: Vec<ComparatorFinding> = Vec::new();

    if !run_outputs.qpdf.success || !run_outputs.flpdf.success {
        let mut reason_parts = Vec::new();
        if !run_outputs.qpdf.success {
            reason_parts.push(format!(
                "qpdf failed (exit_code={:?})",
                run_outputs.qpdf.exit_code
            ));
        }
        if !run_outputs.flpdf.success {
            reason_parts.push(format!(
                "flpdf failed (exit_code={:?})",
                run_outputs.flpdf.exit_code
            ));
        }
        findings.push(ComparatorFinding {
            comparator: "tool-execution".to_string(),
            result: ComparatorResult::Diverge {
                reason: reason_parts.join("; "),
            },
        });
    }

    findings.extend(comparators.iter().map(|c| ComparatorFinding {
        comparator: c.name().to_string(),
        result: c.compare(run_outputs),
    }));

    let verdict = if findings
        .iter()
        .any(|f| matches!(f.result, ComparatorResult::Diverge { .. }))
    {
        Verdict::Fail
    } else if findings.iter().all(|f| f.result == ComparatorResult::Match) {
        Verdict::Pass
    } else if findings
        .iter()
        .all(|f| matches!(f.result, ComparatorResult::Skipped { .. }))
    {
        Verdict::Skipped
    } else {
        // Mix of Match and Skipped: treat as Pass (skipped comparators are advisory).
        Verdict::Pass
    };

    (findings, verdict)
}

// ---------------------------------------------------------------------------
// Unit tests for internal helpers
// ---------------------------------------------------------------------------

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

    #[test]
    fn json_string_escapes_special_chars() {
        assert_eq!(json_string("hello"), "\"hello\"");
        assert_eq!(json_string("a\"b"), "\"a\\\"b\"");
        assert_eq!(json_string("a\\b"), "\"a\\\\b\"");
        assert_eq!(json_string("a\nb"), "\"a\\nb\"");
        assert_eq!(json_string("a\tb"), "\"a\\tb\"");
        assert_eq!(json_string("a\x01b"), "\"a\\u0001b\"");
    }

    #[test]
    fn flag_set_names_are_stable() {
        assert_eq!(FlagSet::Plain.name(), "plain");
        assert_eq!(FlagSet::StaticId.name(), "static-id");
        assert_eq!(FlagSet::Linearize.name(), "linearize");
    }

    #[test]
    fn byte_comparator_skips_when_no_output() {
        let outputs = RunOutputs {
            qpdf: ToolOutput {
                success: false,
                exit_code: Some(1),
                stdout: vec![],
                stderr: vec![],
                output_bytes: None,
            },
            flpdf: ToolOutput {
                success: false,
                exit_code: Some(1),
                stdout: vec![],
                stderr: vec![],
                output_bytes: None,
            },
        };
        let result = ByteComparator.compare(&outputs);
        assert!(matches!(result, ComparatorResult::Skipped { .. }));
    }

    #[test]
    fn byte_comparator_matches_identical_bytes() {
        let bytes = vec![1u8, 2, 3];
        let outputs = RunOutputs {
            qpdf: ToolOutput {
                success: true,
                exit_code: Some(0),
                stdout: vec![],
                stderr: vec![],
                output_bytes: Some(bytes.clone()),
            },
            flpdf: ToolOutput {
                success: true,
                exit_code: Some(0),
                stdout: vec![],
                stderr: vec![],
                output_bytes: Some(bytes),
            },
        };
        let result = ByteComparator.compare(&outputs);
        assert_eq!(result, ComparatorResult::Match);
    }

    #[test]
    fn byte_comparator_diverges_on_different_lengths() {
        let outputs = RunOutputs {
            qpdf: ToolOutput {
                success: true,
                exit_code: Some(0),
                stdout: vec![],
                stderr: vec![],
                output_bytes: Some(vec![1, 2, 3]),
            },
            flpdf: ToolOutput {
                success: true,
                exit_code: Some(0),
                stdout: vec![],
                stderr: vec![],
                output_bytes: Some(vec![4, 5, 6, 7]),
            },
        };
        let result = ByteComparator.compare(&outputs);
        let ComparatorResult::Diverge { reason } = result else {
            panic!("expected Diverge");
        };
        assert!(
            reason.contains("byte lengths differ"),
            "expected length-diff reason, got: {reason}"
        );
    }

    #[test]
    fn byte_comparator_diverges_on_same_length_different_content() {
        let outputs = RunOutputs {
            qpdf: ToolOutput {
                success: true,
                exit_code: Some(0),
                stdout: vec![],
                stderr: vec![],
                output_bytes: Some(vec![1, 2, 3, 4]),
            },
            flpdf: ToolOutput {
                success: true,
                exit_code: Some(0),
                stdout: vec![],
                stderr: vec![],
                output_bytes: Some(vec![1, 2, 9, 4]),
            },
        };
        let result = ByteComparator.compare(&outputs);
        let ComparatorResult::Diverge { reason } = result else {
            panic!("expected Diverge");
        };
        assert!(
            reason.contains("offset 2"),
            "expected first-diff offset 2, got: {reason}"
        );
        assert!(
            reason.contains("len=4"),
            "expected length tag, got: {reason}"
        );
    }

    #[test]
    fn matrix_report_to_json_is_non_empty() {
        let report = MatrixReport {
            tuple_reports: vec![TupleReport {
                fixture: "one-page.pdf".to_string(),
                flag_set: "plain".to_string(),
                verdict: Verdict::Pass,
                findings: vec![ComparatorFinding {
                    comparator: "byte-equal".to_string(),
                    result: ComparatorResult::Match,
                }],
            }],
        };
        let json = report.to_json();
        assert!(!json.is_empty());
        assert!(json.contains("\"pass\": 1"));
        assert!(json.contains("\"fail\": 0"));
        assert!(json.contains("one-page.pdf"));
    }

    #[test]
    fn matrix_report_to_markdown_is_non_empty() {
        let report = MatrixReport {
            tuple_reports: vec![TupleReport {
                fixture: "one-page.pdf".to_string(),
                flag_set: "plain".to_string(),
                verdict: Verdict::Pass,
                findings: vec![ComparatorFinding {
                    comparator: "byte-equal".to_string(),
                    result: ComparatorResult::Match,
                }],
            }],
        };
        let md = report.to_markdown();
        assert!(!md.is_empty());
        assert!(md.contains("PASS"));
        assert!(md.contains("one-page.pdf"));
    }

    fn output_ok(bytes: Vec<u8>) -> ToolOutput {
        ToolOutput {
            success: true,
            exit_code: Some(0),
            stdout: vec![],
            stderr: vec![],
            output_bytes: Some(bytes),
        }
    }

    fn output_fail(exit_code: i32) -> ToolOutput {
        ToolOutput {
            success: false,
            exit_code: Some(exit_code),
            stdout: vec![],
            stderr: b"boom".to_vec(),
            output_bytes: None,
        }
    }

    #[test]
    fn evaluate_tuple_passes_when_all_match() {
        let outputs = RunOutputs {
            qpdf: output_ok(vec![1, 2, 3]),
            flpdf: output_ok(vec![1, 2, 3]),
        };
        let comparators: Vec<&dyn Comparator> = vec![&ByteComparator];
        let (findings, verdict) = evaluate_tuple(&comparators, &outputs);
        assert_eq!(verdict, Verdict::Pass);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].comparator, "byte-equal");
        assert_eq!(findings[0].result, ComparatorResult::Match);
    }

    #[test]
    fn evaluate_tuple_fails_when_qpdf_execution_fails() {
        let outputs = RunOutputs {
            qpdf: output_fail(2),
            flpdf: output_ok(vec![1, 2, 3]),
        };
        let comparators: Vec<&dyn Comparator> = vec![&ByteComparator];
        let (findings, verdict) = evaluate_tuple(&comparators, &outputs);
        assert_eq!(
            verdict,
            Verdict::Fail,
            "tool failure must surface as Fail, not Skipped"
        );
        let exec_finding = findings
            .iter()
            .find(|f| f.comparator == "tool-execution")
            .expect("synthetic tool-execution finding expected");
        let ComparatorResult::Diverge { reason } = &exec_finding.result else {
            panic!("tool-execution finding should be Diverge");
        };
        assert!(
            reason.contains("qpdf failed"),
            "expected qpdf failure marker, got: {reason}"
        );
    }

    #[test]
    fn evaluate_tuple_fails_when_flpdf_execution_fails() {
        let outputs = RunOutputs {
            qpdf: output_ok(vec![1, 2, 3]),
            flpdf: output_fail(101),
        };
        let comparators: Vec<&dyn Comparator> = vec![&ByteComparator];
        let (findings, verdict) = evaluate_tuple(&comparators, &outputs);
        assert_eq!(verdict, Verdict::Fail);
        let exec_finding = findings
            .iter()
            .find(|f| f.comparator == "tool-execution")
            .expect("synthetic tool-execution finding expected");
        let ComparatorResult::Diverge { reason } = &exec_finding.result else {
            panic!("tool-execution finding should be Diverge");
        };
        assert!(
            reason.contains("flpdf failed"),
            "expected flpdf failure marker, got: {reason}"
        );
        assert!(
            reason.contains("101"),
            "expected exit_code in reason, got: {reason}"
        );
    }

    #[test]
    fn evaluate_tuple_skips_when_tools_ran_but_bytes_missing() {
        // Both tools "succeeded" but neither produced output bytes (e.g. they
        // were rejected mid-run by the comparator). This is treated as a
        // benign skip — distinct from the tool-failure path above.
        let no_bytes = ToolOutput {
            success: true,
            exit_code: Some(0),
            stdout: vec![],
            stderr: vec![],
            output_bytes: None,
        };
        let outputs = RunOutputs {
            qpdf: no_bytes.clone(),
            flpdf: no_bytes,
        };
        let comparators: Vec<&dyn Comparator> = vec![&ByteComparator];
        let (findings, verdict) = evaluate_tuple(&comparators, &outputs);
        assert_eq!(verdict, Verdict::Skipped);
        assert!(findings
            .iter()
            .all(|f| matches!(f.result, ComparatorResult::Skipped { .. })));
    }
}