flpdf-cli 0.2.1

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
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
//! JSON tree diff + allowlist + report machinery for the qpdf JSON schema-diff
//! corpus test (flpdf-9hc.11.14).
//!
//! Public surface:
//! - [`Divergence`] — one path-level mismatch between qpdf and flpdf JSON.
//! - [`diff_values`] — recursive strict-equality tree diff.
//! - [`Allowlist`] — load + match + stale-entry detection.
//! - [`Report`] — fixture × top-level-key matrix + markdown/json writers.
//!
//! See `docs/plans/2026-05-27-flpdf-9hc-11-14-json-schema-diff.md` for the full
//! plan.

use serde_json::Value;
use std::path::Path;
use std::process::Command;

/// Invoke `qpdf --json=2 --json-stream-data=none [--password=X] <fixture>`
/// and return the parsed JSON.
///
/// The caller is responsible for checking `super::is_qpdf_available()` first;
/// this helper does not skip on its own.
pub fn run_qpdf_json(fixture: &Path, password: Option<&str>) -> Result<Value, String> {
    let mut cmd = Command::new("qpdf");
    cmd.arg("--json=2").arg("--json-stream-data=none");
    if let Some(p) = password {
        cmd.arg(format!("--password={p}"));
    }
    cmd.arg(fixture);
    let out = cmd.output().map_err(|e| format!("spawn qpdf: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "qpdf exit {}: {}",
            out.status,
            String::from_utf8_lossy(&out.stderr)
        ));
    }
    serde_json::from_slice(&out.stdout).map_err(|e| format!("qpdf parse: {e}"))
}

/// Invoke the local `flpdf` binary (via assert_cmd::cargo_bin) with
/// `--json=2 --json-stream-data=none [--password=X] <fixture>` and return the
/// parsed JSON.
///
/// flpdf's clap surface accepts `--json=2` with `require_equals = true` and
/// `--json-stream-data=none`; see `crates/flpdf-cli/src/main.rs` for the flag
/// definitions. Verified by pre-flight check during Task 5 (flpdf-9hc.11.14).
pub fn run_flpdf_json(fixture: &Path, password: Option<&str>) -> Result<Value, String> {
    let mut cmd = assert_cmd::Command::cargo_bin("flpdf").map_err(|e| e.to_string())?;
    cmd.arg("--json=2").arg("--json-stream-data=none");
    if let Some(p) = password {
        cmd.arg(format!("--password={p}"));
    }
    cmd.arg(fixture);
    let out = cmd.output().map_err(|e| format!("spawn flpdf: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "flpdf exit {}: {}",
            out.status,
            String::from_utf8_lossy(&out.stderr)
        ));
    }
    serde_json::from_slice(&out.stdout).map_err(|e| format!("flpdf parse: {e}"))
}

#[derive(Debug, Clone, PartialEq)]
pub struct Divergence {
    pub path: String,
    pub qpdf: Value,
    pub flpdf: Value,
}

#[derive(Debug, Clone)]
pub struct AllowlistEntry {
    pub fixture: String,
    pub path: String,
    pub category: String,
    pub beads_ref: String,
    pub reason: String,
}

#[derive(Debug)]
pub struct Allowlist {
    entries: Vec<AllowlistEntry>,
    matched: Vec<bool>,
}

impl Allowlist {
    pub fn from_json_str(s: &str) -> Result<Self, String> {
        if s.trim().is_empty() {
            return Ok(Self {
                entries: vec![],
                matched: vec![],
            });
        }
        let v: Value = serde_json::from_str(s).map_err(|e| format!("allowlist parse: {e}"))?;
        let arr = v
            .get("entries")
            .and_then(Value::as_array)
            .ok_or_else(|| "allowlist missing 'entries' array".to_string())?;
        let mut entries = Vec::with_capacity(arr.len());
        for (i, item) in arr.iter().enumerate() {
            let getstr_req = |k: &str| -> Result<String, String> {
                item.get(k)
                    .and_then(Value::as_str)
                    .map(str::to_string)
                    .ok_or_else(|| format!("allowlist entry {i} missing string field '{k}'"))
            };
            let getstr_opt = |k: &str| -> String {
                item.get(k)
                    .and_then(Value::as_str)
                    .map(str::to_string)
                    .unwrap_or_default()
            };
            entries.push(AllowlistEntry {
                fixture: getstr_req("fixture")?,
                path: getstr_req("path")?,
                category: getstr_req("category")?,
                beads_ref: getstr_opt("beads_ref"),
                reason: getstr_opt("reason"),
            });
        }
        let matched = vec![false; entries.len()];
        Ok(Self { entries, matched })
    }

    pub fn from_path(p: &Path) -> Result<Self, String> {
        match std::fs::read_to_string(p) {
            Ok(s) => Self::from_json_str(&s),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self {
                entries: vec![],
                matched: vec![],
            }),
            Err(e) => Err(format!("allowlist read {}: {e}", p.display())),
        }
    }

    pub fn entries(&self) -> &[AllowlistEntry] {
        &self.entries
    }

    /// Match a divergence against the allowlist. On match, marks the entry as
    /// used and returns it.
    pub fn match_divergence(&mut self, fixture: &str, div: &Divergence) -> Option<&AllowlistEntry> {
        for (i, e) in self.entries.iter().enumerate() {
            if e.fixture == fixture && e.path == div.path {
                self.matched[i] = true;
                return Some(&self.entries[i]);
            }
        }
        None
    }

    /// Entries that never matched a divergence during this run.
    pub fn stale_entries(&self) -> Vec<&AllowlistEntry> {
        self.entries
            .iter()
            .enumerate()
            .filter(|(i, _)| !self.matched[*i])
            .map(|(_, e)| e)
            .collect()
    }
}

/// Strict recursive equality diff between two JSON trees.
///
/// Records one [`Divergence`] per mismatched path. No normalization is applied:
/// integers and floats with the same numerical value are reported as different
/// (consistent with the strict-value-match policy in flpdf-9hc.11.14).
pub fn diff_values(qpdf: &Value, flpdf: &Value) -> Vec<Divergence> {
    let mut out = Vec::new();
    diff_at(qpdf, flpdf, "$", &mut out);
    out
}

fn diff_at(a: &Value, b: &Value, path: &str, out: &mut Vec<Divergence>) {
    use serde_json::Value::*;
    match (a, b) {
        (Object(ao), Object(bo)) => {
            let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
            for (k, av) in ao {
                seen.insert(k.as_str());
                let child_path = join_path(path, k);
                match bo.get(k) {
                    Some(bv) => diff_at(av, bv, &child_path, out),
                    None => out.push(Divergence {
                        path: child_path,
                        qpdf: av.clone(),
                        flpdf: Value::Null,
                    }),
                }
            }
            for (k, bv) in bo {
                if !seen.contains(k.as_str()) {
                    out.push(Divergence {
                        path: join_path(path, k),
                        qpdf: Value::Null,
                        flpdf: bv.clone(),
                    });
                }
            }
        }
        (Array(aa), Array(bb)) if aa.len() == bb.len() => {
            for (i, (av, bv)) in aa.iter().zip(bb.iter()).enumerate() {
                let child_path = format!("{path}[{i}]");
                diff_at(av, bv, &child_path, out);
            }
        }
        _ if a != b => out.push(Divergence {
            path: path.to_string(),
            qpdf: a.clone(),
            flpdf: b.clone(),
        }),
        _ => {}
    }
}

fn join_path(parent: &str, key: &str) -> String {
    if is_simple_key(key) {
        format!("{parent}.{key}")
    } else {
        format!("{parent}.{:?}", key)
    }
}

fn is_simple_key(k: &str) -> bool {
    !k.is_empty()
        && k.chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

pub fn top_level_keys() -> &'static [&'static str] {
    &[
        "acroform",
        "attachments",
        "encrypt",
        "outlines",
        "pagelabels",
        "pages",
        "parameters",
        "qpdf",
        "version",
    ]
}

#[derive(Debug)]
pub struct MatrixCell {
    pub key: &'static str,
    pub status: CellStatus,
}

#[derive(Debug)]
pub enum CellStatus {
    /// Subtree present in both, no divergences.
    Pass,
    /// Subtree present, all divergences are in the allowlist.
    Known { divergences: Vec<Divergence> },
    /// Subtree present but at least one divergence is not allowlisted.
    Unknown { divergences: Vec<Divergence> },
    /// Key missing in both qpdf and flpdf output.
    Missing,
}

pub fn compute_matrix(
    fixture: &str,
    qpdf: &Value,
    flpdf: &Value,
    allowlist: &mut Allowlist,
) -> Vec<MatrixCell> {
    top_level_keys()
        .iter()
        .map(|&key| {
            let a = qpdf.get(key);
            let b = flpdf.get(key);
            let status = match (a, b) {
                (None, None) => CellStatus::Missing,
                (Some(av), Some(bv)) => {
                    let raw = diff_values(av, bv);
                    let divs: Vec<Divergence> = raw
                        .into_iter()
                        .map(|d| {
                            let new_path = if d.path == "$" {
                                format!("$.{key}")
                            } else {
                                format!("$.{key}{}", &d.path[1..])
                            };
                            Divergence {
                                path: new_path,
                                ..d
                            }
                        })
                        .collect();
                    classify_divergences(fixture, divs, allowlist)
                }
                (qv, fv) => {
                    // One-sided top-level key: synthesize a divergence at $.<key>
                    // so the same allowlist + Known/Unknown classification pipeline
                    // applies. Without this, a wholly-missing key would silently
                    // bypass the corpus runner's unknown_divergences() assertion.
                    let synth = Divergence {
                        path: format!("$.{key}"),
                        qpdf: qv.cloned().unwrap_or(Value::Null),
                        flpdf: fv.cloned().unwrap_or(Value::Null),
                    };
                    classify_divergences(fixture, vec![synth], allowlist)
                }
            };
            MatrixCell { key, status }
        })
        .collect()
}

fn classify_divergences(
    fixture: &str,
    divs: Vec<Divergence>,
    allowlist: &mut Allowlist,
) -> CellStatus {
    if divs.is_empty() {
        return CellStatus::Pass;
    }
    // Drain ALL divergences against the allowlist before classifying, so every
    // allowlist entry that should match gets its `matched` flag set. partition
    // walks the whole vec (no short-circuit), and also lets us keep allowlisted
    // and unknown divergences in separate buckets so CellStatus::Unknown only
    // ever carries the truly-unknown ones — otherwise unknown_divergences()
    // would wrongly report allowlisted siblings as unknown.
    let (known, unknown): (Vec<Divergence>, Vec<Divergence>) = divs
        .into_iter()
        .partition(|d| allowlist.match_divergence(fixture, d).is_some());
    if unknown.is_empty() {
        CellStatus::Known { divergences: known }
    } else {
        CellStatus::Unknown {
            divergences: unknown,
        }
    }
}

#[derive(Debug)]
pub struct FixtureResult {
    pub fixture: String,
    pub cells: Vec<MatrixCell>,
    pub qpdf_error: Option<String>,
    pub flpdf_error: Option<String>,
}

#[derive(Debug)]
pub struct Report {
    pub fixtures: Vec<FixtureResult>,
    pub stale_allowlist: Vec<AllowlistEntry>,
}

impl Report {
    /// (pass_or_known_count, present_cell_count)
    pub fn overall_pass_rate(&self) -> (usize, usize) {
        let mut pass = 0usize;
        let mut present = 0usize;
        for f in &self.fixtures {
            for c in &f.cells {
                match &c.status {
                    CellStatus::Missing => {} // excluded
                    CellStatus::Pass | CellStatus::Known { .. } => {
                        pass += 1;
                        present += 1;
                    }
                    CellStatus::Unknown { .. } => {
                        present += 1;
                    }
                }
            }
        }
        (pass, present)
    }

    /// All unknown divergences flattened: (key, fixture, &Divergence).
    pub fn unknown_divergences(&self) -> Vec<(&'static str, &str, &Divergence)> {
        let mut out = Vec::new();
        for f in &self.fixtures {
            for c in &f.cells {
                if let CellStatus::Unknown { divergences } = &c.status {
                    for d in divergences {
                        out.push((c.key, f.fixture.as_str(), d));
                    }
                }
            }
        }
        out
    }

    pub fn unknown_summary(&self) -> String {
        let mut s = String::new();
        for (key, fixture, d) in self.unknown_divergences() {
            s.push_str(&format!(
                "  {fixture}  [{key}]  {}\n    qpdf: {}\n    flpdf: {}\n",
                d.path, d.qpdf, d.flpdf
            ));
        }
        s
    }

    pub fn stale_summary(&self) -> String {
        let mut s = String::new();
        for e in &self.stale_allowlist {
            s.push_str(&format!("  {}  {}  {}\n", e.fixture, e.path, e.category));
        }
        s
    }

    pub fn to_markdown(&self) -> String {
        let keys = top_level_keys();
        let (pass, present) = self.overall_pass_rate();
        let pct = if present == 0 {
            0.0
        } else {
            100.0 * pass as f64 / present as f64
        };

        let mut s = String::new();
        s.push_str("# qpdf JSON schema-diff report\n\n");
        s.push_str(&format!(
            "Overall pass rate: **{}/{}** ({:.1}%) — present cells only\n\n",
            pass, present, pct
        ));

        s.push_str("| fixture |");
        for k in keys {
            s.push_str(&format!(" {} |", k));
        }
        s.push('\n');
        s.push_str("|---|");
        for _ in keys {
            s.push_str("---|");
        }
        s.push('\n');

        for f in &self.fixtures {
            s.push_str(&format!("| `{}` |", f.fixture));
            let cell_by_key: std::collections::HashMap<&str, &MatrixCell> =
                f.cells.iter().map(|c| (c.key, c)).collect();
            for k in keys {
                let glyph = match cell_by_key.get(k).map(|c| &c.status) {
                    Some(CellStatus::Pass) => "ok".to_string(),
                    Some(CellStatus::Known { divergences }) => {
                        format!("known({})", divergences.len())
                    }
                    Some(CellStatus::Unknown { divergences }) => {
                        format!("FAIL({})", divergences.len())
                    }
                    Some(CellStatus::Missing) => "n/a".to_string(),
                    None => "?".to_string(),
                };
                s.push_str(&format!(" {} |", glyph));
            }
            s.push('\n');
        }

        if !self.unknown_divergences().is_empty() {
            s.push_str("\n## Unknown divergences\n\n");
            s.push_str(&self.unknown_summary());
        }

        if !self.stale_allowlist.is_empty() {
            s.push_str("\n## Stale allowlist entries\n\n");
            s.push_str(&self.stale_summary());
        }

        s
    }

    pub fn to_json(&self) -> String {
        let fixtures: Vec<Value> = self
            .fixtures
            .iter()
            .map(|f| {
                let cells: Vec<Value> = f
                    .cells
                    .iter()
                    .map(|c| {
                        let (status, divs): (&str, Vec<&Divergence>) = match &c.status {
                            CellStatus::Pass => ("pass", vec![]),
                            CellStatus::Known { divergences } => {
                                ("known", divergences.iter().collect())
                            }
                            CellStatus::Unknown { divergences } => {
                                ("unknown", divergences.iter().collect())
                            }
                            CellStatus::Missing => ("missing", vec![]),
                        };
                        let divs_json: Vec<Value> = divs
                            .iter()
                            .map(|d| {
                                serde_json::json!({"path": d.path, "qpdf": d.qpdf, "flpdf": d.flpdf})
                            })
                            .collect();
                        serde_json::json!({"key": c.key, "status": status, "divergences": divs_json})
                    })
                    .collect();
                serde_json::json!({
                    "fixture": f.fixture,
                    "qpdf_error": f.qpdf_error,
                    "flpdf_error": f.flpdf_error,
                    "cells": cells,
                })
            })
            .collect();
        let (pass, present) = self.overall_pass_rate();
        let payload = serde_json::json!({
            "overall": {"pass_or_known": pass, "present": present},
            "fixtures": fixtures,
            "stale_allowlist": self.stale_allowlist.iter().map(|e| serde_json::json!({
                "fixture": e.fixture, "path": e.path, "category": e.category,
                "beads_ref": e.beads_ref, "reason": e.reason,
            })).collect::<Vec<_>>(),
        });
        serde_json::to_string_pretty(&payload).unwrap()
    }
}

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

    fn paths(divs: &[Divergence]) -> Vec<&str> {
        divs.iter().map(|d| d.path.as_str()).collect()
    }

    #[test]
    fn identical_primitives_no_divergence() {
        assert!(diff_values(&json!(1), &json!(1)).is_empty());
        assert!(diff_values(&json!("a"), &json!("a")).is_empty());
        assert!(diff_values(&json!(null), &json!(null)).is_empty());
        assert!(diff_values(&json!(true), &json!(true)).is_empty());
    }

    #[test]
    fn primitive_mismatch_reports_root_path() {
        let d = diff_values(&json!(1), &json!(2));
        assert_eq!(paths(&d), vec!["$"]);
        assert_eq!(d[0].qpdf, json!(1));
        assert_eq!(d[0].flpdf, json!(2));
    }

    #[test]
    fn integer_vs_float_is_a_divergence() {
        let d = diff_values(&json!(0), &json!(0.0));
        assert_eq!(paths(&d), vec!["$"]);
    }

    #[test]
    fn array_length_mismatch_reports_array_path() {
        let d = diff_values(&json!([1, 2]), &json!([1, 2, 3]));
        assert_eq!(paths(&d), vec!["$"]);
    }

    #[test]
    fn array_element_mismatch_reports_indexed_path() {
        let d = diff_values(&json!([1, 2, 3]), &json!([1, 9, 3]));
        assert_eq!(paths(&d), vec!["$[1]"]);
    }

    #[test]
    fn object_value_mismatch_reports_key_path() {
        let a = json!({"x": 1, "y": 2});
        let b = json!({"x": 1, "y": 99});
        let d = diff_values(&a, &b);
        assert_eq!(paths(&d), vec!["$.y"]);
    }

    #[test]
    fn missing_key_in_b_is_a_divergence() {
        let a = json!({"x": 1, "y": 2});
        let b = json!({"x": 1});
        let d = diff_values(&a, &b);
        assert_eq!(paths(&d), vec!["$.y"]);
        assert_eq!(d[0].qpdf, json!(2));
        assert_eq!(d[0].flpdf, Value::Null);
    }

    #[test]
    fn extra_key_in_b_is_a_divergence() {
        let a = json!({"x": 1});
        let b = json!({"x": 1, "z": 5});
        let d = diff_values(&a, &b);
        assert_eq!(paths(&d), vec!["$.z"]);
        assert_eq!(d[0].qpdf, Value::Null);
        assert_eq!(d[0].flpdf, json!(5));
    }

    #[test]
    fn nested_object_path_uses_dot() {
        let a = json!({"a": {"b": {"c": 1}}});
        let b = json!({"a": {"b": {"c": 2}}});
        let d = diff_values(&a, &b);
        assert_eq!(paths(&d), vec!["$.a.b.c"]);
    }

    #[test]
    fn key_with_special_chars_is_quoted() {
        let a = json!({"3 0 R": 1});
        let b = json!({"3 0 R": 2});
        let d = diff_values(&a, &b);
        assert_eq!(paths(&d), vec![r#"$."3 0 R""#]);
    }

    #[test]
    fn type_mismatch_records_both_values() {
        let d = diff_values(&json!(1), &json!("1"));
        assert_eq!(paths(&d), vec!["$"]);
        assert_eq!(d[0].qpdf, json!(1));
        assert_eq!(d[0].flpdf, json!("1"));
    }

    #[test]
    fn multiple_divergences_collected() {
        let a = json!({"a": 1, "b": 2, "c": 3});
        let b = json!({"a": 9, "b": 2, "c": 8});
        let d = diff_values(&a, &b);
        let mut got = paths(&d);
        got.sort();
        assert_eq!(got, vec!["$.a", "$.c"]);
    }

    #[test]
    fn object_inside_array_path() {
        let a = json!([{"x": 1}]);
        let b = json!([{"x": 2}]);
        let d = diff_values(&a, &b);
        assert_eq!(paths(&d), vec!["$[0].x"]);
    }

    #[test]
    fn nested_arrays_path() {
        let a = json!([[1, 2]]);
        let b = json!([[1, 9]]);
        let d = diff_values(&a, &b);
        assert_eq!(paths(&d), vec!["$[0][1]"]);
    }

    #[test]
    fn type_mismatch_under_object_key() {
        let a = json!({"x": [1]});
        let b = json!({"x": {"a": 1}});
        let d = diff_values(&a, &b);
        assert_eq!(paths(&d), vec!["$.x"]);
        assert_eq!(d[0].qpdf, json!([1]));
        assert_eq!(d[0].flpdf, json!({"a": 1}));
    }

    const SAMPLE_ALLOWLIST: &str = r#"{
  "entries": [
    {
      "fixture": "compat/foo.pdf",
      "path": "$.parameters.version",
      "category": "flpdf-feature-gap",
      "beads_ref": "flpdf-9hc.11.x",
      "reason": "version reporting differs"
    }
  ]
}"#;

    #[test]
    fn allowlist_loads_from_json_string() {
        let al = Allowlist::from_json_str(SAMPLE_ALLOWLIST).unwrap();
        assert_eq!(al.entries().len(), 1);
        assert_eq!(al.entries()[0].fixture, "compat/foo.pdf");
        assert_eq!(al.entries()[0].path, "$.parameters.version");
        assert_eq!(al.entries()[0].category, "flpdf-feature-gap");
    }

    #[test]
    fn allowlist_empty_object_is_empty() {
        let al = Allowlist::from_json_str(r#"{"entries":[]}"#).unwrap();
        assert!(al.entries().is_empty());
    }

    #[test]
    fn allowlist_missing_file_is_empty() {
        let al = Allowlist::from_path(std::path::Path::new("/nonexistent/allowlist.json")).unwrap();
        assert!(al.entries().is_empty());
    }

    #[test]
    fn allowlist_matches_by_fixture_and_path() {
        let mut al = Allowlist::from_json_str(SAMPLE_ALLOWLIST).unwrap();
        let div = Divergence {
            path: "$.parameters.version".to_string(),
            qpdf: json!(1),
            flpdf: json!(2),
        };
        let m = al.match_divergence("compat/foo.pdf", &div);
        assert!(m.is_some());
        assert_eq!(m.unwrap().category, "flpdf-feature-gap");
    }

    #[test]
    fn allowlist_no_match_for_different_fixture() {
        let mut al = Allowlist::from_json_str(SAMPLE_ALLOWLIST).unwrap();
        let div = Divergence {
            path: "$.parameters.version".to_string(),
            qpdf: json!(1),
            flpdf: json!(2),
        };
        assert!(al.match_divergence("compat/other.pdf", &div).is_none());
    }

    #[test]
    fn allowlist_no_match_for_different_path() {
        let mut al = Allowlist::from_json_str(SAMPLE_ALLOWLIST).unwrap();
        let div = Divergence {
            path: "$.pages[0].mediabox".to_string(),
            qpdf: json!(1),
            flpdf: json!(2),
        };
        assert!(al.match_divergence("compat/foo.pdf", &div).is_none());
    }

    #[test]
    fn allowlist_tracks_unused_entries() {
        let mut al = Allowlist::from_json_str(SAMPLE_ALLOWLIST).unwrap();
        let stale = al.stale_entries();
        assert_eq!(stale.len(), 1);

        let div = Divergence {
            path: "$.parameters.version".to_string(),
            qpdf: json!(1),
            flpdf: json!(2),
        };
        let _ = al.match_divergence("compat/foo.pdf", &div);
        assert!(al.stale_entries().is_empty());
    }

    const QPDF_V2_KEYS: &[&str] = &[
        "acroform",
        "attachments",
        "encrypt",
        "outlines",
        "pagelabels",
        "pages",
        "parameters",
        "qpdf",
        "version",
    ];

    #[test]
    fn matrix_keys_are_all_qpdf_v2_top_level() {
        assert_eq!(top_level_keys(), QPDF_V2_KEYS);
    }

    #[test]
    fn matrix_cell_pass_when_subtrees_equal() {
        let qpdf = json!({"parameters": {"version": 2}, "pages": []});
        let flpdf = json!({"parameters": {"version": 2}, "pages": []});
        let mut al = Allowlist::from_json_str(r#"{"entries":[]}"#).unwrap();
        let cells = compute_matrix("smoke.pdf", &qpdf, &flpdf, &mut al);
        let by_key: std::collections::HashMap<_, _> =
            cells.iter().map(|c| (c.key, &c.status)).collect();
        assert!(matches!(
            by_key.get("parameters").unwrap(),
            CellStatus::Pass
        ));
        assert!(matches!(by_key.get("pages").unwrap(), CellStatus::Pass));
        assert!(matches!(
            by_key.get("version").unwrap(),
            CellStatus::Missing
        ));
    }

    #[test]
    fn matrix_cell_unknown_when_divergence_not_in_allowlist() {
        let qpdf = json!({"parameters": {"version": 2}});
        let flpdf = json!({"parameters": {"version": 3}});
        let mut al = Allowlist::from_json_str(r#"{"entries":[]}"#).unwrap();
        let cells = compute_matrix("foo.pdf", &qpdf, &flpdf, &mut al);
        let params = cells.iter().find(|c| c.key == "parameters").unwrap();
        match &params.status {
            CellStatus::Unknown { divergences } => {
                assert_eq!(divergences.len(), 1);
                assert_eq!(divergences[0].path, "$.parameters.version");
            }
            other => panic!("expected Unknown, got {other:?}"),
        }
    }

    #[test]
    fn matrix_cell_known_when_divergence_is_allowlisted() {
        let qpdf = json!({"parameters": {"version": 2}});
        let flpdf = json!({"parameters": {"version": 3}});
        let allowlist_json = r#"{"entries":[{
            "fixture":"foo.pdf","path":"$.parameters.version",
            "category":"flpdf-feature-gap","beads_ref":"","reason":""
        }]}"#;
        let mut al = Allowlist::from_json_str(allowlist_json).unwrap();
        let cells = compute_matrix("foo.pdf", &qpdf, &flpdf, &mut al);
        let params = cells.iter().find(|c| c.key == "parameters").unwrap();
        assert!(matches!(params.status, CellStatus::Known { .. }));
    }

    #[test]
    fn qpdf_returns_object_with_top_level_keys() {
        if !super::super::is_qpdf_available() {
            eprintln!("skipping: qpdf not on PATH");
            return;
        }
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/minimal.pdf");
        let v = run_qpdf_json(&path, None).expect("qpdf --json=2 on minimal.pdf");
        assert!(v.is_object());
        let obj = v.as_object().unwrap();
        assert!(
            obj.contains_key("parameters"),
            "missing parameters: {:?}",
            obj.keys().collect::<Vec<_>>()
        );
        assert!(
            obj.contains_key("qpdf"),
            "missing 'qpdf' top-level key (qpdf JSON v2 schema): {:?}",
            obj.keys().collect::<Vec<_>>()
        );
    }

    #[test]
    fn flpdf_returns_object_with_top_level_keys() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/minimal.pdf");
        let v = run_flpdf_json(&path, None).expect("flpdf --json=2 on minimal.pdf");
        assert!(v.is_object());
        assert!(v.as_object().unwrap().contains_key("parameters"));
    }

    fn dummy_fixture_result(fixture: &str, cells: Vec<MatrixCell>) -> FixtureResult {
        FixtureResult {
            fixture: fixture.to_string(),
            cells,
            qpdf_error: None,
            flpdf_error: None,
        }
    }

    #[test]
    fn report_overall_pass_rate_counts_pass_and_known() {
        let cells_a = vec![
            MatrixCell {
                key: "parameters",
                status: CellStatus::Pass,
            },
            MatrixCell {
                key: "pages",
                status: CellStatus::Pass,
            },
            MatrixCell {
                key: "outlines",
                status: CellStatus::Known {
                    divergences: vec![Divergence {
                        path: "$.outlines[0].x".into(),
                        qpdf: json!(1),
                        flpdf: json!(2),
                    }],
                },
            },
            MatrixCell {
                key: "encrypt",
                status: CellStatus::Missing,
            },
        ];
        let cells_b = vec![
            MatrixCell {
                key: "parameters",
                status: CellStatus::Pass,
            },
            MatrixCell {
                key: "pages",
                status: CellStatus::Unknown {
                    divergences: vec![Divergence {
                        path: "$.pages[0].x".into(),
                        qpdf: json!(1),
                        flpdf: json!(2),
                    }],
                },
            },
            MatrixCell {
                key: "outlines",
                status: CellStatus::Pass,
            },
            MatrixCell {
                key: "encrypt",
                status: CellStatus::Missing,
            },
        ];
        let report = Report {
            fixtures: vec![
                dummy_fixture_result("a.pdf", cells_a),
                dummy_fixture_result("b.pdf", cells_b),
            ],
            stale_allowlist: vec![],
        };
        // present cells: a has 3 (params Pass, pages Pass, outlines Known), b has 3
        // (params Pass, pages Unknown, outlines Pass). Total present = 6.
        // pass-or-known: 3 (a) + 2 (b) = 5. Expected 5/6.
        assert_eq!(report.overall_pass_rate(), (5, 6));
    }

    #[test]
    fn report_unknown_divergences_collected() {
        let cells = vec![MatrixCell {
            key: "pages",
            status: CellStatus::Unknown {
                divergences: vec![Divergence {
                    path: "$.pages[0].x".into(),
                    qpdf: json!(1),
                    flpdf: json!(2),
                }],
            },
        }];
        let report = Report {
            fixtures: vec![dummy_fixture_result("a.pdf", cells)],
            stale_allowlist: vec![],
        };
        let unknown = report.unknown_divergences();
        assert_eq!(unknown.len(), 1);
        assert_eq!(unknown[0].1, "a.pdf");
        assert_eq!(unknown[0].2.path, "$.pages[0].x");
    }

    #[test]
    fn report_markdown_includes_matrix_header() {
        let report = Report {
            fixtures: vec![],
            stale_allowlist: vec![],
        };
        let md = report.to_markdown();
        assert!(md.contains("| fixture"));
        for key in top_level_keys() {
            assert!(md.contains(key), "markdown missing header column '{key}'");
        }
    }

    #[test]
    fn report_json_round_trips() {
        let report = Report {
            fixtures: vec![dummy_fixture_result(
                "a.pdf",
                vec![MatrixCell {
                    key: "parameters",
                    status: CellStatus::Pass,
                }],
            )],
            stale_allowlist: vec![],
        };
        let s = report.to_json();
        let v: Value = serde_json::from_str(&s).unwrap();
        assert_eq!(v["fixtures"][0]["fixture"], "a.pdf");
        assert_eq!(v["fixtures"][0]["cells"][0]["key"], "parameters");
        assert_eq!(v["fixtures"][0]["cells"][0]["status"], "pass");
    }

    #[test]
    fn matrix_one_sided_top_level_key_surfaces_as_unknown_when_not_allowlisted() {
        // Regression for false-negative: if qpdf has a top-level key flpdf is
        // missing (or vice versa), the schema-diff test must FAIL unless the gap
        // is explicitly allowlisted at $.<key>.
        let qpdf = json!({"parameters": {"x": 1}, "qpdf": ["..."]});
        let flpdf = json!({"parameters": {"x": 1}}); // missing "qpdf"
        let mut al = Allowlist::from_json_str(r#"{"entries":[]}"#).unwrap();
        let cells = compute_matrix("f.pdf", &qpdf, &flpdf, &mut al);
        let qpdf_cell = cells.iter().find(|c| c.key == "qpdf").unwrap();
        match &qpdf_cell.status {
            CellStatus::Unknown { divergences } => {
                assert_eq!(divergences.len(), 1);
                assert_eq!(divergences[0].path, "$.qpdf");
                assert!(
                    divergences[0].flpdf.is_null(),
                    "flpdf side must be Null when the key is missing on flpdf"
                );
            }
            other => panic!("expected Unknown for one-sided key, got {other:?}"),
        }
    }

    #[test]
    fn matrix_one_sided_top_level_key_can_be_allowlisted() {
        // When the gap is explicit and allowlisted, the cell becomes Known.
        let qpdf = json!({"parameters": {"x": 1}, "qpdf": ["..."]});
        let flpdf = json!({"parameters": {"x": 1}});
        let allowlist_json = r#"{"entries":[{
            "fixture":"f.pdf","path":"$.qpdf",
            "category":"flpdf-feature-gap","beads_ref":"","reason":"flpdf v2 output skips qpdf section"
        }]}"#;
        let mut al = Allowlist::from_json_str(allowlist_json).unwrap();
        let cells = compute_matrix("f.pdf", &qpdf, &flpdf, &mut al);
        let qpdf_cell = cells.iter().find(|c| c.key == "qpdf").unwrap();
        assert!(matches!(qpdf_cell.status, CellStatus::Known { .. }));
        assert!(al.stale_entries().is_empty());
    }

    #[test]
    fn matrix_unknown_cell_excludes_allowlisted_siblings() {
        // When a cell has both allowlisted and non-allowlisted divergences, the
        // Unknown variant must contain ONLY the unknown ones — otherwise
        // unknown_divergences() (and the test failure message) wrongly lists
        // allowlisted divergences as unknown.
        let qpdf = json!({"parameters": {"a_unknown": 1, "z_allowed": 2}});
        let flpdf = json!({"parameters": {"a_unknown": 9, "z_allowed": 8}});
        let allowlist_json = r#"{"entries":[{
            "fixture":"f.pdf","path":"$.parameters.z_allowed",
            "category":"x","beads_ref":"","reason":""
        }]}"#;
        let mut al = Allowlist::from_json_str(allowlist_json).unwrap();
        let cells = compute_matrix("f.pdf", &qpdf, &flpdf, &mut al);
        let params = cells.iter().find(|c| c.key == "parameters").unwrap();
        match &params.status {
            CellStatus::Unknown { divergences } => {
                assert_eq!(
                    divergences.len(),
                    1,
                    "Unknown must contain only unknown divs, got {} ({:?})",
                    divergences.len(),
                    divergences.iter().map(|d| &d.path).collect::<Vec<_>>(),
                );
                assert_eq!(divergences[0].path, "$.parameters.a_unknown");
            }
            other => panic!("expected Unknown, got {other:?}"),
        }
        // The allowlist entry was still marked as used (no stale).
        assert!(al.stale_entries().is_empty());
    }

    #[test]
    fn matrix_marks_later_allowlisted_div_even_when_earlier_is_unknown() {
        // Regression: compute_matrix must visit every divergence in a cell to
        // mark allowlist entries as used. If classification short-circuits on
        // the first unknown, a sibling allowlisted divergence is left unmarked
        // and stale_entries() returns a false positive — which would fail the
        // Task 7 corpus runner's stale_allowlist.is_empty() assertion.
        //
        // Key names a_unknown / z_allowed force alphabetical ordering inside
        // serde_json::Map (a BTreeMap by default) so the unknown appears first.
        let qpdf = json!({"parameters": {"a_unknown": 1, "z_allowed": 2}});
        let flpdf = json!({"parameters": {"a_unknown": 9, "z_allowed": 8}});
        let allowlist_json = r#"{"entries":[{
            "fixture":"f.pdf","path":"$.parameters.z_allowed",
            "category":"x","beads_ref":"","reason":""
        }]}"#;
        let mut al = Allowlist::from_json_str(allowlist_json).unwrap();
        let _ = compute_matrix("f.pdf", &qpdf, &flpdf, &mut al);
        assert!(
            al.stale_entries().is_empty(),
            "allowlist entry must be matched even when a sibling is unknown; stale = {:?}",
            al.stale_entries()
                .iter()
                .map(|e| &e.path)
                .collect::<Vec<_>>(),
        );
    }
}