ridl-diff 0.15.0

The `ridl diff` engine: compares two resolved IR snapshots and classifies every difference.
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
//! The `ridl diff` IR-snapshot compare engine.
//!
//! The engine compares two resolved IR v2 snapshots and classifies every
//! difference as a [`Change`] with a [`Category`] and a [`Verdict`]. It reads
//! only the IR — never source — so the comparison is honest against exactly
//! what a backend sees (ADR-0008 decision 14, concept note §9.1). Placement is
//! deliberate: this crate is an engine surfaced by the `ridl` facade, never by
//! `ridlc`, so the compiler stays a pure source→IR function (the ISO 26262
//! tool-qualification boundary, ADR-0008 decision 9).
//!
//! The comparison has two halves. The walk ([`walk`]) says *what* structurally
//! differs, emitting one [`Change`] per difference with a [`Category`]; the
//! classifier ([`classify`]) says which *direction* that difference moved
//! in and settles its [`Verdict`]. Splitting them is what lets a single
//! structural category — an appended interaction, a changed timing — carry
//! opposite verdicts depending on the direction, without the walk needing both
//! snapshots at every emission site.
//!
//! This module owns the vocabulary ([`Verdict`], [`Category`], [`Change`],
//! [`DiffReport`]), the set-level comparison ([`diff_sets`], and
//! [`diff_workspaces`] with the system headings of [`system`]), and rendering
//! ([`render_text`], [`render_json`]). It re-exports the snapshot loader
//! [`load_ir_json`] from `ridl-ir`, which owns it. The
//! classification table itself is documented per category by [`explain`], which
//! `ridl diff --explain` prints.

use ridl_ir::v2::{Package, System};

mod classify;
mod remote_inline;
pub mod system;
pub mod unit_verdict;
mod walk;

pub use classify::{absence_refused, category_from_word, classify, explain, is_above_high_water};
// Re-exported under its earlier path (ADR-0008 decision 9).
pub use ridl_ir::v2::{LoadError, load_ir_json};
pub use system::{SystemChange, SystemHeading, diff_systems};
pub use unit_verdict::{UnitVerdicts, unit_verdict};

#[cfg(test)]
mod tests;

/// The compatibility verdict of a change or of a whole report — ordered so
/// `Breaking > Compatible > Identical` and a report's verdict is the maximum
/// over its changes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Verdict {
    /// No differences at all.
    Identical,
    /// A consumer built against the old snapshot still works.
    Compatible,
    /// A consumer built against the old snapshot may break.
    Breaking,
}

/// Declares the [`Category`] vocabulary once (ADR-0008 decision 21).
///
/// One list of variants expands to both the enum and the [`CATEGORIES`] array
/// that `ridl diff --explain` iterates, so a variant that never reaches
/// `CATEGORIES` cannot be written: there is no second list to forget. This
/// replaces the guard PR #163 shipped, which expanded one list into an
/// exhaustive `match` and an array *inside the test* — that narrowed the gap but
/// left `CATEGORIES` shadowed rather than produced, and an assertion comparing
/// two lists can be defeated by editing what feeds it.
///
/// A new variant therefore stops three functions compiling — [`classify`],
/// [`explain`], and [`category_word`] — and reaches `CATEGORIES` with no second
/// edit. The escape rustc's own `help:` text proposes for those three errors is
/// a wildcard arm. Each of the three functions denies
/// `clippy::wildcard_enum_match_arm` and
/// `clippy::match_wildcard_for_single_variants` for exactly that reason. The
/// second lint is the load-bearing one: the first does not fire when the
/// wildcard covers a single variant, which is precisely the added-variant case,
/// so denying it alone leaves clippy green.
///
/// How far the wildcard gets before clippy stops it depends on what its body
/// says. `_ => todo!()` panics the `--explain` coverage test, and a bare
/// `_ => "unknown"` fails it — the row names no verdict. A wildcard whose text
/// happens to contain "compatible" passes all 115 tests. So the escape is real
/// but narrow, and `cargo test` alone catches the two careless spellings of it.
/// `just build` runs clippy so that the third is caught too.
///
/// What this does **not** close: rustc forces *an* arm, not the right one. A
/// new variant given an explicit arm that classifies compatible, or whose rule
/// row describes the wrong rule, still compiles and still passes. The [`explain`]
/// coverage test checks that each row names a verdict and that its word
/// round-trips; neither is proof that the row is correct.
macro_rules! declare_categories {
    (
        $(#[$enum_meta:meta])*
        $vis:vis enum $name:ident {
            $(
                $(#[$variant_meta:meta])*
                $variant:ident,
            )+
        }
    ) => {
        $(#[$enum_meta])*
        $vis enum $name {
            $(
                $(#[$variant_meta])*
                $variant,
            )+
        }

        /// Every category, in the order `--explain` lists them when asked for an
        /// unknown one.
        ///
        /// Generated from the [`Category`] declaration by
        /// [`declare_categories!`], not maintained beside it.
        //
        // The length counts the variants rather than being written down:
        // `${count(...)}` is still unstable (rust-lang/rust#83527), so the
        // count comes from the same repetition that fills the array.
        pub const CATEGORIES: [$name; [$(stringify!($variant)),+].len()] =
            [$($name::$variant),+];
    };
}

declare_categories! {
    /// The kind of a single difference. The walk emits the structural categories;
    /// the classifier maps them to directional verdicts.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub enum Category {
        /// A package-level declaration, interface, or service present only in the
        /// new snapshot.
        DeclAdded,
        /// A package-level declaration, interface, or service present only in the
        /// old snapshot. An interface is matched by its `interfaces.lock`
        /// number (lock design §7), so an interface here is one whose number
        /// is gone from the new snapshot and not retired there.
        DeclRemoved,
        /// An interface whose `interfaces.lock` number is the same on both
        /// sides and whose name changed (lock design §7). The number is the
        /// interface's identity and its routing key, so nothing moves on the
        /// wire; a rename is visible in source — it changes the generated
        /// identity-table names in both wire backends — so the text report
        /// lists it under the heading ([`heading`]). The path carries the new
        /// name; the detail carries the old and the new name.
        InterfaceRenamed,
        /// An interface whose number the old snapshot held and the new
        /// snapshot's retired entries list (lock design §7): the sanctioned
        /// removal of an interface, recorded by `ridl lock --retire`.
        InterfaceRetired,
        /// An interface matched by name across a provisional old side whose
        /// number is the same on both sides and whose provisional flag went
        /// from true to false: the number `ridl lock` froze in place. Nothing
        /// moves on the wire, but the catalog hash covers the number and the
        /// flag, so the hash changes and the text report lists it under the
        /// heading "compatible on the wire, may change the catalog hash"
        /// ([`heading`]). A number 0 on
        /// either side, from a snapshot written before the lock existed, is
        /// not compared. The path carries the name; the detail carries the
        /// old and the new number, each marked when it is provisional.
        InterfaceFrozen,
        /// A matched interface whose number differs between the two sides,
        /// whatever the two flags: a provisional number moved by a sibling
        /// added before it, or frozen as another number. The number is the
        /// routing key, so the change is breaking. A number 0 on either side,
        /// from a snapshot written before the lock existed, is not compared. The
        /// detail carries the old and the new number, each marked when it is
        /// provisional.
        InterfaceNumberChanged,
        /// A surviving composite member whose slot in the body changed — a
        /// struct field, enum value, enum-set bit or union arm — reported only
        /// when both bodies hold the same member names. For a struct field or
        /// union arm the slot is the ordinal, which is wire identity (typl
        /// §7.4), and the detail carries the old and new ordinal. An enum value
        /// or enum-set bit takes its identity from the explicit number it
        /// declares instead (typl §8, §9), so its slot is that number: the
        /// category reports a member whose number changed, with the old and
        /// new value or bit in the detail. When every difference between the
        /// two bodies is a changed number, the container's
        /// [`Category::ConstraintChanged`] is not reported beside it. A body
        /// of an enum or an enum set that differs only in order is
        /// [`Category::EnumReordered`] instead.
        MemberReordered,
        /// An enum or enum-set body whose difference is only order: its live
        /// values or bits reordered with no number changed, the enum's
        /// `reserved` list reordered with no entry added, removed or changed,
        /// or both. A value or bit takes its identity from the explicit number
        /// it declares (typl §8, §9), so nothing moves on the wire. The catalog
        /// hash covers only the declarations an interface reaches; when an
        /// interface reaches the enum or enum set, the order of its values or
        /// bits, and of an enum's reserved list, is part of the hash, so the
        /// hash changes then. The text report lists it under the heading that
        /// [`Category::InterfaceFrozen`] shares ([`heading`]). The path is the
        /// container's; there is no detail.
        EnumReordered,
        /// A new interaction added at the end of an interface (no earlier
        /// interaction shifted).
        InteractionAppended,
        /// A new interaction added before the end — an earlier interaction now
        /// sits after it (ridl §11: insert shifts ordinals, a wire break).
        InteractionInserted,
        /// A surviving interaction whose relative order within the interface
        /// changed (ridl §11: reorder shifts ordinals, a wire break).
        InteractionReordered,
        /// An interaction removed without leaving a `reserved` tombstone.
        InteractionRemoved,
        /// An interaction removed and replaced by a `reserved` tombstone in the
        /// same slot (ridl §11).
        InteractionRetired,
        /// A surviving interaction whose kind changed (signal ↔ event, etc.).
        KindChanged,
        /// A signal/event/fixed payload type changed.
        PayloadChanged,
        /// A query return type changed.
        ReturnChanged,
        /// A command/query parameter list changed.
        ParamsChanged,
        /// A signal/event resolved timing changed.
        TimingChanged,
        /// A command/query declared RPC bound changed (ADR-0015 decision 8).
        /// Separate from [`Category::TimingChanged`] because the direction of
        /// `min` inverts: on an RPC it constrains the caller, not the
        /// provider, so the signal/event rule must not be inherited silently.
        RpcBoundChanged,
        /// The payload limit declared for an interaction changed, was added or
        /// was removed (ADR-0030 decision 13). Any change is breaking: the
        /// limit is part of the catalog hash, so peers with different limits
        /// do not attach.
        LimitChanged,
        /// A command/query require/ensure clause set changed.
        ContractChanged,
        /// A name-paired interaction's family or operation shape changed
        /// (ADR-0012 decision 6).
        InteractionClassChanged,
        /// A derived wire width or scalar backing changed.
        WidthChanged,
        /// A scalar constraint (range, step, length, pattern) changed, or a
        /// composite member changed in place.
        ConstraintChanged,
        /// A resolved or declared init value changed.
        InitChanged,
        /// A name that was a `reserved` tombstone is live again — an
        /// interaction inside an interface body.
        ReservedNameRedeclared,
        /// A service switched between the named list and an inline shape.
        /// Narrowed to the form switch by ADR-0015 decision 19: a changed
        /// list is read as a set by the two `ServiceInterface*` categories
        /// below.
        ServiceChanged,
        /// An interface in a service's set that the old snapshot's set did not
        /// hold (ADR-0015 decision 19 as amended on 2026-09-15: a service's
        /// list is a set of interface references).
        ServiceInterfaceAdded,
        /// An interface the old snapshot's set held that the new one does not.
        /// Compatible on the wire — the routing key does not contain the
        /// service — and visible in source, so the text report lists it under
        /// that heading ([`heading`]).
        ServiceInterfaceRemoved,
        /// Only doc comment, labels, or deprecation metadata changed.
        DocOnly,
        /// The visibility a declaration is published at changed. Separate from
        /// [`Category::DocOnly`] because `internal` removes the declaration from
        /// every out-of-package consumer (ADR-0002 §8), so the change has a
        /// direction.
        VisibilityChanged,
        /// A struct field appended, compatible under the generic rule, to a
        /// struct another head of the old side holds inline, when the field
        /// does not fit entirely inside the old head: the layout law places
        /// any of its bytes past the old head's size (ADR-0031 decision 10,
        /// the inline-append rule;
        /// `ridl diff --explain podbuf_inline_append` states it in full).
        /// Breaking when the comparison is judged for the `podbuf` encoding,
        /// compatible otherwise, listed under the heading "breaking under
        /// podbuf" ([`heading`]). The path is the appended field's; the
        /// detail names each inline use of the old side, a struct field as
        /// `<package>/<struct>/<field>` and an interaction's request, reply
        /// or fixed payload as `<package>/<interface>/<interaction>`.
        PodbufInlineAppend,
        /// A remote declaration held inline by an old consumer has a larger podbuf size.
        PodbufRemoteInlineGrowth,
        /// An enum value, an enum-set flag or a union arm appended, compatible
        /// under the generic rule, after which the podbuf integer of the enum
        /// or the enum set or the tag of the union is a different integer, by
        /// width or by signedness (ADR-0031 decision 10, the width rule;
        /// `ridl diff --explain podbuf_width_change` states it in full).
        /// Breaking when `podbuf` is among the encodings the comparison is
        /// judged for, compatible otherwise. Reported once per declaration,
        /// at `<package>/<decl>`, with the old and the new integer.
        PodbufWidthChange,
        /// Superseded by [`Category::StrictEnumAppend`], which is breaking for
        /// every encoding. The variant stays so that a report or a consumer
        /// that names the category still compiles; `ridl diff` no longer
        /// reports it.
        PodbufStrictEnumAppend,
        /// An enum value or an enum-set flag appended to an enum or an enum
        /// set that is not `open` (ADR-0031 decision 12). A reader built from
        /// the old declaration refuses a value or a flag it does not name, in
        /// the `verify` of podbuf and in the codec of every other encoding
        /// that checks the declaration, so the append is breaking for every
        /// encoding. Reported once per declaration, at `<package>/<decl>`,
        /// with the appended names in the detail. The same append to an
        /// `open` declaration is compatible.
        StrictEnumAppend,
        /// An enum or an enum set that gained the `open` keyword: every
        /// reader of the old declaration already accepts the values it
        /// named, so the change is compatible. Reported at
        /// `<package>/<decl>`.
        EnumOpened,
        /// An enum or an enum set that lost the `open` keyword: a reader of
        /// the new declaration refuses a value that a producer of the old one
        /// may still send, so the change is breaking. Reported at
        /// `<package>/<decl>`.
        EnumClosed,
        /// An enum value or an enum-set flag appended, compatible under the
        /// generic rule, after which the FlatBuffers integer of the enum or
        /// the enum set is a different integer (ADR-0019 decision 10;
        /// `ridl diff --explain flatbuffers_width_change` states it in full).
        /// Breaking when `flatbuffers` is among the encodings the comparison
        /// is judged for, compatible otherwise. Reported once per declaration,
        /// at `<package>/<decl>`, with the old and the new integer.
        /// With per-side contexts, a remote declaration reached by a surviving
        /// old consumer use is reported once per consumer path and remote
        /// declaration, at the consumer path, with
        /// `<remote declaration>: <integer>` values. A side without remote
        /// context draws no remote width line; shared-context entry points
        /// do not report remote widths.
        FlatbuffersWidthChange,
        /// An enum-set flag appended, compatible under the generic rule,
        /// after which the proto3 scalar of the enum set is a different
        /// scalar (ADR-0017 decision 9;
        /// `ridl diff --explain proto3_width_change` states it in full).
        /// Breaking when `proto3` is among the encodings the comparison is
        /// judged for, compatible otherwise. Reported once per declaration,
        /// at `<package>/<decl>`, with the old and the new proto3 scalar.
        /// With per-side contexts, a remote declaration reached by a surviving
        /// old consumer use is reported once per consumer path and remote
        /// declaration, at the consumer path, with
        /// `<remote declaration>: <integer>` values. A side without remote
        /// context draws no remote width line; shared-context entry points
        /// do not report remote widths.
        Proto3WidthChange,
    }
}

/// One difference between two snapshots, with an honest path into the IR and
/// the rendered before/after values where they apply.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Change {
    /// A slash-separated path, e.g. `veh.cluster/VehicleStatus/doorOpened`.
    pub path: String,
    pub category: Category,
    pub verdict: Verdict,
    /// The rendered old value, absent when the change is an addition.
    pub before: Option<String>,
    /// The rendered new value, absent when the change is a removal.
    pub after: Option<String>,
}

impl Change {
    /// The dotted name of the package the change belongs to: the first
    /// segment of [`path`](Change::path). The walk builds the path as
    /// `<package>/<name>[/<member>...]`, and this accessor and
    /// [`declaration`](Change::declaration) are the one place that reads that
    /// layout back.
    pub fn package(&self) -> &str {
        self.path.split('/').next().unwrap_or_default()
    }

    /// The bare name of the package-level declaration, interface or service
    /// the change belongs to: the second segment of [`path`](Change::path), or
    /// `None` for a change to the package itself.
    pub fn declaration(&self) -> Option<&str> {
        self.path.split('/').nth(1)
    }
}

/// The result of a comparison: every change and the report-level verdict (the
/// maximum verdict over the changes; [`Verdict::Identical`] when there are
/// none).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DiffReport {
    pub changes: Vec<Change>,
    pub verdict: Verdict,
    /// The changes to the lowered system, each under its heading (rsdl
    /// reference §14). Only a change under
    /// [`SystemHeading::InstanceNumberChanged`] enters `verdict`, as breaking;
    /// the other headings carry no verdict. Empty unless
    /// both sides carry a system ([`diff_workspaces`]).
    pub system: Vec<SystemChange>,
}

/// Appends one change.
///
/// The verdict is stamped breaking here and settled by [`classify`] once the
/// walk of the containing package pair is complete — the classifier needs both
/// snapshots, which the walk does not carry down to every emission site.
/// Breaking is the safe placeholder: a change that somehow escaped
/// classification would gate rather than pass.
pub(crate) fn emit(
    changes: &mut Vec<Change>,
    path: String,
    category: Category,
    before: Option<String>,
    after: Option<String>,
) {
    changes.push(Change {
        path,
        category,
        verdict: Verdict::Breaking,
        before,
        after,
    });
}

/// Whether an interface carries an identity: a frozen, non-zero number from
/// its unit's `interfaces.lock` (lock design §7). A provisional number is
/// no identity, and `number` 0 — never allocated — marks a snapshot published
/// before the lock existed. The walk matches by number only when both sides
/// have one, and the classifier re-finds the old side the same way.
pub(crate) fn frozen(interface: &ridl_ir::v2::Interface) -> bool {
    interface.number != 0 && !interface.provisional
}

/// Settles the verdict of every change the walk of one package pair produced.
/// `scope` is every package a reference to another package's declaration
/// resolves against ([`classify::classify_in`]); `encodings` is the list the
/// comparison is judged for ([`diff_refs_with`]).
///
/// A change's new side is in `new`, except for an interface whose number
/// moved to another package of the unit: the walk puts that package first in
/// the change's path, and the classifier reads the new side from it, so the
/// package is taken from `scope`, which holds every package of the new set.
fn classify_all(
    changes: &mut [Change],
    old: &Package,
    new: &Package,
    scope: &[&Package],
    encodings: &[&str],
) {
    for change in changes {
        let held_by = change.path.split('/').next().unwrap_or_default();
        let new = if held_by == new.name {
            new
        } else {
            scope
                .iter()
                .copied()
                .find(|package| package.name == held_by)
                .unwrap_or(new)
        };
        change.verdict = classify::classify_in(change, old, new, scope, encodings);
    }
}

/// Assembles a [`DiffReport`], deriving the report verdict as the maximum over
/// its changes.
pub(crate) fn report(changes: Vec<Change>) -> DiffReport {
    let verdict = changes
        .iter()
        .map(|change| change.verdict)
        .max()
        .unwrap_or(Verdict::Identical);
    DiffReport {
        changes,
        verdict,
        system: Vec::new(),
    }
}

/// Compares two resolved packages. Matched packages share a name; the new
/// package's name is used as the path prefix.
///
/// Only the pair is in hand, so a type from another package does not resolve,
/// and a type the diff cannot resolve is reported as breaking: a struct field
/// appended with such a type classifies breaking (driftsys/ridl#598).
/// [`diff_sets_in`] resolves it.
pub fn diff_packages(old: &Package, new: &Package) -> DiffReport {
    let matching = walk::Matching::new(&[old], &[new]);
    let mut changes = Vec::new();
    walk::walk_packages(old, new, &matching, &mut changes);
    let mut changes = walk::fold_strict_enum_appends(changes, old, new);
    classify_all(&mut changes, old, new, &[], &[]);
    report(changes)
}

/// Compares two sets of resolved packages, matching by package name, and
/// interface numbers within each unit ([`walk::Matching`]). A package present
/// only on the new side is a [`Category::DeclAdded`]; matched packages are
/// walked pairwise. A package present only on the old side is a
/// [`Category::DeclRemoved`] when its whole unit is gone from the new side,
/// and is walked declaration by declaration when the unit is still there, so
/// that an interface whose number moved to another package of the unit is
/// [`Category::InterfaceRenamed`] and one the unit retired is
/// [`Category::InterfaceRetired`].
///
/// [`diff_sets_in`] with no context: a type from a package outside `new`, such
/// as `ridl.std`, which no snapshot carries, does not resolve, and a type the
/// diff cannot resolve is reported as breaking.
pub fn diff_sets(old: &[Package], new: &[Package]) -> DiffReport {
    diff_sets_in(old, new, &[])
}

/// [`diff_sets`], with `context`: packages that a type reference resolves
/// against without being compared. This entry point shares one context.
/// `ridl diff` and the MCP server use per-side contexts through
/// [`diff_workspaces_with_contexts`]: the built-in `ridl.std` plus each side's
/// own remote packages, compiled from source or retained in a snapshot
/// directory, so historical layouts never borrow current remote definitions.
/// `ridl check`'s baseline desk check passes one shared context and judges no encoding.
pub fn diff_sets_in(old: &[Package], new: &[Package], context: &[Package]) -> DiffReport {
    let old: Vec<&Package> = old.iter().collect();
    let new: Vec<&Package> = new.iter().collect();
    let context: Vec<&Package> = context.iter().collect();
    diff_refs_in(&old, &new, &context)
}

/// [`diff_sets_in`] over borrowed packages, for a caller that holds the
/// packages by reference and would otherwise clone them. The comparison is
/// judged for no encoding: [`diff_refs_with`] with an empty list.
pub fn diff_refs_in(old: &[&Package], new: &[&Package], context: &[&Package]) -> DiffReport {
    diff_refs_with(old, new, context, &[])
}

/// [`diff_refs_in`], judged for `encodings`: the names a `[backend.<name>]
/// encodings` list writes (`flatbuffers`, `proto3`, `podbuf`). A snapshot
/// does not carry the encodings a workspace builds, so the caller names them.
///
/// Each of the three names has rules of its own: a struct field appended that
/// does not fit inside the old head of a struct another head of the old
/// side holds inline is [`Category::PodbufInlineAppend`], and an enum value,
/// an enum-set flag or a union arm appended that changes the integer of the
/// enum or the enum set or the union's tag is [`Category::PodbufWidthChange`];
/// each is
/// breaking when `podbuf` is in `encodings` and compatible otherwise. An enum
/// value or an enum-set flag appended to a declaration that is not `open` is
/// [`Category::StrictEnumAppend`], breaking under every list. An enum value or
/// an enum-set flag appended that changes the FlatBuffers integer is
/// [`Category::FlatbuffersWidthChange`], breaking when `flatbuffers` is in
/// `encodings` and compatible otherwise. An enum-set flag appended that
/// changes the proto3 scalar is [`Category::Proto3WidthChange`], breaking
/// when `proto3` is in `encodings` and compatible otherwise. Every other
/// category is judged the same under every list. The CLI and the MCP tool
/// refuse a name that is not one of the three before calling this; the engine
/// does not check it.
/// The podbuf rule lays the old side out over `old` and the context packages
/// `old` does not name, and the new side over `new` and `context`; a package
/// in both `new` and `context` is read at its first occurrence.
pub fn diff_refs_with(
    old: &[&Package],
    new: &[&Package],
    context: &[&Package],
    encodings: &[&str],
) -> DiffReport {
    diff_refs_scoped(old, new, context, context, encodings)
}

/// The side whose remote evidence cannot establish inline compatibility.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum ContextSide {
    Old,
    New,
}

impl std::fmt::Display for ContextSide {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Old => "old",
            Self::New => "new",
        })
    }
}

/// Why remote evidence cannot establish inline compatibility.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum ContextIssueReason {
    Missing,
    Unlayable,
    KindChanged,
}

/// Unusable evidence for a consumer-owned podbuf comparison.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct ContextIssue {
    pub path: String,
    pub declaration: String,
    pub side: ContextSide,
    pub reason: ContextIssueReason,
}

impl std::fmt::Display for ContextIssue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.reason {
            ContextIssueReason::Missing => write!(
                f,
                "{}: {} context is missing {}",
                self.path, self.side, self.declaration
            ),
            ContextIssueReason::Unlayable => write!(
                f,
                "{}: {} context cannot lay out {}",
                self.path, self.side, self.declaration
            ),
            ContextIssueReason::KindChanged => write!(
                f,
                "{}: {} context changes {} from a struct to another declaration kind",
                self.path, self.side, self.declaration
            ),
        }
    }
}

/// An explicit podbuf comparison cannot use its own side's remote evidence.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContextError {
    pub issues: Vec<ContextIssue>,
}

impl std::fmt::Display for ContextError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (index, issue) in self.issues.iter().enumerate() {
            if index != 0 {
                f.write_str("; ")?;
            }
            write!(f, "{issue}")?;
        }
        Ok(())
    }
}
impl std::error::Error for ContextError {}

/// Compares packages using independent source-side resolution scopes.
/// Missing remote evidence prevents only an explicit podbuf judgment.
/// Context packages resolve references without being compared themselves.
/// Local packages take precedence over context packages with the same name.
/// Growth is reported once per old consumer path and remote declaration;
/// issues are sorted by consumer path, declaration, then side.
pub fn diff_refs_with_contexts(
    old: &[&Package],
    new: &[&Package],
    old_context: &[&Package],
    new_context: &[&Package],
    encodings: &[&str],
) -> Result<DiffReport, ContextError> {
    let (result, issues) =
        diff_refs_with_contexts_partial(old, new, old_context, new_context, encodings);
    if encodings.contains(&"podbuf") && !issues.is_empty() {
        return Err(ContextError { issues });
    }
    Ok(result)
}

/// Compares complete scopes while retaining independent missing-evidence issues.
/// The report is not an affirmative compatibility judgment for any unit that
/// owns or reaches an issue's consumer declaration. Such units require recovery;
/// callers may use the report's proved verdicts for unaffected units.
/// Remote FlatBuffers and proto3 widths are reported once per consumer path
/// and remote declaration reached by a surviving old consumer use, at the
/// consumer path, with `<remote declaration>: <integer>` values. Only the
/// per-side context entry points report remote widths; a side without remote
/// context draws no such line.
pub fn diff_refs_with_contexts_partial(
    old: &[&Package],
    new: &[&Package],
    old_context: &[&Package],
    new_context: &[&Package],
    encodings: &[&str],
) -> (DiffReport, Vec<ContextIssue>) {
    let old_scope: Vec<_> = old.iter().chain(old_context).copied().collect();
    let new_scope: Vec<_> = new.iter().chain(new_context).copied().collect();
    let (mut remote, issues) = remote_inline::compare(old, new, &old_scope, &new_scope, encodings);
    let mut result = diff_refs_scoped(old, new, old_context, new_context, encodings);
    result.changes.append(&mut remote);
    (report(result.changes), issues)
}

fn diff_refs_scoped(
    old: &[&Package],
    new: &[&Package],
    old_context: &[&Package],
    new_context: &[&Package],
    encodings: &[&str],
) -> DiffReport {
    use std::collections::BTreeMap;

    use ridl_ir::v2::{members_of_unit, unit_of};

    let scope: Vec<&Package> = new.iter().chain(new_context).copied().collect();
    let matching = walk::Matching::new(old, new);

    let old_by: BTreeMap<&str, &Package> =
        old.iter().map(|pkg| (pkg.name.as_str(), *pkg)).collect();
    let new_by: BTreeMap<&str, &Package> =
        new.iter().map(|pkg| (pkg.name.as_str(), *pkg)).collect();
    // Old packages take precedence over their own context, independently
    // of the new side's definitions.
    let old_scope: Vec<&Package> = old
        .iter()
        .copied()
        .chain(
            old_context
                .iter()
                .copied()
                .filter(|pkg| !old_by.contains_key(pkg.name.as_str())),
        )
        .collect();

    // Each matched pair is walked and classified against its own two snapshots,
    // because the classifier resolves a change's path back into the packages it
    // came from.
    let mut changes = Vec::new();
    for (name, old_pkg) in &old_by {
        match new_by.get(name) {
            Some(new_pkg) => {
                let mut pair = Vec::new();
                walk::walk_packages(old_pkg, new_pkg, &matching, &mut pair);
                let mut pair = walk::fold_strict_enum_appends(pair, old_pkg, new_pkg);
                classify_all(&mut pair, old_pkg, new_pkg, &scope, encodings);
                // The encoding rules read the settled verdicts of the pair
                // and the heads of both whole sides, so they run after the
                // walk and the classifier of the pair.
                let mut encoding_changes =
                    walk::podbuf_inline_appends(&pair, old, &old_scope, &scope);
                encoding_changes.append(&mut walk::podbuf_width_changes(&pair, old_pkg, new_pkg));
                encoding_changes.append(&mut walk::flatbuffers_width_changes(
                    &pair, old_pkg, new_pkg,
                ));
                encoding_changes.append(&mut walk::proto3_width_changes(&pair, old_pkg, new_pkg));
                classify_all(&mut encoding_changes, old_pkg, new_pkg, &scope, encodings);
                pair.append(&mut encoding_changes);
                changes.append(&mut pair);
            }
            // A package gone while its unit stays: walked against a package
            // with nothing in it, so that each shape is matched in the unit,
            // retired by the unit, or removed, and each other declaration is
            // removed on its own line.
            None if members_of_unit(unit_of(old_pkg), new).next().is_some() => {
                let gone = Package {
                    name: old_pkg.name.clone(),
                    unit: old_pkg.unit.clone(),
                    ..Default::default()
                };
                let mut pair = Vec::new();
                walk::walk_packages(old_pkg, &gone, &matching, &mut pair);
                classify_all(&mut pair, old_pkg, &gone, &scope, encodings);
                changes.append(&mut pair);
            }
            // A package present on one side only: the change classifies on its
            // category alone, so the one snapshot stands for both.
            None => {
                let mut pair = Vec::new();
                emit(
                    &mut pair,
                    (*name).to_string(),
                    Category::DeclRemoved,
                    Some(format!("package {name}")),
                    None,
                );
                classify_all(&mut pair, old_pkg, old_pkg, &[], encodings);
                changes.append(&mut pair);
            }
        }
    }
    for (name, new_pkg) in &new_by {
        if !old_by.contains_key(name) {
            let mut pair = Vec::new();
            emit(
                &mut pair,
                (*name).to_string(),
                Category::DeclAdded,
                None,
                Some(format!("package {name}")),
            );
            classify_all(&mut pair, new_pkg, new_pkg, &[], encodings);
            changes.append(&mut pair);
        }
    }
    report(changes)
}

/// Compares two workspaces at the system (rsdl reference §14): the packages by
/// the ridl categories, exactly as [`diff_sets`] does, and — when both sides
/// carry a lowered system — the system's placement and composition changes,
/// which carry no verdict, and its instance number changes, which make the
/// report breaking. A system on one side only is not compared: there is
/// nothing to compare it against.
///
/// `context` is passed to [`diff_sets_in`]. The comparison is judged for no
/// encoding: [`diff_workspaces_with`] with an empty list.
pub fn diff_workspaces(
    old: &[Package],
    old_system: Option<&System>,
    new: &[Package],
    new_system: Option<&System>,
    context: &[Package],
) -> DiffReport {
    diff_workspaces_with(old, old_system, new, new_system, context, &[])
}

/// [`diff_workspaces`], judged for `encodings` ([`diff_refs_with`]).
pub fn diff_workspaces_with(
    old: &[Package],
    old_system: Option<&System>,
    new: &[Package],
    new_system: Option<&System>,
    context: &[Package],
    encodings: &[&str],
) -> DiffReport {
    let old: Vec<&Package> = old.iter().collect();
    let new: Vec<&Package> = new.iter().collect();
    let context: Vec<&Package> = context.iter().collect();
    let mut report = diff_refs_with(&old, &new, &context, encodings);
    if let (Some(old_system), Some(new_system)) = (old_system, new_system) {
        report.system = diff_systems(old_system, new_system);
        if report
            .system
            .iter()
            .any(|change| change.heading == SystemHeading::InstanceNumberChanged)
        {
            report.verdict = Verdict::Breaking;
        }
    }
    report
}

/// Compares workspace packages with independent side contexts and, when both
/// sides carry a system, lists the system changes, of which only an instance
/// number change enters the verdict, as breaking ([`diff_workspaces_with`]).
/// Missing remote evidence is an error for an explicit podbuf comparison.
pub fn diff_workspaces_with_contexts(
    old: &[Package],
    old_system: Option<&System>,
    new: &[Package],
    new_system: Option<&System>,
    old_context: &[Package],
    new_context: &[Package],
    encodings: &[&str],
) -> Result<DiffReport, ContextError> {
    let old: Vec<&Package> = old.iter().collect();
    let new: Vec<&Package> = new.iter().collect();
    let old_context: Vec<&Package> = old_context.iter().collect();
    let new_context: Vec<&Package> = new_context.iter().collect();
    let mut report = diff_refs_with_contexts(&old, &new, &old_context, &new_context, encodings)?;
    if let (Some(old_system), Some(new_system)) = (old_system, new_system) {
        report.system = diff_systems(old_system, new_system);
        if report
            .system
            .iter()
            .any(|change| change.heading == SystemHeading::InstanceNumberChanged)
        {
            report.verdict = Verdict::Breaking;
        }
    }
    Ok(report)
}

/// The stable lowercase word for a verdict — used by both the text and JSON
/// renderers so the two stay in lockstep.
pub(crate) fn verdict_word(verdict: Verdict) -> &'static str {
    match verdict {
        Verdict::Identical => "identical",
        Verdict::Compatible => "compatible",
        Verdict::Breaking => "breaking",
    }
}

/// The stable snake_case word for a category — the single source of truth for
/// both renderers and for `ridl diff --explain`, which takes a category exactly
/// as the report prints it.
// A new variant must be given a real arm here, not swept into a
// catch-all: rustc forces *an* arm, and the arm its `help:` text
// proposes is `_ =>`, which classifies the new variant silently. The
// two lints below reject a wildcard over `Category` — the first when
// it covers several variants, the second when it covers exactly one,
// which is the case one added variant creates.
#[deny(
    clippy::wildcard_enum_match_arm,
    clippy::match_wildcard_for_single_variants
)]
pub fn category_word(category: Category) -> &'static str {
    match category {
        Category::DeclAdded => "decl_added",
        Category::DeclRemoved => "decl_removed",
        Category::InterfaceRenamed => "interface_renamed",
        Category::InterfaceRetired => "interface_retired",
        Category::InterfaceFrozen => "interface_frozen",
        Category::InterfaceNumberChanged => "interface_number_changed",
        Category::MemberReordered => "member_reordered",
        Category::EnumReordered => "enum_reordered",
        Category::InteractionAppended => "interaction_appended",
        Category::InteractionInserted => "interaction_inserted",
        Category::InteractionReordered => "interaction_reordered",
        Category::InteractionRemoved => "interaction_removed",
        Category::InteractionRetired => "interaction_retired",
        Category::KindChanged => "kind_changed",
        Category::PayloadChanged => "payload_changed",
        Category::ReturnChanged => "return_changed",
        Category::ParamsChanged => "params_changed",
        Category::TimingChanged => "timing_changed",
        Category::RpcBoundChanged => "rpc_bound_changed",
        Category::LimitChanged => "limit_changed",
        Category::ContractChanged => "contract_changed",
        Category::InteractionClassChanged => "interaction_class_changed",
        Category::WidthChanged => "width_changed",
        Category::ConstraintChanged => "constraint_changed",
        Category::InitChanged => "init_changed",
        Category::ReservedNameRedeclared => "reserved_name_redeclared",
        Category::ServiceChanged => "service_changed",
        Category::ServiceInterfaceAdded => "service_interface_added",
        Category::ServiceInterfaceRemoved => "service_interface_removed",
        Category::DocOnly => "doc_only",
        Category::VisibilityChanged => "visibility_changed",
        Category::PodbufInlineAppend => "podbuf_inline_append",
        Category::PodbufRemoteInlineGrowth => "podbuf_remote_inline_growth",
        Category::PodbufWidthChange => "podbuf_width_change",
        Category::PodbufStrictEnumAppend => "podbuf_strict_enum_append",
        Category::StrictEnumAppend => "strict_enum_append",
        Category::EnumOpened => "enum_opened",
        Category::EnumClosed => "enum_closed",
        Category::FlatbuffersWidthChange => "flatbuffers_width_change",
        Category::Proto3WidthChange => "proto3_width_change",
    }
}

/// The heading a category's changes are grouped under in the text report, or
/// `None` for a category listed plainly. Five headings exist. "compatible on
/// the wire, visible in source" is for a change that exits 0 but that a
/// consumer sees in its source — an interface renamed on its number changes
/// the generated identity-table names in both wire backends, and an interface
/// leaving a service's set stops the `service.member` addresses of that
/// interface resolving under the service. "compatible on the wire, may change
/// the catalog hash" is for a change that exits 0 but can change the catalog
/// hash, which a generated face compares with its peer's — a number `ridl
/// lock` froze in place, which always changes it, and an enum or enum-set body
/// reordered, which changes it when an interface reaches the enum or enum set
/// (the hash covers only the declarations an interface reaches). "breaking
/// under podbuf" is for a change whose verdict depends on the encodings the
/// comparison is judged for ([`diff_refs_with`]): it exits 0 unless `podbuf`
/// is among them. "breaking under flatbuffers" follows the same rule for
/// `flatbuffers`, and "breaking under proto3" for `proto3`. Each such
/// category's `--explain` text states its own consequence; the JSON report
/// carries the category word and no heading field.
///
/// Wildcard arms are denied for the reason `category_word` gives.
#[deny(
    clippy::wildcard_enum_match_arm,
    clippy::match_wildcard_for_single_variants
)]
pub fn heading(category: Category) -> Option<&'static str> {
    match category {
        Category::InterfaceRenamed | Category::ServiceInterfaceRemoved => {
            Some("compatible on the wire, visible in source")
        }
        Category::InterfaceFrozen | Category::EnumReordered => {
            Some("compatible on the wire, may change the catalog hash")
        }
        Category::PodbufInlineAppend
        | Category::PodbufRemoteInlineGrowth
        | Category::PodbufWidthChange
        | Category::PodbufStrictEnumAppend => Some("breaking under podbuf"),
        Category::FlatbuffersWidthChange => Some("breaking under flatbuffers"),
        Category::Proto3WidthChange => Some("breaking under proto3"),
        Category::DeclAdded
        | Category::DeclRemoved
        | Category::InterfaceRetired
        | Category::InterfaceNumberChanged
        | Category::MemberReordered
        | Category::InteractionAppended
        | Category::InteractionInserted
        | Category::InteractionReordered
        | Category::InteractionRemoved
        | Category::InteractionRetired
        | Category::KindChanged
        | Category::PayloadChanged
        | Category::ReturnChanged
        | Category::ParamsChanged
        | Category::TimingChanged
        | Category::RpcBoundChanged
        | Category::LimitChanged
        | Category::ContractChanged
        | Category::InteractionClassChanged
        | Category::WidthChanged
        | Category::ConstraintChanged
        | Category::InitChanged
        | Category::ReservedNameRedeclared
        | Category::ServiceChanged
        | Category::ServiceInterfaceAdded
        | Category::StrictEnumAppend
        | Category::EnumOpened
        | Category::EnumClosed
        | Category::DocOnly
        | Category::VisibilityChanged => None,
    }
}

impl serde::Serialize for Verdict {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(verdict_word(*self))
    }
}

impl serde::Serialize for Category {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(category_word(*self))
    }
}

impl serde::Serialize for Change {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct as _;
        let mut state = serializer.serialize_struct("Change", 5)?;
        state.serialize_field("path", &self.path)?;
        state.serialize_field("category", &self.category)?;
        state.serialize_field("verdict", &self.verdict)?;
        state.serialize_field("before", &self.before)?;
        state.serialize_field("after", &self.after)?;
        state.end()
    }
}

/// Renders a report as a human-readable summary: the report verdict on the
/// first line, then one indented line per change. A change whose category has
/// no [`heading`] is listed first, in report order; then each heading is
/// printed once, as its own line ending in a colon, followed by the changes
/// under it, in report order. Headings come in [`CATEGORIES`] order.
///
/// After the contract changes come the system headings (rsdl reference §14):
/// each heading that has a change on its own line, then one indented line per
/// change under it, in the `path: before -> after` form. Only the instance
/// number heading carries a verdict, printed after it as `(breaking)`.
pub fn render_text(report: &DiffReport) -> String {
    let mut out = String::new();
    out.push_str(verdict_word(report.verdict));
    out.push('\n');
    for change in &report.changes {
        if heading(change.category).is_none() {
            push_change_line(&mut out, change);
        }
    }
    let mut printed: Vec<&'static str> = Vec::new();
    for category in CATEGORIES {
        let Some(title) = heading(category) else {
            continue;
        };
        if printed.contains(&title) {
            continue;
        }
        printed.push(title);
        let mut under = report
            .changes
            .iter()
            .filter(|change| heading(change.category) == Some(title))
            .peekable();
        if under.peek().is_none() {
            continue;
        }
        out.push_str(title);
        out.push_str(":\n");
        for change in under {
            push_change_line(&mut out, change);
        }
    }
    for heading in [
        SystemHeading::PlacementChanged,
        SystemHeading::CompositionChanged,
        SystemHeading::InstanceNumberChanged,
    ] {
        let mut listed = report
            .system
            .iter()
            .filter(|change| change.heading == heading)
            .peekable();
        if listed.peek().is_none() {
            continue;
        }
        out.push_str(system::heading_text(heading));
        if heading == SystemHeading::InstanceNumberChanged {
            out.push_str(" (breaking)");
        }
        out.push('\n');
        for change in listed {
            out.push_str("  ");
            out.push_str(&change.path);
            push_values(&mut out, change.before.as_ref(), change.after.as_ref());
            out.push('\n');
        }
    }
    out
}

/// One change of the text report: `  [verdict] category path`, then
/// `: before -> after` where the sides apply.
fn push_change_line(out: &mut String, change: &Change) {
    out.push_str("  [");
    out.push_str(verdict_word(change.verdict));
    out.push_str("] ");
    out.push_str(category_word(change.category));
    out.push(' ');
    out.push_str(&change.path);
    push_values(out, change.before.as_ref(), change.after.as_ref());
    out.push('\n');
}

/// The rendered `before -> after` tail of one change line, shared by contract
/// changes and system changes.
fn push_values(out: &mut String, before: Option<&String>, after: Option<&String>) {
    match (before, after) {
        (Some(before), Some(after)) => {
            out.push_str(": ");
            out.push_str(before);
            out.push_str(" -> ");
            out.push_str(after);
        }
        (Some(before), None) => {
            out.push_str(": ");
            out.push_str(before);
            out.push_str(" -> (removed)");
        }
        (None, Some(after)) => {
            out.push_str(": (absent) -> ");
            out.push_str(after);
        }
        (None, None) => {}
    }
}

/// Renders a report as machine-readable JSON with the stable schema
/// `{"verdict", "changes": [{"path", "category", "verdict", "before",
/// "after"}]}`.
pub fn render_json(report: &DiffReport) -> String {
    #[derive(serde::Serialize)]
    struct JsonSystemChange<'a> {
        path: &'a str,
        before: Option<&'a str>,
        after: Option<&'a str>,
    }

    #[derive(serde::Serialize)]
    struct JsonReport<'a> {
        verdict: Verdict,
        changes: &'a [Change],
        #[serde(skip_serializing_if = "Vec::is_empty")]
        placement_changed: Vec<JsonSystemChange<'a>>,
        #[serde(skip_serializing_if = "Vec::is_empty")]
        composition_changed: Vec<JsonSystemChange<'a>>,
        #[serde(skip_serializing_if = "Vec::is_empty")]
        instance_number_changed: Vec<JsonSystemChange<'a>>,
    }

    let under = |heading: SystemHeading| -> Vec<JsonSystemChange<'_>> {
        report
            .system
            .iter()
            .filter(|change| change.heading == heading)
            .map(|change| JsonSystemChange {
                path: &change.path,
                before: change.before.as_deref(),
                after: change.after.as_deref(),
            })
            .collect()
    };
    serde_json::to_string_pretty(&JsonReport {
        verdict: report.verdict,
        changes: &report.changes,
        placement_changed: under(SystemHeading::PlacementChanged),
        composition_changed: under(SystemHeading::CompositionChanged),
        instance_number_changed: under(SystemHeading::InstanceNumberChanged),
    })
    .expect("a diff report holds only string-representable values, so serialization cannot fail")
}