ridl-diff 0.6.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
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
//! The comparison walk over two resolved IR v2 packages.
//!
//! The walk matches package declarations, services, and interactions by name
//! within their container, and interfaces — declared ones and the inline
//! shapes of services alike — by the number each carries from its package's
//! `interfaces.lock` (lock design §7; see `diff_interfaces`). It then compares
//! the aspects that carry contract identity — ordinals, payloads, timings,
//! returns, parameters, contracts, widths, constraints, and inits — emitting
//! one [`Change`](crate::Change) per difference with an honest path.
//!
//! Ordinal analysis (ridl §11) is done on the surviving interactions of an
//! interface. A new slot is [`InteractionAppended`](crate::Category::InteractionAppended)
//! when it sits after every pre-existing slot and
//! [`InteractionInserted`](crate::Category::InteractionInserted) otherwise; a
//! surviving interaction whose *relative* order changed is
//! [`InteractionReordered`](crate::Category::InteractionReordered).
//!
//! A surviving interaction whose *absolute* ordinal shifted while its relative
//! order held is not reported a second time. That suppression is sound only
//! because every cause of such a shift is itself reported as breaking, so the
//! report verdict can never come out compatible while a wire identity moved
//! (ADR-0008 decision 14 lists "shifts or reuses a wire identity" first among
//! breaking changes). The causes are exhaustive:
//!
//! 1. an interaction added ahead of it — `InteractionInserted`;
//! 2. an interaction removed ahead of it with no tombstone —
//!    `InteractionRemoved`;
//! 3. an interaction retired to a tombstone in its own slot — no shift at all;
//! 4. an interaction retired to a tombstone written out of its slot —
//!    `InteractionRemoved`, because the freed slot is what the survivors slide
//!    into;
//! 5. a tombstone dropped ahead of it — `InteractionRemoved`, a permanent wire
//!    reservation cannot be released;
//! 6. a tombstone moved — `InteractionReordered`;
//! 7. a tombstone minted ahead of it for a name the old snapshot never held —
//!    `InteractionInserted`.
//!
//! Cases 4 through 7 are why tombstones carry their ordinal through the
//! comparison rather than being compared as a bare set of names: a retirement
//! is compatible, so a tombstone edit that shifts a wire identity would
//! otherwise reach no `Change` at all and the classifier downstream would have
//! nothing left to judge.

use std::collections::{BTreeMap, BTreeSet};

use ridl_ir::v2;

use crate::classify::{struct_slots, union_slots};
use crate::{Category, Change, emit, frozen};

/// Walks two matched packages, appending every difference to `changes`.
pub(crate) fn walk_packages(old: &v2::Package, new: &v2::Package, changes: &mut Vec<Change>) {
    let pkg = new.name.as_str();
    diff_decls(pkg, &old.decls, &new.decls, changes);
    diff_interfaces(pkg, old, new, changes);
    diff_services(pkg, &old.services, &new.services, changes);
}

// ==========================================================================
// Package-level typl declarations.
// ==========================================================================

fn diff_decls(pkg: &str, old: &[v2::Decl], new: &[v2::Decl], changes: &mut Vec<Change>) {
    let old_by: BTreeMap<&str, &v2::Decl> = old.iter().map(|d| (d.name.as_str(), d)).collect();
    let new_by: BTreeMap<&str, &v2::Decl> = new.iter().map(|d| (d.name.as_str(), d)).collect();

    for (name, old_decl) in &old_by {
        match new_by.get(name) {
            Some(new_decl) => diff_decl(pkg, name, old_decl, new_decl, changes),
            None => emit(
                changes,
                format!("{pkg}/{name}"),
                Category::DeclRemoved,
                Some(decl_kind_name(old_decl).to_string()),
                None,
            ),
        }
    }
    for (name, new_decl) in &new_by {
        if !old_by.contains_key(name) {
            emit(
                changes,
                format!("{pkg}/{name}"),
                Category::DeclAdded,
                None,
                Some(decl_kind_name(new_decl).to_string()),
            );
        }
    }
}

fn diff_decl(pkg: &str, name: &str, old: &v2::Decl, new: &v2::Decl, changes: &mut Vec<Change>) {
    let path = format!("{pkg}/{name}");
    if envelope_differs(old, new) || member_docs_differ(&old.kind, &new.kind) {
        emit(changes, path.clone(), Category::DocOnly, None, None);
    }
    emit_visibility(changes, path.clone(), old.visibility, new.visibility);

    use v2::decl::Kind;
    match (
        &without_member_docs(&old.kind),
        &without_member_docs(&new.kind),
    ) {
        (Some(Kind::TypeDef(a)), Some(Kind::TypeDef(b))) => diff_type_def(&path, a, b, changes),
        (Some(Kind::ConstDef(a)), Some(Kind::ConstDef(b))) => {
            if a != b {
                emit(
                    changes,
                    path,
                    Category::InitChanged,
                    Some(const_str(a)),
                    Some(const_str(b)),
                );
            }
        }
        (Some(Kind::StructDef(a)), Some(Kind::StructDef(b))) => {
            diff_composite(
                &path,
                struct_slots(a),
                struct_slots(b),
                "ordinal",
                a == b,
                || struct_ignoring_order(a) == struct_ignoring_order(b),
                changes,
            );
        }
        (Some(Kind::EnumDef(a)), Some(Kind::EnumDef(b))) => {
            diff_composite(
                &path,
                positions(&a.values),
                positions(&b.values),
                "position",
                a == b,
                || enum_ignoring_order(a) == enum_ignoring_order(b),
                changes,
            );
        }
        (Some(Kind::EnumSetDef(a)), Some(Kind::EnumSetDef(b))) => {
            diff_composite(
                &path,
                positions(&a.bits),
                positions(&b.bits),
                "position",
                a == b,
                || enum_set_ignoring_order(a) == enum_set_ignoring_order(b),
                changes,
            );
        }
        (Some(Kind::UnionDef(a)), Some(Kind::UnionDef(b))) => {
            diff_composite(
                &path,
                union_slots(a),
                union_slots(b),
                "ordinal",
                a == b,
                || union_ignoring_order(a) == union_ignoring_order(b),
                changes,
            );
        }
        (old_kind, new_kind) => {
            if kind_discriminant(old_kind) != kind_discriminant(new_kind) {
                emit(
                    changes,
                    path,
                    Category::KindChanged,
                    Some(kind_name_opt(old_kind).to_string()),
                    Some(kind_name_opt(new_kind).to_string()),
                );
            }
        }
    }
}

fn diff_type_def(path: &str, a: &v2::TypeDef, b: &v2::TypeDef, changes: &mut Vec<Change>) {
    if a.backing != b.backing || a.width != b.width {
        emit(
            changes,
            path.to_string(),
            Category::WidthChanged,
            Some(type_repr_str(a)),
            Some(type_repr_str(b)),
        );
    }
    if a.constraint != b.constraint {
        emit(
            changes,
            path.to_string(),
            Category::ConstraintChanged,
            Some(constraint_str(a.constraint.as_ref())),
            Some(constraint_str(b.constraint.as_ref())),
        );
    }
    if a.declared_init != b.declared_init || a.init != b.init {
        emit(
            changes,
            path.to_string(),
            Category::InitChanged,
            Some(type_init_str(a)),
            Some(type_init_str(b)),
        );
    }
}

/// A coarse comparison of a composite type body (struct fields, enum values,
/// enum-set bits, union arms) by member name, each member paired with its
/// slot. A member present on one side is an addition or removal, and the
/// comparison stops there: a reorder in the same edit as an addition or a
/// removal reports no `MemberReordered`. The classifier reads the bodies
/// themselves to decide an addition's direction, so the append-only rule of
/// typl §7.4 is judged there.
///
/// With the same member names on both sides, a member whose slot changed is
/// one `MemberReordered` each, carrying the old and new slot — with the
/// container's `ConstraintChanged` as well when the body's content also
/// changed — and a body changed in place with every slot untouched is the
/// container's `ConstraintChanged` alone. The slot is the ordinal for a struct
/// field or union arm, which is the wire identity (typl §7.4), so a field a
/// moved tombstone shifted is reported even though the live names kept their
/// order. An enum value or enum-set bit carries an explicit number instead, and
/// its slot here is its 1-based position in the body: the comparison is over
/// positions, not those numbers, so a textual reorder is reported the same way
/// (typl §17.14). `slot` names the unit in the rendered detail.
///
/// **Known limitation (carried debt).** This comparison is keyed on member
/// names and never reads the body's `reserved` list, so it cannot tell a bare
/// deletion from typl §7.4's sanctioned "delete by tombstone" — both arrive at
/// the classifier as `DeclRemoved`, which classifies breaking. That errs in the
/// safe direction, but it makes a sanctioned retirement gate CI, so a team that
/// retires a struct field correctly still has to override the gate. Closing it
/// means matching removals against the container's `reserved` entries — the IR
/// carries everything needed (`Reserved.name` for struct and union bodies,
/// `Reserved.value` for enum bodies). Recorded for a later epic rather than
/// taken here, because the stability policy's normative table scopes its tombstone row to
/// interactions. Do not close this alone: driftsys/ridl#302 records a
/// FlatBuffers union-discriminant coupling that must move with it.
fn diff_composite(
    path: &str,
    old: Vec<(String, i64)>,
    new: Vec<(String, i64)>,
    slot: &str,
    equal: bool,
    equal_ignoring_order: impl FnOnce() -> bool,
    changes: &mut Vec<Change>,
) {
    if equal {
        return;
    }
    let old_set: BTreeSet<&String> = old.iter().map(|(name, _)| name).collect();
    let new_set: BTreeSet<&String> = new.iter().map(|(name, _)| name).collect();
    let mut structural = false;
    for (name, _) in &new {
        if !old_set.contains(name) {
            emit(
                changes,
                format!("{path}/{name}"),
                Category::DeclAdded,
                None,
                Some(name.clone()),
            );
            structural = true;
        }
    }
    for (name, _) in &old {
        if !new_set.contains(name) {
            emit(
                changes,
                format!("{path}/{name}"),
                Category::DeclRemoved,
                Some(name.clone()),
                None,
            );
            structural = true;
        }
    }
    if structural {
        return;
    }
    // The member names match on both sides, so the difference is a reorder of
    // the body, a member changed in place, or both. A reorder is its own
    // category: for struct fields and union arms the ordinal is wire identity,
    // and an enum or enumset body is reported the same way conservatively,
    // because this walk compares member positions rather than the explicit
    // values. Reporting a reorder as a constraint edit sends the reader looking
    // for a constraint that did not change (driftsys/ridl#314). None of this
    // changes removal matching, so the carried debt above — and
    // driftsys/ridl#302's coupling — stays exactly as it is.
    let mut moved = false;
    for (name, new_slot) in &new {
        let (_, old_slot) = old
            .iter()
            .find(|(old_name, _)| old_name == name)
            .expect("the name sets are equal, so every new name appears in the old body");
        if old_slot != new_slot {
            moved = true;
            emit(
                changes,
                format!("{path}/{name}"),
                Category::MemberReordered,
                Some(format!("{slot} {old_slot}")),
                Some(format!("{slot} {new_slot}")),
            );
        }
    }
    // With no slot moved, the bodies differ in content only: a member changed
    // in place, or a tombstone list changed without shifting a live member. A
    // reorder can also arrive in the same edit as a change to a member's
    // content or to the container itself. Comparing the bodies with member
    // order removed tells the two apart: when they still differ, the
    // container's `ConstraintChanged` is reported as well, after the
    // per-member lines, so the content change is not hidden behind the
    // reorder.
    if !moved || !equal_ignoring_order() {
        emit(
            changes,
            path.to_string(),
            Category::ConstraintChanged,
            None,
            None,
        );
    }
}

// ==========================================================================
// Interfaces and interactions.
// ==========================================================================

/// A shape's place in the walk's maps: its form — `false` for a declared
/// interface, `true` for a service's inline shape — then its identity name.
/// The form comes first so that a declared interface and an inline shape
/// spelled the same (`interface cabin` beside `service cabin`) are two keys,
/// and so that the declared interfaces sort before the inline shapes.
type ShapeKey<'a> = (bool, &'a str);

fn shapes_by_key(package: &v2::Package) -> BTreeMap<ShapeKey<'_>, v2::InterfaceShape<'_>> {
    package
        .shapes()
        .map(|shape| ((shape.is_inline(), shape.name), shape))
        .collect()
}

/// The interface walk, over every shape of the package — the declared
/// interfaces and the inline shapes of its services alike — matched by the
/// number each carries from its `interfaces.lock` (lock design §7; plan
/// decision PD-1), in three passes:
///
/// 1. an old shape with a frozen, non-zero number matches the new shape with
///    the same frozen number, whatever either is named;
/// 2. an old shape with no identity — `number` 0, from a snapshot published
///    before the lock existed, or a provisional number — matches by name and
///    form among the new shapes pass 1 left unmatched;
/// 3. an old shape still unmatched is `InterfaceRetired` when its frozen
///    number is in the new side's retired entries and `DeclRemoved`
///    otherwise; a new shape still unmatched is `DeclAdded`.
///
/// A frozen old number therefore never matches a new provisional shape: a
/// rename keeps its number, so a provisional shape is always a new interface.
/// Two new shapes cannot carry one frozen number — the checker refuses the
/// lock that would give them one (RIDL-410) — so pass 1 reads the first.
///
/// A matched pair whose names differ is `InterfaceRenamed`, compatible, and
/// its body is then diffed as any other pair's; every change path carries the
/// new side's name (plan decision PD-14), so the desk check's index finds a
/// span, and the classifier re-finds the old side by number. The envelope and
/// the visibility of a declared interface are compared here; an inline
/// shape's are its service's, which `diff_service` compares under the same
/// path, so an inline shape whose service is added or removed is reported at
/// both levels: once as the service, once as the interface whose number went
/// with it.
///
/// Changes come out in the old side's key order — the declared interfaces by
/// name, then the inline shapes by service name — and the additions in the new
/// side's key order.
fn diff_interfaces(pkg: &str, old: &v2::Package, new: &v2::Package, changes: &mut Vec<Change>) {
    let old_shapes = shapes_by_key(old);
    let new_shapes = shapes_by_key(new);

    let new_by_number: BTreeMap<u32, ShapeKey<'_>> = new_shapes
        .iter()
        .rev()
        .filter(|(_, shape)| frozen(shape.interface))
        .map(|(key, shape)| (shape.interface.number, *key))
        .collect();

    // Old key to new key, and the new keys taken so far.
    let mut pairs: BTreeMap<ShapeKey<'_>, ShapeKey<'_>> = BTreeMap::new();
    let mut taken: BTreeSet<ShapeKey<'_>> = BTreeSet::new();
    // Pass 1: by frozen number.
    for (old_key, old_shape) in &old_shapes {
        if !frozen(old_shape.interface) {
            continue;
        }
        if let Some(new_key) = new_by_number.get(&old_shape.interface.number)
            && taken.insert(*new_key)
        {
            pairs.insert(*old_key, *new_key);
        }
    }
    // Pass 2: by name and form, for an old shape with no identity.
    for (old_key, old_shape) in &old_shapes {
        if frozen(old_shape.interface) {
            continue;
        }
        if new_shapes.contains_key(old_key) && taken.insert(*old_key) {
            pairs.insert(*old_key, *old_key);
        }
    }

    for (old_key, old_shape) in &old_shapes {
        let Some(new_key) = pairs.get(old_key) else {
            let number = old_shape.interface.number;
            let sanctioned = frozen(old_shape.interface)
                && new.retired.iter().any(|entry| entry.number == number);
            if sanctioned {
                emit(
                    changes,
                    format!("{pkg}/{}", old_shape.name),
                    Category::InterfaceRetired,
                    Some("interface".to_string()),
                    Some("retired".to_string()),
                );
            } else {
                emit(
                    changes,
                    format!("{pkg}/{}", old_shape.name),
                    Category::DeclRemoved,
                    Some("interface".to_string()),
                    None,
                );
            }
            continue;
        };
        let new_shape = &new_shapes[new_key];
        let name = new_shape.name;
        if old_shape.name != name {
            emit(
                changes,
                format!("{pkg}/{name}"),
                Category::InterfaceRenamed,
                Some(old_shape.name.to_string()),
                Some(name.to_string()),
            );
        }
        if !new_shape.is_inline() {
            if interface_envelope_differs(old_shape.interface, new_shape.interface) {
                emit(
                    changes,
                    format!("{pkg}/{name}"),
                    Category::DocOnly,
                    None,
                    None,
                );
            }
            emit_visibility(
                changes,
                format!("{pkg}/{name}"),
                old_shape.visibility(),
                new_shape.visibility(),
            );
        }
        diff_interface(pkg, name, old_shape.interface, new_shape.interface, changes);
    }
    for (new_key, new_shape) in &new_shapes {
        if !taken.contains(new_key) {
            emit(
                changes,
                format!("{pkg}/{}", new_shape.name),
                Category::DeclAdded,
                None,
                Some("interface".to_string()),
            );
        }
    }
}

/// The core interaction walk for one matched interface (used for both a
/// top-level interface and a service's inline shape).
fn diff_interface(
    pkg: &str,
    iface: &str,
    old: &v2::Interface,
    new: &v2::Interface,
    changes: &mut Vec<Change>,
) {
    let old_live = live_interactions(old);
    let new_live = live_interactions(new);
    let old_reserved = reserved_names(old);
    let new_reserved = reserved_names(new);

    let old_live_names: BTreeSet<&str> = old_live.iter().map(|(name, ..)| *name).collect();
    let new_live_map: BTreeMap<&str, (u32, &v2::Decl)> = new_live
        .iter()
        .map(|(name, ord, decl)| (*name, (*ord, *decl)))
        .collect();

    // (name, old ordinal, new ordinal) for interactions present on both sides.
    let mut matched: Vec<(&str, u32, u32)> = Vec::new();

    for (name, old_ord, old_decl) in &old_live {
        let member_path = format!("{pkg}/{iface}/{name}");
        if let Some((new_ord, new_decl)) = new_live_map.get(name) {
            matched.push((name, *old_ord, *new_ord));
            diff_interaction(iface, &member_path, old_decl, new_decl, changes);
        } else if let Some(reserved_ord) = new_reserved.get(name) {
            // A tombstone must hold the retired interaction's own ordinal
            // (ridl §11). A tombstone placed elsewhere lets the surviving
            // interactions slide into the freed slot — a wire break that the
            // relative-order check below cannot see.
            if *reserved_ord == *old_ord {
                emit(
                    changes,
                    member_path,
                    Category::InteractionRetired,
                    Some(interaction_desc(old_decl)),
                    Some("reserved".to_string()),
                );
            } else {
                emit(
                    changes,
                    member_path,
                    Category::InteractionRemoved,
                    Some(format!(
                        "{} at ordinal {old_ord}",
                        interaction_desc(old_decl)
                    )),
                    Some(format!("reserved at ordinal {reserved_ord}")),
                );
            }
        } else {
            emit(
                changes,
                member_path,
                Category::InteractionRemoved,
                Some(interaction_desc(old_decl)),
                None,
            );
        }
    }

    // A tombstone is a permanent wire reservation (ridl §11). Dropping one, or
    // moving it, lets every later interaction slide down into the freed slot —
    // a wire break invisible to the relative-order check below.
    for (name, old_ord) in &old_reserved {
        if new_live_map.contains_key(name) {
            continue; // handled as ReservedNameRedeclared below.
        }
        match new_reserved.get(name) {
            Some(new_ord) if new_ord == old_ord => {}
            Some(new_ord) => emit(
                changes,
                format!("{pkg}/{iface}/{name}"),
                Category::InteractionReordered,
                Some(format!("reserved at ordinal {old_ord}")),
                Some(format!("reserved at ordinal {new_ord}")),
            ),
            None => emit(
                changes,
                format!("{pkg}/{iface}/{name}"),
                Category::InteractionRemoved,
                Some(format!("reserved at ordinal {old_ord}")),
                None,
            ),
        }
    }

    let anchor_ordinals = anchor_ordinals(&matched, new, &old_live_names, &old_reserved);

    // A tombstone minted for a name the old snapshot never held reserves a
    // fresh slot. At the end of the body that is harmless; written earlier it
    // pushes every later interaction down one slot — the same wire break as an
    // inserted interaction, and the last shift cause that would otherwise reach
    // no `Change` at all.
    for (name, new_ord) in &new_reserved {
        if old_live_names.contains(name) || old_reserved.contains_key(name) {
            continue;
        }
        let category = if anchor_ordinals.iter().any(|&anchor| anchor > *new_ord) {
            Category::InteractionInserted
        } else {
            Category::InteractionAppended
        };
        emit(
            changes,
            format!("{pkg}/{iface}/{name}"),
            category,
            None,
            Some(format!("reserved at ordinal {new_ord}")),
        );
    }

    for (name, new_ord, new_decl) in &new_live {
        if old_live_names.contains(name) {
            continue;
        }
        let member_path = format!("{pkg}/{iface}/{name}");
        if old_reserved.contains_key(name) {
            emit(
                changes,
                member_path,
                Category::ReservedNameRedeclared,
                Some("reserved".to_string()),
                Some(interaction_desc(new_decl)),
            );
        } else {
            let category = if anchor_ordinals.iter().any(|&anchor| anchor > *new_ord) {
                Category::InteractionInserted
            } else {
                Category::InteractionAppended
            };
            emit(
                changes,
                member_path,
                category,
                None,
                Some(interaction_desc(new_decl)),
            );
        }
    }

    detect_reorders(pkg, iface, &matched, changes);
}

/// Flags surviving interactions whose relative order within the interface
/// changed. An absolute-ordinal change that preserves relative order is a
/// consequence of a slot added or released elsewhere and is not reported here;
/// see the module documentation for why every such cause is independently
/// reported as breaking.
fn detect_reorders(
    pkg: &str,
    iface: &str,
    matched: &[(&str, u32, u32)],
    changes: &mut Vec<Change>,
) {
    let old_rank = rank_by(matched, |(_, old_ord, _)| *old_ord);
    let new_rank = rank_by(matched, |(_, _, new_ord)| *new_ord);
    for (name, old_ord, new_ord) in matched {
        if old_rank[name] != new_rank[name] {
            emit(
                changes,
                format!("{pkg}/{iface}/{name}"),
                Category::InteractionReordered,
                Some(old_ord.to_string()),
                Some(new_ord.to_string()),
            );
        }
    }
}

/// Ranks matched interaction names by a chosen ordinal, returning name → rank.
fn rank_by<'a>(
    matched: &[(&'a str, u32, u32)],
    key: impl Fn(&(&'a str, u32, u32)) -> u32,
) -> BTreeMap<&'a str, usize> {
    let mut order: Vec<&(&'a str, u32, u32)> = matched.iter().collect();
    order.sort_by_key(|entry| key(entry));
    order
        .iter()
        .enumerate()
        .map(|(rank, (name, _, _))| (*name, rank))
        .collect()
}

/// The new-side ordinals of the slots that existed before the change —
/// surviving interactions and the tombstones of names the old snapshot already
/// held. A new slot sitting before any of these was inserted, not appended. A
/// tombstone minted in this change is new content, so it is not itself an
/// anchor.
fn anchor_ordinals(
    matched: &[(&str, u32, u32)],
    new: &v2::Interface,
    old_live_names: &BTreeSet<&str>,
    old_reserved: &BTreeMap<&str, u32>,
) -> Vec<u32> {
    let mut ordinals: Vec<u32> = matched.iter().map(|(_, _, new_ord)| *new_ord).collect();
    for decl in &new.interactions {
        if let Some(v2::decl::Kind::ReservedSlot(reserved)) = &decl.kind
            && let Some(name) = reserved.name.as_deref()
            && (old_live_names.contains(name) || old_reserved.contains_key(name))
        {
            ordinals.push(decl.ordinal);
        }
    }
    ordinals
}

/// Compares two matched interactions of the same name: kind, then the
/// kind-specific contract-carrying fields, then the doc envelope. `iface` is the
/// enclosing interface name, needed to derive an inline `T | E` transport
/// identity (ADR-0008 decision 4).
fn diff_interaction(
    iface: &str,
    path: &str,
    old: &v2::Decl,
    new: &v2::Decl,
    changes: &mut Vec<Change>,
) {
    if envelope_differs(old, new) || member_docs_differ(&old.kind, &new.kind) {
        emit(changes, path.to_string(), Category::DocOnly, None, None);
    }
    emit_visibility(changes, path.to_string(), old.visibility, new.visibility);

    use v2::decl::Kind;
    // A parameter's doc fields are compared above, so `params` below is
    // compared without them: a parameter doc edit is not `ParamsChanged`.
    match (
        &without_member_docs(&old.kind),
        &without_member_docs(&new.kind),
    ) {
        (Some(Kind::SignalDef(a)), Some(Kind::SignalDef(b))) => {
            if a.payload != b.payload {
                emit(
                    changes,
                    path.to_string(),
                    Category::PayloadChanged,
                    Some(a.payload.clone()),
                    Some(b.payload.clone()),
                );
            }
            if a.declared_init != b.declared_init || a.init != b.init {
                emit(
                    changes,
                    path.to_string(),
                    Category::InitChanged,
                    Some(signal_init_str(a)),
                    Some(signal_init_str(b)),
                );
            }
            if a.timing != b.timing {
                emit(
                    changes,
                    path.to_string(),
                    Category::TimingChanged,
                    Some(timing_str(a.timing.as_ref())),
                    Some(timing_str(b.timing.as_ref())),
                );
            }
        }
        (Some(Kind::EventDef(a)), Some(Kind::EventDef(b))) => {
            if a.payload != b.payload {
                emit(
                    changes,
                    path.to_string(),
                    Category::PayloadChanged,
                    Some(a.payload.clone()),
                    Some(b.payload.clone()),
                );
            }
            if a.timing != b.timing {
                emit(
                    changes,
                    path.to_string(),
                    Category::TimingChanged,
                    Some(timing_str(a.timing.as_ref())),
                    Some(timing_str(b.timing.as_ref())),
                );
            }
        }
        (Some(Kind::CommandDef(a)), Some(Kind::CommandDef(b))) => {
            if a.params != b.params {
                emit(
                    changes,
                    path.to_string(),
                    Category::ParamsChanged,
                    Some(params_str(&a.params)),
                    Some(params_str(&b.params)),
                );
            }
            if a.contracts != b.contracts {
                emit(
                    changes,
                    path.to_string(),
                    Category::ContractChanged,
                    Some(contracts_str(&a.contracts)),
                    Some(contracts_str(&b.contracts)),
                );
            }
            // The declared RPC bounds travel as their own category, not as
            // `TimingChanged`: the `min` direction inverts on an RPC
            // (ADR-0015 decision 8).
            if a.timing != b.timing {
                emit(
                    changes,
                    path.to_string(),
                    Category::RpcBoundChanged,
                    Some(timing_str(a.timing.as_ref())),
                    Some(timing_str(b.timing.as_ref())),
                );
            }
        }
        (Some(Kind::QueryDef(a)), Some(Kind::QueryDef(b))) => {
            if a.params != b.params {
                emit(
                    changes,
                    path.to_string(),
                    Category::ParamsChanged,
                    Some(params_str(&a.params)),
                    Some(params_str(&b.params)),
                );
            }
            if a.return_type != b.return_type {
                emit(
                    changes,
                    path.to_string(),
                    Category::ReturnChanged,
                    Some(return_str(iface, old.ordinal, a.return_type.as_ref())),
                    Some(return_str(iface, new.ordinal, b.return_type.as_ref())),
                );
            }
            if a.contracts != b.contracts {
                emit(
                    changes,
                    path.to_string(),
                    Category::ContractChanged,
                    Some(contracts_str(&a.contracts)),
                    Some(contracts_str(&b.contracts)),
                );
            }
            // As on a command: the declared RPC bounds are their own category
            // (ADR-0015 decision 8).
            if a.timing != b.timing {
                emit(
                    changes,
                    path.to_string(),
                    Category::RpcBoundChanged,
                    Some(timing_str(a.timing.as_ref())),
                    Some(timing_str(b.timing.as_ref())),
                );
            }
        }
        (Some(Kind::FixedDef(a)), Some(Kind::FixedDef(b))) => {
            if a.payload != b.payload {
                emit(
                    changes,
                    path.to_string(),
                    Category::PayloadChanged,
                    Some(field_type_opt_str(a.payload.as_ref())),
                    Some(field_type_opt_str(b.payload.as_ref())),
                );
            }
        }
        (old_kind, new_kind) => {
            emit(
                changes,
                path.to_string(),
                Category::KindChanged,
                Some(kind_name_opt(old_kind).to_string()),
                Some(kind_name_opt(new_kind).to_string()),
            );
        }
    }
}

// ==========================================================================
// Services.
// ==========================================================================

fn diff_services(pkg: &str, old: &[v2::Service], new: &[v2::Service], changes: &mut Vec<Change>) {
    let old_by: BTreeMap<&str, &v2::Service> = old.iter().map(|s| (s.name.as_str(), s)).collect();
    let new_by: BTreeMap<&str, &v2::Service> = new.iter().map(|s| (s.name.as_str(), s)).collect();

    for (name, old_svc) in &old_by {
        match new_by.get(name) {
            Some(new_svc) => diff_service(pkg, name, old_svc, new_svc, changes),
            None => emit(
                changes,
                format!("{pkg}/{name}"),
                Category::DeclRemoved,
                Some("service".to_string()),
                None,
            ),
        }
    }
    for name in new_by.keys() {
        if !old_by.contains_key(name) {
            emit(
                changes,
                format!("{pkg}/{name}"),
                Category::DeclAdded,
                None,
                Some("service".to_string()),
            );
        }
    }
}

fn diff_service(
    pkg: &str,
    name: &str,
    old: &v2::Service,
    new: &v2::Service,
    changes: &mut Vec<Change>,
) {
    let path = format!("{pkg}/{name}");
    if service_envelope_differs(old, new) {
        emit(changes, path.clone(), Category::DocOnly, None, None);
    }
    emit_visibility(changes, path.clone(), old.visibility, new.visibility);

    // The `INLINE` slot marks the inline form (ADR-0015 decision 14: one
    // inline shape, never mixed with named shapes). A switch between the two
    // forms stays `ServiceChanged` — extraction rewrites the transport
    // identity of every fallible query in the shape (ADR-0015 decision 15) —
    // while a changed list is read as a set by `diff_service_set` (decision
    // 19 as amended on 2026-09-15, which narrows `ServiceChanged` to the form
    // switch). Two inline shapes are not diffed here: an inline shape is an
    // interface with its own lock number, and `diff_interfaces` matched it by
    // that number, so its body was compared there — under this service's
    // name when the number was found under it, or under the name of whichever
    // service holds the number now.
    match (inline_shape(old), inline_shape(new)) {
        (Some(_), Some(_)) => {}
        (None, None) => diff_service_set(pkg, name, old, new, changes),
        (old_inline, new_inline) => {
            emit(
                changes,
                path,
                Category::ServiceChanged,
                Some(form_desc(old_inline.is_some()).to_string()),
                Some(form_desc(new_inline.is_some()).to_string()),
            );
        }
    }
}

/// The set walk of one matched named-form service (ADR-0015 decision 19 as
/// amended on 2026-09-15): a service's list is a set of interface references,
/// keyed on the canonical reference the checker lowered. An interface in one
/// set and not the other is `ServiceInterfaceRemoved` or
/// `ServiceInterfaceAdded`; the list's order carries nothing, so a reorder is
/// no change. A `reserved` slot the IR may still carry is ignored: a set holds
/// no tombstone. The change path is `<package>/<service>/<reference>`, the
/// reference whole because two references may share a final segment.
fn diff_service_set(
    pkg: &str,
    svc: &str,
    old: &v2::Service,
    new: &v2::Service,
    changes: &mut Vec<Change>,
) {
    let old_refs = interface_refs(old);
    let new_refs = interface_refs(new);
    for reference in old_refs.difference(&new_refs) {
        emit(
            changes,
            format!("{pkg}/{svc}/{reference}"),
            Category::ServiceInterfaceRemoved,
            Some((*reference).to_string()),
            None,
        );
    }
    for reference in new_refs.difference(&old_refs) {
        emit(
            changes,
            format!("{pkg}/{svc}/{reference}"),
            Category::ServiceInterfaceAdded,
            None,
            Some((*reference).to_string()),
        );
    }
}

// ==========================================================================
// Collectors.
// ==========================================================================

/// The live interactions of an interface — every member that is not a reserved
/// tombstone — as (name, ordinal, decl).
fn live_interactions(iface: &v2::Interface) -> Vec<(&str, u32, &v2::Decl)> {
    iface
        .interactions
        .iter()
        .filter_map(|decl| match &decl.kind {
            Some(v2::decl::Kind::ReservedSlot(_)) | None => None,
            Some(_) => Some((decl.name.as_str(), decl.ordinal, decl)),
        })
        .collect()
}

/// The names retired by `reserved` tombstones in an interface body, each with
/// the ordinal its tombstone holds.
fn reserved_names(iface: &v2::Interface) -> BTreeMap<&str, u32> {
    iface
        .interactions
        .iter()
        .filter_map(|decl| match &decl.kind {
            Some(v2::decl::Kind::ReservedSlot(reserved)) => {
                reserved.name.as_deref().map(|name| (name, decl.ordinal))
            }
            _ => None,
        })
        .collect()
}

/// The inline shape of a service, when it carries one — the `INLINE` slot
/// that marks the inline form (ADR-0015 decision 14).
fn inline_shape(service: &v2::Service) -> Option<&v2::Interface> {
    service.shapes.iter().find_map(|slot| match &slot.kind {
        Some(v2::service_shape::Kind::Inline(interface)) => Some(interface),
        _ => None,
    })
}

/// The interface references of a service's set — every `InterfaceRef` slot,
/// by its canonical reference. An inline or `reserved` slot is not a member.
fn interface_refs(service: &v2::Service) -> BTreeSet<&str> {
    service
        .shapes
        .iter()
        .filter_map(|slot| match &slot.kind {
            Some(v2::service_shape::Kind::InterfaceRef(reference)) => Some(reference.as_str()),
            _ => None,
        })
        .collect()
}

/// Enum values or enum-set bits, each with its 1-based position in the body.
/// The explicit number is not read here: the reorder comparison is over
/// positions, conservatively (typl §17.14).
fn positions(values: &[v2::EnumValue]) -> Vec<(String, i64)> {
    values
        .iter()
        .zip(1..)
        .map(|(value, position)| (value.name.clone(), position))
        .collect()
}

// The four `*_ignoring_order` helpers return a body with its member order
// removed, so that `==` over two of them asks whether the bodies are equal
// once order is ignored — the question `diff_composite` needs to tell a pure
// reorder from a reorder combined with a content change. Each removes exactly
// two things from what `a == b` compares: the order of the members, and every
// field whose value is derived from position (the 1-based `ordinal` of a
// struct field, a union arm, and a struct or union tombstone — typl §7.4).
// Everything else stays in the comparison: member names, types, inits, the
// explicit value of an enum value or enum-set bit, the retired identity of a
// tombstone, and the container's own fields. The members' doc fields are not
// there to compare: `diff_decl` removes them first ([`without_member_docs`]).

/// A struct body with its member order removed (see above). Fields and
/// tombstones share the `members` list and one ordinal counter, so both have
/// the ordinal cleared and both are sorted, fields before tombstones.
fn struct_ignoring_order(def: &v2::StructDef) -> v2::StructDef {
    use v2::struct_member::Member;
    let mut def = def.clone();
    for member in &mut def.members {
        match &mut member.member {
            Some(Member::Field(field)) => field.ordinal = 0,
            Some(Member::Reserved(reserved)) => reserved.ordinal = 0,
            None => {}
        }
    }
    def.members.sort_by_key(|member| match &member.member {
        Some(Member::Field(field)) => (0, Some(field.name.clone()), None),
        Some(Member::Reserved(reserved)) => (1, reserved.name.clone(), reserved.value),
        None => (2, None, None),
    });
    def
}

/// An enum body with its member order removed (see above). An enum value
/// carries no ordinal — its number is explicit content and stays compared —
/// and an enum tombstone's ordinal is always 0, so only the two lists are
/// sorted.
fn enum_ignoring_order(def: &v2::EnumDef) -> v2::EnumDef {
    let mut def = def.clone();
    def.values.sort_by_key(|value| value.name.clone());
    def.reserved.sort_by_key(tombstone_key);
    def
}

/// An enum-set body with its member order removed (see above). A bit carries
/// no ordinal — its position number is explicit content and stays compared —
/// so only the list is sorted.
fn enum_set_ignoring_order(def: &v2::EnumSetDef) -> v2::EnumSetDef {
    let mut def = def.clone();
    def.bits.sort_by_key(|bit| bit.name.clone());
    def
}

/// A union body with its member order removed (see above). Arms and
/// tombstones are two lists over one ordinal counter, so both have the
/// ordinal cleared and both are sorted.
fn union_ignoring_order(def: &v2::UnionDef) -> v2::UnionDef {
    let mut def = def.clone();
    for arm in &mut def.arms {
        arm.ordinal = 0;
    }
    def.arms.sort_by_key(|arm| arm.name.clone());
    for reserved in &mut def.reserved {
        reserved.ordinal = 0;
    }
    def.reserved.sort_by_key(tombstone_key);
    def
}

/// The retired identity of a tombstone — its name in a struct or union body,
/// its value in an enum body — as a sort key.
fn tombstone_key(reserved: &v2::Reserved) -> (Option<String>, Option<i64>) {
    (reserved.name.clone(), reserved.value)
}

// ==========================================================================
// Envelope comparison.
// ==========================================================================

/// Whether anything in the doc envelope changed.
///
/// Visibility is deliberately **not** part of this comparison. It is metadata
/// in the surface grammar, but it is not metadata to a consumer: `internal`
/// maps to a target's package-private mechanism — Rust `pub(crate)`, a
/// non-exported TypeScript member (ADR-0002 §8) — so narrowing it deletes the
/// declaration from every out-of-package consumer. It travels as its own
/// category so it can be classified by direction.
fn envelope_differs(old: &v2::Decl, new: &v2::Decl) -> bool {
    old.doc != new.doc
        || old.labels != new.labels
        || old.deprecated != new.deprecated
        || old.links != new.links
        || old.see != new.see
        || old.since != new.since
}

/// The same comparison as [`envelope_differs`], over an interface. The body is
/// identical but the parameter type is not, and `Decl`, `Interface`, and
/// `Service` are three unrelated generated structs with no shared trait, so none
/// can call another without a trait written only to join them. The third copy is
/// [`service_envelope_differs`].
fn interface_envelope_differs(old: &v2::Interface, new: &v2::Interface) -> bool {
    old.doc != new.doc
        || old.labels != new.labels
        || old.deprecated != new.deprecated
        || old.links != new.links
        || old.see != new.see
        || old.since != new.since
}

/// The third copy, over a service — named rather than inlined so all three are
/// greppable together.
fn service_envelope_differs(old: &v2::Service, new: &v2::Service) -> bool {
    old.doc != new.doc
        || old.labels != new.labels
        || old.deprecated != new.deprecated
        || old.links != new.links
        || old.see != new.see
        || old.since != new.since
}

/// The doc fields of one member of a declaration body — a struct field, an
/// enum value, an enum-set bit, a union arm or a parameter. `labels` and
/// `deprecated` are empty on the members that do not carry them.
#[derive(PartialEq)]
struct MemberDocs<'a> {
    doc: &'a str,
    labels: &'a [String],
    deprecated: Option<&'a str>,
    links: &'a [v2::DocLink],
    see: &'a [v2::DocLink],
    since: &'a [String],
}

/// The doc fields of every member of a declaration body, by member name.
fn member_docs(kind: &Option<v2::decl::Kind>) -> BTreeMap<&str, MemberDocs<'_>> {
    use v2::decl::Kind;
    let mut docs = BTreeMap::new();
    match kind {
        Some(Kind::StructDef(def)) => {
            for member in &def.members {
                if let Some(v2::struct_member::Member::Field(field)) = &member.member {
                    docs.insert(
                        field.name.as_str(),
                        MemberDocs {
                            doc: &field.doc,
                            labels: &field.labels,
                            deprecated: field.deprecated.as_deref(),
                            links: &field.links,
                            see: &field.see,
                            since: &field.since,
                        },
                    );
                }
            }
        }
        Some(Kind::EnumDef(v2::EnumDef { values, .. }))
        | Some(Kind::EnumSetDef(v2::EnumSetDef { bits: values, .. })) => {
            for value in values {
                docs.insert(
                    value.name.as_str(),
                    MemberDocs {
                        doc: &value.doc,
                        labels: &[],
                        deprecated: None,
                        links: &value.links,
                        see: &value.see,
                        since: &value.since,
                    },
                );
            }
        }
        Some(Kind::UnionDef(def)) => {
            for arm in &def.arms {
                docs.insert(
                    arm.name.as_str(),
                    MemberDocs {
                        doc: &arm.doc,
                        labels: &[],
                        deprecated: None,
                        links: &arm.links,
                        see: &arm.see,
                        since: &arm.since,
                    },
                );
            }
        }
        Some(Kind::CommandDef(v2::CommandDef { params, .. }))
        | Some(Kind::QueryDef(v2::QueryDef { params, .. })) => {
            for param in params {
                docs.insert(
                    param.name.as_str(),
                    MemberDocs {
                        doc: &param.doc,
                        labels: &[],
                        deprecated: None,
                        links: &param.links,
                        see: &param.see,
                        since: &param.since,
                    },
                );
            }
        }
        Some(Kind::TypeDef(_))
        | Some(Kind::ConstDef(_))
        | Some(Kind::SignalDef(_))
        | Some(Kind::EventDef(_))
        | Some(Kind::FixedDef(_))
        | Some(Kind::ReservedSlot(_))
        | None => {}
    }
    docs
}

/// Whether a member present on both sides changed a doc field. A member on
/// one side only is an addition or a removal, reported by the body walk.
fn member_docs_differ(old: &Option<v2::decl::Kind>, new: &Option<v2::decl::Kind>) -> bool {
    let new_docs = member_docs(new);
    member_docs(old).iter().any(|(name, old_docs)| {
        new_docs
            .get(name)
            .is_some_and(|new_docs| new_docs != old_docs)
    })
}

/// A declaration body with every member's doc fields cleared, so that the
/// body comparisons see only what carries contract identity.
fn without_member_docs(kind: &Option<v2::decl::Kind>) -> Option<v2::decl::Kind> {
    use v2::decl::Kind;
    let mut kind = kind.clone();
    match &mut kind {
        Some(Kind::StructDef(def)) => {
            for member in &mut def.members {
                if let Some(v2::struct_member::Member::Field(field)) = &mut member.member {
                    field.doc.clear();
                    field.labels.clear();
                    field.deprecated = None;
                    field.links.clear();
                    field.see.clear();
                    field.since.clear();
                }
            }
        }
        Some(Kind::EnumDef(v2::EnumDef { values, .. }))
        | Some(Kind::EnumSetDef(v2::EnumSetDef { bits: values, .. })) => {
            for value in values {
                value.doc.clear();
                value.links.clear();
                value.see.clear();
                value.since.clear();
            }
        }
        Some(Kind::UnionDef(def)) => {
            for arm in &mut def.arms {
                arm.doc.clear();
                arm.links.clear();
                arm.see.clear();
                arm.since.clear();
            }
        }
        Some(Kind::CommandDef(v2::CommandDef { params, .. }))
        | Some(Kind::QueryDef(v2::QueryDef { params, .. })) => {
            for param in params {
                param.doc.clear();
                param.links.clear();
                param.see.clear();
                param.since.clear();
            }
        }
        Some(Kind::TypeDef(_))
        | Some(Kind::ConstDef(_))
        | Some(Kind::SignalDef(_))
        | Some(Kind::EventDef(_))
        | Some(Kind::FixedDef(_))
        | Some(Kind::ReservedSlot(_))
        | None => {}
    }
    kind
}

/// Emits a [`Category::VisibilityChanged`] when the two sides publish a
/// declaration at different visibilities. The classifier reads the direction.
fn emit_visibility(changes: &mut Vec<Change>, path: String, old: i32, new: i32) {
    if old == new {
        return;
    }
    emit(
        changes,
        path,
        Category::VisibilityChanged,
        Some(visibility_name(old).to_string()),
        Some(visibility_name(new).to_string()),
    );
}

fn visibility_name(visibility: i32) -> &'static str {
    match v2::Visibility::try_from(visibility) {
        Ok(v2::Visibility::Public) => "public",
        Ok(v2::Visibility::Internal) => "internal",
        _ => "unspecified",
    }
}

// ==========================================================================
// Renderers — honest, compact before/after strings.
// ==========================================================================

fn decl_kind_name(decl: &v2::Decl) -> &'static str {
    kind_name_opt(&decl.kind)
}

fn kind_name_opt(kind: &Option<v2::decl::Kind>) -> &'static str {
    use v2::decl::Kind;
    match kind {
        Some(Kind::TypeDef(_)) => "type",
        Some(Kind::ConstDef(_)) => "const",
        Some(Kind::StructDef(_)) => "struct",
        Some(Kind::EnumDef(_)) => "enum",
        Some(Kind::EnumSetDef(_)) => "enum set",
        Some(Kind::UnionDef(_)) => "union",
        Some(Kind::SignalDef(_)) => "signal",
        Some(Kind::EventDef(_)) => "event",
        Some(Kind::CommandDef(_)) => "command",
        Some(Kind::QueryDef(_)) => "query",
        Some(Kind::FixedDef(_)) => "fixed",
        Some(Kind::ReservedSlot(_)) => "reserved",
        None => "declaration",
    }
}

/// A stable discriminant for a decl kind, so a variant switch is a
/// `KindChanged` while a same-variant edit is not.
fn kind_discriminant(kind: &Option<v2::decl::Kind>) -> u8 {
    use v2::decl::Kind;
    match kind {
        None => 0,
        Some(Kind::TypeDef(_)) => 1,
        Some(Kind::ConstDef(_)) => 2,
        Some(Kind::StructDef(_)) => 3,
        Some(Kind::EnumDef(_)) => 4,
        Some(Kind::EnumSetDef(_)) => 5,
        Some(Kind::UnionDef(_)) => 6,
        Some(Kind::SignalDef(_)) => 7,
        Some(Kind::EventDef(_)) => 8,
        Some(Kind::CommandDef(_)) => 9,
        Some(Kind::QueryDef(_)) => 10,
        Some(Kind::FixedDef(_)) => 11,
        Some(Kind::ReservedSlot(_)) => 12,
    }
}

fn interaction_desc(decl: &v2::Decl) -> String {
    format!("{} {}", kind_name_opt(&decl.kind), decl.name)
}

/// The form a service publishes in, for the `ServiceChanged` report: the
/// inline shape, or the named shape list.
fn form_desc(inline: bool) -> &'static str {
    if inline {
        "inline shape"
    } else {
        "interface list"
    }
}

fn timing_str(timing: Option<&v2::Timing>) -> String {
    let Some(timing) = timing else {
        return "(none)".to_string();
    };
    let mode = match v2::TimingMode::try_from(timing.mode) {
        Ok(v2::TimingMode::StrictPeriodic) => "strict",
        Ok(v2::TimingMode::Range) => "range",
        _ => "unspecified",
    };
    let min = timing.min_us.as_deref().unwrap_or("_");
    let max = timing.max_us.as_deref().unwrap_or("_");
    let default = if timing.default_applied {
        " (default)"
    } else {
        ""
    };
    format!("{mode} [{min}us..{max}us]{default}")
}

fn params_str(params: &[v2::Param]) -> String {
    let rendered: Vec<String> = params
        .iter()
        .map(|param| {
            format!(
                "{}: {}",
                param.name,
                field_type_opt_str(param.r#type.as_ref())
            )
        })
        .collect();
    format!("({})", rendered.join(", "))
}

fn contracts_str(contracts: &[v2::Contract]) -> String {
    let rendered: Vec<String> = contracts
        .iter()
        .map(|contract| {
            let kind = match v2::ContractKind::try_from(contract.kind) {
                Ok(v2::ContractKind::Require) => "require",
                Ok(v2::ContractKind::Ensure) => "ensure",
                _ => "clause",
            };
            format!("{kind} {}", contract.source)
        })
        .collect();
    format!("[{}]", rendered.join("; "))
}

/// Renders a query return shape.
///
/// An inline `T | E` renders with its synthesized transport identity alongside
/// the arms (ADR-0008 decision 4: interface + interaction ordinal + ordered arm
/// types). The identity is what a backend keys on, so a report that only showed
/// the arm spelling would hide which of the two changed things actually moved —
/// the same arms at a different ordinal are a different identity.
fn return_str(iface: &str, ordinal: u32, return_type: Option<&v2::ReturnType>) -> String {
    let Some(return_type) = return_type else {
        return "()".to_string();
    };
    match &return_type.kind {
        Some(v2::return_type::Kind::Value(value)) => field_type_str(value),
        Some(v2::return_type::Kind::Fallible(fallible)) => format!(
            "{} | {} (transport identity {})",
            fallible.ok,
            fallible.err,
            v2::fallible_transport_identity(iface, ordinal, fallible)
        ),
        None => "()".to_string(),
    }
}

fn field_type_opt_str(field_type: Option<&v2::FieldType>) -> String {
    field_type
        .map(field_type_str)
        .unwrap_or_else(|| "()".to_string())
}

fn field_type_str(field_type: &v2::FieldType) -> String {
    use v2::field_type::Kind;
    let mut rendered = match &field_type.kind {
        Some(Kind::Named(name)) => name.clone(),
        Some(Kind::Primitive(primitive)) => primitive_name(*primitive).to_string(),
        Some(Kind::InlineScalar(_)) => "<inline scalar>".to_string(),
        Some(Kind::Tuple(tuple)) => {
            let fields: Vec<String> = tuple
                .fields
                .iter()
                .map(|field| {
                    format!(
                        "{}: {}",
                        field.name,
                        field_type_opt_str(field.r#type.as_ref())
                    )
                })
                .collect();
            format!("({})", fields.join(", "))
        }
        Some(Kind::Array(array)) => format!(
            "[{}; {}..{}]",
            field_type_opt_str(array.element.as_deref()),
            array.min,
            array.max
        ),
        Some(Kind::Map(map)) => format!(
            "{{{}: {}}}",
            field_type_opt_str(map.key.as_deref()),
            field_type_opt_str(map.value.as_deref())
        ),
        Some(Kind::Stream(stream)) => match &stream.element {
            Some(v2::stream_type::Element::Named(name)) => format!("<{name}>"),
            Some(v2::stream_type::Element::Primitive(primitive)) => {
                format!("<{}>", primitive_name(*primitive))
            }
            None => "<>".to_string(),
        },
        None => "?".to_string(),
    };
    if field_type.optional {
        rendered.push('?');
    }
    rendered
}

fn primitive_name(primitive: i32) -> &'static str {
    match v2::PrimitiveType::try_from(primitive) {
        Ok(v2::PrimitiveType::Boolean) => "boolean",
        Ok(v2::PrimitiveType::Integer) => "integer",
        Ok(v2::PrimitiveType::Float) => "float",
        Ok(v2::PrimitiveType::String) => "string",
        Ok(v2::PrimitiveType::Bytes) => "bytes",
        _ => "unspecified",
    }
}

fn const_str(def: &v2::ConstDef) -> String {
    if let Some(regex) = &def.regex {
        return format!("regex {regex}");
    }
    match &def.type_ref {
        Some(type_ref) => format!("{}: {}", type_ref, def.value),
        None => def.value.clone(),
    }
}

fn type_repr_str(def: &v2::TypeDef) -> String {
    let backing = match def
        .backing
        .as_ref()
        .and_then(|backing| backing.kind.as_ref())
    {
        Some(v2::backing::Kind::Primitive(primitive)) => primitive_name(*primitive).to_string(),
        Some(v2::backing::Kind::Unit(unit)) => unit.clone(),
        None => "?".to_string(),
    };
    match &def.width {
        Some(v2::type_def::Width::IntWidth(width)) => {
            format!("{backing} {}", int_width_name(*width))
        }
        Some(v2::type_def::Width::FloatWidth(width)) => {
            format!("{backing} {}", float_width_name(*width))
        }
        None => backing,
    }
}

fn int_width_name(width: i32) -> &'static str {
    match v2::IntWidth::try_from(width) {
        Ok(v2::IntWidth::U8) => "u8",
        Ok(v2::IntWidth::I8) => "i8",
        Ok(v2::IntWidth::U16) => "u16",
        Ok(v2::IntWidth::I16) => "i16",
        Ok(v2::IntWidth::U32) => "u32",
        Ok(v2::IntWidth::I32) => "i32",
        Ok(v2::IntWidth::U64) => "u64",
        Ok(v2::IntWidth::I64) => "i64",
        _ => "unspecified",
    }
}

fn float_width_name(width: i32) -> &'static str {
    match v2::FloatWidth::try_from(width) {
        Ok(v2::FloatWidth::F32) => "f32",
        Ok(v2::FloatWidth::F64) => "f64",
        _ => "unspecified",
    }
}

fn constraint_str(constraint: Option<&v2::Constraint>) -> String {
    let Some(constraint) = constraint else {
        return "(none)".to_string();
    };
    let mut parts = Vec::new();
    if let Some(min) = &constraint.min {
        parts.push(format!("min={min}"));
    }
    if let Some(max) = &constraint.max {
        parts.push(format!("max={max}"));
    }
    if let Some(step) = &constraint.step {
        parts.push(format!("step={step}"));
    }
    if let Some(len_min) = constraint.len_min {
        parts.push(format!("len_min={len_min}"));
    }
    if let Some(len_max) = constraint.len_max {
        parts.push(format!("len_max={len_max}"));
    }
    if let Some(pattern) = &constraint.pattern {
        parts.push(format!("pattern={pattern}"));
    }
    format!("[{}]", parts.join(" "))
}

fn type_init_str(def: &v2::TypeDef) -> String {
    if let Some(declared) = &def.declared_init {
        return declared.clone();
    }
    match def.init.as_ref().and_then(|init| init.value.as_ref()) {
        Some(value) => value.clone(),
        None => "(none)".to_string(),
    }
}

fn signal_init_str(def: &v2::SignalDef) -> String {
    if let Some(declared) = &def.declared_init {
        return declared.clone();
    }
    match def.init.as_ref().and_then(|init| init.value.as_ref()) {
        Some(value) => value.clone(),
        None => "(none)".to_string(),
    }
}