amberfork-layout 0.9.1

The semantic view-model between amberfork's DiffResult and its painters (CLI, web).
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
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
//! The semantic view-model over a [`DiffResult`] — the one seam every painter reads
//! (issue #21, design doc Amendment 2026-07-11).
//!
//! ```text
//!            DiffResult  (+ the two Runs)
//!                     │
//!                     ▼
//!             amberfork-layout
//!                     │
//!                     ▼
//!                 ViewModel
//!        semantic rows (spine / fork / downstream), step summaries,
//!        designed wording (confidence, verdict, absence), attribution
//!        reading order, field-diff evidence
//!                     │
//!         ┌───────────┴───────────┐
//!         ▼                       ▼
//!   CLI painter (render.rs)   web painter (ui/, Leptos)
//!   columns · glyphs · ANSI   SVG/DOM geometry
//! ```
//!
//! What lives here is exactly what every surface must agree on: which alignment move plays
//! which role, the one-line gist of a step, the wording rules the design locked — confidence
//! as `conf 0.NN` with the explicit `marginal call` at zero (notebook 005), the converged
//! verdict that only claims "identical" when the alignment earned it (issue #19), the
//! `(no aligned step)` absence — plus the attribution reading order (DR5) and the
//! field-level evidence at the fork.
//!
//! What deliberately does NOT live here is any painter's own arithmetic: column widths,
//! truncation, wrapping, gutter glyphs, and ANSI are the CLI painter's business; pixel
//! geometry is the web painter's. This crate has zero terminal dependencies, and styling
//! decisions never feed back into it.
//!
//! For the web painter the view crosses a wire: [`Document`] is the serializable form the
//! server ships (issue #24) — the same [`ViewModel`] plus a [`DOCUMENT_VERSION`] stamp and
//! the payload envelope: building the document cuts every payload-derived slot at
//! [`SLOT_TEXT_LIMIT`] bytes with an explicit [`SlotText::truncated`] mark the UI must
//! render visibly.

use std::fmt;

use amberfork_model::{
    Attribution, AttributionMode, Counterfactual, DiffResult, FieldDiffKind, Payload, Recovery,
    ResourceDelta, ResourceDeltas, Run, Step,
};
use serde::{Deserialize, Serialize};

// The model types embedded in the view-model's public fields (`StepView::kind`, `StepRow::kind`,
// `RunHeader::outcome`, `ViewModel::warnings`) and named by the `*_label` helpers travel with it:
// a consumer that reads a `ViewModel` must be able to name what it is made of. This completes the
// view-model's own type surface — it is the contract, not a barrel re-export of the engine.
pub use amberfork_model::{MoveKind, Outcome, StepKind, Warning};

/// The design system's stylesheet — the single source both painters dress from.
///
/// It lives beside the view-model rather than in `ui/` for a packaging reason: `ui/` is a
/// separate workspace, so `crates/amberfork/src/html_export.rs` could only reach it with an
/// `include_str!` that escapes its own crate root, which builds in the repo and then fails
/// `cargo package` (the tarball carries no path outside the crate). Owning it here makes it a
/// normal dependency for the static export, while `ui/index.html` inlines the same bytes at
/// build time via trunk — one stylesheet, no hand-copied second copy to drift.
pub const UI_CSS: &str = include_str!("../ui.css");

/// The document version this build emits. A bare wire-hygiene marker (issue #24): the web UI
/// and the server ship in one binary, lockstep by construction, so there is no read-gate —
/// bump it when the document's shape changes so a stale payload is at least identifiable.
/// `0.2`: field-level evidence moved from `ForkRow` onto every [`AlignedStep`] (issue #27) so
/// the content-diff pane can show any selected pair's diff, not only the fork's.
pub const DOCUMENT_VERSION: &str = "0.2";

/// The wire form of the seam: what `amberfork serve` ships to the web painter. The body is
/// the SAME [`ViewModel`] the terminal paints — the document only adds wire hygiene on top.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Document {
    /// Always [`DOCUMENT_VERSION`] when built by this crate.
    pub schema_version: String,
    pub view: ViewModel,
}

impl Document {
    /// Wrap a view for the wire: stamp the current document version and enforce the payload
    /// envelope. There is deliberately no other way to build a [`Document`], so an
    /// over-limit payload can never reach the browser unmarked (issue #24).
    #[must_use]
    pub fn new(mut view: ViewModel) -> Self {
        envelope(&mut view);
        Self {
            schema_version: DOCUMENT_VERSION.to_string(),
            view,
        }
    }
}

/// The payload envelope's per-slot byte limit. The threat is multi-MB field-diff payloads
/// (eng review D12+D17): a slot is one display line, so 4 KiB loses nothing any pane shows
/// unexpanded (expand-on-demand is issue #30's job) while keeping a worst-case document of
/// hundreds of rows around a megabyte. Bytes, not chars, because the guard protects wire
/// size; the cut backs off to a UTF-8 char boundary.
pub const SLOT_TEXT_LIMIT: usize = 4096;

/// Cut every payload-derived slot in the view down to [`SLOT_TEXT_LIMIT`], marking the cut and
/// stamping a [`SlotAddress`] the served view can be asked to resolve back to full text with
/// (issue #30). The fork adds its own resolved sides on top; the field-level evidence rides on
/// the aligned step now, so [`envelope_step`] bounds it uniformly for every row.
fn envelope(view: &mut ViewModel) {
    for (row, r) in view.rows.iter_mut().enumerate() {
        match r {
            Row::Step(step_row) => envelope_step(row, &mut step_row.step),
            Row::Fork(fork) => {
                envelope_step(row, &mut fork.step);
                fork.side_a.truncate_to(SLOT_TEXT_LIMIT, || SlotAddress {
                    row,
                    kind: SlotKind::ForkSide { side: Side::A },
                });
                fork.side_b.truncate_to(SLOT_TEXT_LIMIT, || SlotAddress {
                    row,
                    kind: SlotKind::ForkSide { side: Side::B },
                });
            }
        }
    }
}

fn envelope_step(row: usize, step: &mut AlignedStep) {
    for (side, view) in [(Side::A, &mut step.a), (Side::B, &mut step.b)] {
        if let Some(view) = view {
            view.summary.truncate_to(SLOT_TEXT_LIMIT, || SlotAddress {
                row,
                kind: SlotKind::StepSummary { side },
            });
        }
    }
    for fd in &mut step.field_diffs {
        if let Some(removed) = &mut fd.removed {
            let path = fd.path.clone();
            removed.truncate_to(SLOT_TEXT_LIMIT, || SlotAddress {
                row,
                kind: SlotKind::FieldRemoved { path },
            });
        }
        if let Some(added) = &mut fd.added {
            let path = fd.path.clone();
            added.truncate_to(SLOT_TEXT_LIMIT, || SlotAddress {
                row,
                kind: SlotKind::FieldAdded { path },
            });
        }
    }
}

/// One payload-derived text slot. [`ViewModel::compute`] always produces the full text;
/// only the payload envelope in [`Document::new`] sets `truncated` — so the CLI painter,
/// which reads the view directly, never sees a cut slot. Generated wording (verdicts,
/// confidence, attribution, warnings) is bounded by construction and stays plain `String`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlotText {
    pub text: String,
    /// Whether the envelope cut this slot at [`SLOT_TEXT_LIMIT`]. A UI must render the
    /// mark visibly — a silently shortened payload reads as the payload.
    #[serde(default, skip_serializing_if = "is_false")]
    pub truncated: bool,
    /// Where to find this slot's full text again (issue #30: expand-on-demand). `Some` iff
    /// `truncated` — an unmarked slot already carries its full text, so it needs no address.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub address: Option<SlotAddress>,
}

impl SlotText {
    /// A full, unmarked slot — the only form [`ViewModel::compute`] emits.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            truncated: false,
            address: None,
        }
    }

    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Cut to the largest char boundary within `limit` bytes and mark the cut, stamping
    /// where the full text can be found again. `address` is a closure rather than a value so
    /// building one (a field-diff address clones a path string) costs nothing on the
    /// overwhelmingly common under-limit path.
    fn truncate_to(&mut self, limit: usize, address: impl FnOnce() -> SlotAddress) {
        if self.text.len() <= limit {
            return;
        }
        let cut = (0..=limit)
            .rev()
            .find(|&i| self.text.is_char_boundary(i))
            .unwrap_or(0);
        self.text.truncate(cut);
        self.truncated = true;
        self.address = Some(address());
    }
}

/// Which of a row's two runs a slot belongs to — the `DiffResult` side convention (`a` is the
/// reference, `b` the observed run), reused here rather than a second vocabulary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Side {
    A,
    B,
}

/// Which slot within a row's [`AlignedStep`] (or [`ForkRow`]) a [`SlotAddress`] names.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SlotKind {
    /// [`StepView::summary`] on the named side.
    StepSummary { side: Side },
    /// [`ForkRow::side_a`] / `side_b`.
    ForkSide { side: Side },
    /// [`FieldDiffView::removed`] at the named field path.
    FieldRemoved { path: String },
    /// [`FieldDiffView::added`] at the named field path.
    FieldAdded { path: String },
}

/// A stable pointer to one payload-derived slot, good for the life of one `Document` (rows
/// are positional, so this does not survive a re-diff). Round-trips over the wire so the web
/// painter can hand one straight back to the server to ask for the full text (issue #30).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlotAddress {
    /// Index into [`ViewModel::rows`].
    pub row: usize,
    pub kind: SlotKind,
}

/// The wire form of one resolved [`SlotAddress`] (issue #30) — deliberately just the text, no
/// echo of the address or the `truncated` marker: the caller already has both from the
/// document it read the address off, so restating them here would only invite the two copies
/// to drift. Shared by `amberfork-server`'s handler and the web painter's fetch, the same way
/// [`Document`] is — one wire contract, not one redeclared per consumer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PayloadResponse {
    pub text: String,
}

impl fmt::Display for SlotText {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.text)
    }
}

/// Content comparison — the mark is provenance, not content.
impl PartialEq<&str> for SlotText {
    fn eq(&self, other: &&str) -> bool {
        self.text == *other
    }
}

fn is_false(value: &bool) -> bool {
    !*value
}

/// The full semantic view of one diff: everything a painter needs, nothing it must compute.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ViewModel {
    pub run_a: RunHeader,
    pub run_b: RunHeader,
    /// Digits for zero-padded step indices (`step 06`), derived from the runs' largest step
    /// index — shared number-formatting voice, not a column width (those are data-derived,
    /// these are medium-derived; only the former belong in the seam).
    pub idx_width: usize,
    pub rows: Vec<Row>,
    pub verdict: Verdict,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attribution: Option<AttributionView>,
    /// Latency / token deltas between the two runs (issue #40), already formatted in the
    /// designed wording. `None` when [`DiffResult::deltas`] is `None` (nothing to show), not
    /// when a delta happens to be zero — a real zero still renders `+0ms`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deltas: Option<DeltasView>,
    /// Pass-through of the result's warnings so a painter never reaches back into
    /// [`DiffResult`]: the CLI keeps warnings on stderr, the web UI surfaces them inline.
    pub warnings: Vec<Warning>,
}

/// A run's identity as every surface introduces it (terminal header lines, web header bar).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RunHeader {
    pub id: String,
    pub role: RunRole,
    pub n_steps: usize,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outcome: Option<Outcome>,
}

/// Which seat a run occupies in the diff — the `DiffResult` contract's side convention:
/// `a` is always the reference, `b` the observed/failing run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RunRole {
    Reference,
    Observed,
}

impl RunRole {
    /// The designed label every surface prints.
    pub fn label(self) -> &'static str {
        match self {
            Self::Reference => "reference",
            Self::Observed => "observed",
        }
    }
}

/// One alignment move as a display row.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Row {
    /// A regular move: spine before the fork, divergent path after it.
    Step(StepRow),
    /// The fork itself, with both sides' content and the field-level evidence.
    Fork(ForkRow),
}

impl Row {
    /// The aligned pair behind the row, whichever variant it is.
    pub fn step(&self) -> &AlignedStep {
        match self {
            Self::Step(row) => &row.step,
            Self::Fork(row) => &row.step,
        }
    }
}

/// Where a non-fork row stands relative to the fork — the role that drives every painter's
/// styling (sameness recedes, divergence glows).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RowRole {
    /// Before the fork, or every row of a converged diff. The eye skates over it.
    Spine,
    /// After the fork: the divergent path stays marked.
    Downstream,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StepRow {
    pub role: RowRole,
    /// The move's alignment kind; painters frame it as the row tag (the CLI brackets it).
    pub kind: MoveKind,
    pub step: AlignedStep,
}

/// The fork row: the first move of the block the alignment never recovers from.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ForkRow {
    pub step: AlignedStep,
    /// Reference-side content at the fork, resolved to the designed absence wording
    /// (`(no aligned step)`) when the fork has no step on that side.
    pub side_a: SlotText,
    /// Observed-side counterpart of `side_a`.
    pub side_b: SlotText,
    /// Designed confidence wording: `conf 0.NN`, or `marginal call` at zero (notebook 005).
    pub confidence: String,
}

/// The two sides of one alignment move, resolved for display. Indices are kept separate
/// from the resolved views: a gap move has an index on one side only, and a painter still
/// shows the index even where (malformed hand-built input) it resolves to no step.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AlignedStep {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub a_idx: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub b_idx: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub a: Option<StepView>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub b: Option<StepView>,
    /// Field-level `-`/`+` evidence for this synchronous pair — the only red/green in any
    /// surface. Empty when the payloads matched (a recede-worthy sync) or the move has no
    /// counterpart to compare (a log/model gap move); the engine emits it for every sync,
    /// so it rides the pair, not the fork alone (issue #27). The content-diff pane shows
    /// the selected row's; the terminal renders only the fork's.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub field_diffs: Vec<FieldDiffView>,
}

impl AlignedStep {
    /// The step fronting a single-line rendering: the observed side where it exists — that
    /// is the run being debugged — the reference side for model-only moves.
    pub fn front(&self) -> Option<&StepView> {
        self.b.as_ref().or(self.a.as_ref())
    }

    /// The index shown in the gutter, matching [`Self::front`]'s side priority.
    pub fn display_idx(&self) -> Option<usize> {
        self.b_idx.or(self.a_idx)
    }
}

/// One side's step, resolved to what surfaces display.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StepView {
    pub kind: StepKind,
    pub name: String,
    /// One-line gist: first line of the step's output (else input) text, compact JSON for
    /// structured payloads, or the designed `(no content captured)`.
    pub summary: SlotText,
}

/// One field-level difference at the fork, values already in display form (compact JSON).
/// `removed`/`added` are what a painter shows on the `-`/`+` side; an added field has no
/// `removed`, a removed field no `added`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FieldDiffView {
    pub path: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub removed: Option<SlotText>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub added: Option<SlotText>,
}

/// The one-line answer every diff ends with.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Verdict {
    /// Every move a sync at cost 0 — a claim the alignment must earn (issue #19).
    Identical {
        steps: usize,
    },
    /// No fork, but the alignment absorbed divergence (gap moves, costly syncs) on the way.
    Absorbed {
        absorbed: usize,
        a_steps: usize,
        b_steps: usize,
    },
    Forked,
}

impl Verdict {
    /// The designed converged statement; `None` when forked — the fork row and attribution
    /// carry the answer instead.
    pub fn converged_text(&self) -> Option<String> {
        match *self {
            Self::Identical { steps } => {
                Some(format!("converged — identical through {steps} steps"))
            }
            Self::Absorbed {
                absorbed,
                a_steps,
                b_steps,
            } => Some(format!(
                "converged — no fork ({absorbed} absorbed divergence{} across {a_steps}⇄{b_steps} steps)",
                if absorbed == 1 { "" } else { "s" },
            )),
            Self::Forked => None,
        }
    }
}

/// The attribution answer in DR5's reading order — mode, origin, propagation, confidence, then
/// the counterfactual verdict when there is one — each part already in its designed wording. The
/// terminal flattens the parts to one line; the web attribution pane renders them as separate
/// elements.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttributionView {
    /// `static` or `counterfactual` — owned, not `&'static str`, because the view must
    /// deserialize on the web side of the wire.
    pub mode: String,
    /// `origin step 02` (gutter-padded) or `origin unlocalized`.
    pub origin: String,
    /// `step 03`, a contiguous `steps 03–07`, a comma list, or `none`.
    pub propagation: String,
    pub confidence: String,
    /// The counterfactual recovery verdict — `recovered · 3 runs`, `not recovered · 3 runs`, or
    /// `unverified · 3 runs` — present only when re-execution produced evidence. `None` for static
    /// attribution, whose wire form and terminal line are therefore unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub verdict: Option<String>,
}

/// Latency / token deltas, already in the designed wording (`+5.20s`, `-300 tok`) so no
/// painter reinvents the sign/units convention. Mirrors [`AttributionView`]'s split: the
/// terminal flattens the parts to one line, the web pane can lay them out as separate elements.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DeltasView {
    /// Whole-run totals, when at least one of latency/tokens has data on both sides.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub total: Option<String>,
    /// The delta at just the diverging step, when the fork lands on a synchronous pair.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub at_fork: Option<String>,
}

impl ViewModel {
    /// Build the semantic view. Pure and total: any `DiffResult` over its two runs yields a
    /// view, and nothing here inspects the output medium.
    pub fn compute(result: &DiffResult, reference: &Run, observed: &Run) -> Self {
        let max_idx = reference
            .steps
            .iter()
            .chain(&observed.steps)
            .map(|s| s.idx)
            .max()
            .unwrap_or(0);
        let idx_width = decimal_digits(max_idx).max(2);

        let rows = result
            .alignment
            .iter()
            .enumerate()
            .map(|(i, mv)| {
                let step = AlignedStep {
                    a_idx: mv.a_idx,
                    b_idx: mv.b_idx,
                    a: step_view(reference, mv.a_idx),
                    b: step_view(observed, mv.b_idx),
                    // The field-level evidence rides on the pair, so every sync row carries its
                    // own — the content-diff pane reads the selected row's, not only the fork's.
                    field_diffs: field_diff_views(result, i),
                };
                match result.fork {
                    Some(fork) if i == fork.index => Row::Fork(ForkRow {
                        step,
                        side_a: side_content(reference, fork.a_step),
                        side_b: side_content(observed, fork.b_step),
                        confidence: confidence_text(fork.confidence),
                    }),
                    Some(fork) if i > fork.index => Row::Step(StepRow {
                        role: RowRole::Downstream,
                        kind: mv.kind,
                        step,
                    }),
                    _ => Row::Step(StepRow {
                        role: RowRole::Spine,
                        kind: mv.kind,
                        step,
                    }),
                }
            })
            .collect();

        let verdict = match result.fork {
            Some(_) => Verdict::Forked,
            None => {
                // "identical" is a claim the alignment must earn: every move a sync at cost
                // 0. Anything the resync rule merely absorbed (gap moves, costly syncs)
                // converged without being identical (issue #19).
                let absorbed = result
                    .alignment
                    .iter()
                    .filter(|mv| mv.kind != MoveKind::Sync || mv.cost > 0.0)
                    .count();
                if absorbed == 0 {
                    Verdict::Identical {
                        steps: result.alignment.len(),
                    }
                } else {
                    Verdict::Absorbed {
                        absorbed,
                        a_steps: reference.steps.len(),
                        b_steps: observed.steps.len(),
                    }
                }
            }
        };

        Self {
            run_a: RunHeader {
                id: result.runs.a.id.clone(),
                role: RunRole::Reference,
                n_steps: reference.steps.len(),
                outcome: reference.outcome,
            },
            run_b: RunHeader {
                id: result.runs.b.id.clone(),
                role: RunRole::Observed,
                n_steps: observed.steps.len(),
                outcome: observed.outcome,
            },
            idx_width,
            rows,
            verdict,
            attribution: result
                .attribution
                .as_ref()
                .map(|a| attribution_view(a, idx_width)),
            deltas: result.deltas.as_ref().and_then(deltas_view),
            warnings: result.warnings.clone(),
        }
    }

    /// Resolve a [`SlotAddress`] back to full text (issue #30: expand-on-demand). Only
    /// meaningful called on a pre-envelope view — [`ViewModel::compute`]'s own output, never a
    /// [`Document`]'s already-truncated one — so the caller must hold onto that view itself;
    /// nothing here re-derives it. `None` means the address does not resolve against this view
    /// (a stale address from a different diff, a malformed request), not that the slot is empty.
    #[must_use]
    pub fn full_text(&self, address: &SlotAddress) -> Option<&str> {
        let row = self.rows.get(address.row)?;
        match &address.kind {
            SlotKind::StepSummary { side } => {
                let step = match side {
                    Side::A => row.step().a.as_ref(),
                    Side::B => row.step().b.as_ref(),
                }?;
                Some(step.summary.as_str())
            }
            SlotKind::ForkSide { side } => {
                let Row::Fork(fork) = row else {
                    return None;
                };
                Some(match side {
                    Side::A => fork.side_a.as_str(),
                    Side::B => fork.side_b.as_str(),
                })
            }
            SlotKind::FieldRemoved { path } => row
                .step()
                .field_diffs
                .iter()
                .find(|fd| &fd.path == path)?
                .removed
                .as_ref()
                .map(SlotText::as_str),
            SlotKind::FieldAdded { path } => row
                .step()
                .field_diffs
                .iter()
                .find(|fd| &fd.path == path)?
                .added
                .as_ref()
                .map(SlotText::as_str),
        }
    }

    /// The one-line verdict headline every surface opens with: `serve`'s terminal handoff
    /// and the web header print the SAME string (issue #25 amendment), so it lives here
    /// with the rest of the designed wording, not in a painter.
    ///
    /// Forked: `⑂ forked at step 02 · conf 0.86` — index padded like the gutter, confidence
    /// in the fork row's designed wording (so `marginal call` composes for free).
    /// Converged: exactly [`Verdict::converged_text`].
    pub fn headline(&self) -> String {
        if let Some(text) = self.verdict.converged_text() {
            return text;
        }
        // Forked: compute() emits exactly one fork row alongside a Forked verdict; the
        // bare-claim fallback keeps this total for hand-built views (never panics).
        let fork = self.rows.iter().find_map(|row| match row {
            Row::Fork(fork) => Some(fork),
            Row::Step(_) => None,
        });
        let Some(fork) = fork else {
            return "⑂ forked".to_string();
        };
        let idx = match fork.step.display_idx() {
            Some(i) => format!("{i:0w$}", w = self.idx_width),
            // The gutter's absence convention (a fork row with no index on either side).
            None => "·".repeat(self.idx_width),
        };
        format!("⑂ forked at step {idx} · {}", fork.confidence)
    }
}

/// The canonical step-kind vocabulary every surface prints.
pub fn kind_label(kind: StepKind) -> &'static str {
    match kind {
        StepKind::Llm => "llm",
        StepKind::Tool => "tool",
        StepKind::Agent => "agent",
        StepKind::Other => "other",
    }
}

/// The canonical move-kind vocabulary; painters add their own framing (the CLI brackets it
/// into `[sync]`, the web renders a chip).
pub fn move_label(kind: MoveKind) -> &'static str {
    match kind {
        MoveKind::Sync => "sync",
        MoveKind::Log => "log-move",
        MoveKind::Model => "model-move",
    }
}

/// The canonical outcome vocabulary.
pub fn outcome_label(outcome: Outcome) -> &'static str {
    match outcome {
        Outcome::Pass => "pass",
        Outcome::Fail => "fail",
        Outcome::Unknown => "unknown",
    }
}

/// Confidence per notebook 005: zero — the designed weak-call state (evidence ≤ τ) — is
/// stated in words, never rendered as a small number.
pub fn confidence_text(confidence: f64) -> String {
    if confidence <= f64::EPSILON {
        "marginal call".to_string()
    } else {
        format!("conf {confidence:.2}")
    }
}

/// One side of an alignment move, where its index resolves to a real step.
fn step_view(run: &Run, idx: Option<usize>) -> Option<StepView> {
    idx.and_then(|i| run.steps.get(i)).map(|s| StepView {
        kind: s.kind,
        name: s.name.clone(),
        summary: SlotText::new(summarize(s)),
    })
}

/// Fork-side content: the step's summary, empty where an index resolves to no step, the
/// designed absence wording where the fork has no step on that side at all.
fn side_content(run: &Run, step: Option<usize>) -> SlotText {
    SlotText::new(match step {
        Some(idx) => run.steps.get(idx).map_or_else(String::new, summarize),
        None => "(no aligned step)".to_string(),
    })
}

/// The field-level evidence attached to the fork's alignment index, values in display form.
fn field_diff_views(result: &DiffResult, index: usize) -> Vec<FieldDiffView> {
    result
        .field_diffs
        .iter()
        .filter(|fd| fd.step == index)
        .map(|fd| FieldDiffView {
            path: fd.path.clone(),
            removed: match fd.kind {
                FieldDiffKind::Added => None,
                _ => fd.before.as_ref().map(|v| SlotText::new(compact_json(v))),
            },
            added: match fd.kind {
                FieldDiffKind::Removed => None,
                _ => fd.after.as_ref().map(|v| SlotText::new(compact_json(v))),
            },
        })
        .collect()
}

fn attribution_view(attribution: &Attribution, idx_width: usize) -> AttributionView {
    let mode = match attribution.mode {
        AttributionMode::Static => "static",
        AttributionMode::Counterfactual => "counterfactual",
    }
    .to_string();
    let origin = attribution.origin_step.map_or_else(
        || "origin unlocalized".to_string(),
        |s| format!("origin step {s:0w$}", w = idx_width),
    );
    AttributionView {
        mode,
        origin,
        propagation: steps_text(&attribution.propagation, idx_width),
        confidence: confidence_text(attribution.confidence),
        // Keyed on the evidence, not the mode: a verdict appears iff re-execution produced one, so
        // static attribution stays verdict-free and its rendering is untouched.
        verdict: attribution.counterfactual.as_ref().map(verdict_text),
    }
}

/// The counterfactual verdict wording: the recovery outcome and the run count that backs it —
/// `recovered · 3 runs`, `not recovered · 1 run`, `unverified · 3 runs`. The tri-state maps
/// one-to-one to [`Recovery`], so `unverified` reads as the honest "we re-ran but the runs did not
/// agree", never as a silent absence.
fn verdict_text(counterfactual: &Counterfactual) -> String {
    let outcome = match counterfactual.recovered {
        Recovery::Recovered => "recovered",
        Recovery::NotRecovered => "not recovered",
        Recovery::Unverified => "unverified",
    };
    let runs = counterfactual.runs;
    let unit = if runs == 1 { "run" } else { "runs" };
    format!("{outcome} · {runs} {unit}")
}

/// Resolve a [`ResourceDeltas`] to its designed wording, or `None` when neither granularity
/// has anything to say (both fields empty on both `total` and `at_fork`).
fn deltas_view(deltas: &ResourceDeltas) -> Option<DeltasView> {
    let total = delta_text(&deltas.total);
    let at_fork = deltas.at_fork.as_ref().and_then(delta_text);
    (total.is_some() || at_fork.is_some()).then_some(DeltasView { total, at_fork })
}

/// One measurement's designed wording: `+5.20s`, `-300 tok`, or both joined — `None` when
/// neither latency nor tokens is present on this delta.
fn delta_text(delta: &ResourceDelta) -> Option<String> {
    let parts: Vec<String> = [
        delta.latency_ms.map(latency_text),
        delta.tokens.map(token_text),
    ]
    .into_iter()
    .flatten()
    .collect();
    (!parts.is_empty()).then(|| parts.join(" · "))
}

/// A millisecond delta, signed: sub-second deltas stay in `ms` (`+120ms`) so a fast local step
/// doesn't round to `+0.00s`; anything at or past a second switches to `s` (`+5.20s`).
fn latency_text(ms: i64) -> String {
    let sign = if ms < 0 { '-' } else { '+' };
    let abs = ms.unsigned_abs();
    if abs >= 1000 {
        format!("{sign}{:.2}s", abs as f64 / 1000.0)
    } else {
        format!("{sign}{abs}ms")
    }
}

/// A token-count delta, signed: `+300 tok`, `-40 tok`.
fn token_text(tokens: i64) -> String {
    let sign = if tokens < 0 { '-' } else { '+' };
    format!("{sign}{} tok", tokens.unsigned_abs())
}

/// A step list in the gutter's zero-padded style: `none`, `step 03`, a contiguous
/// `steps 03–07`, or a comma list when a future mode emits gaps.
fn steps_text(steps: &[usize], idx_width: usize) -> String {
    let pad = |s: &usize| format!("{s:0idx_width$}");
    let contiguous = steps.windows(2).all(|w| w[1] == w[0] + 1);
    match steps {
        [] => "none".to_string(),
        [only] => format!("step {}", pad(only)),
        [first, .., last] if contiguous => format!("steps {}–{}", pad(first), pad(last)),
        _ => format!(
            "steps {}",
            steps.iter().map(pad).collect::<Vec<_>>().join(", ")
        ),
    }
}

/// One-line gist of a step: its output (else input) text, first line only.
fn summarize(step: &Step) -> String {
    let payload = step.outputs.as_ref().or(step.inputs.as_ref());
    match payload {
        None => "(no content captured)".to_string(),
        Some(Payload::Text(t)) => t.lines().next().unwrap_or("").to_string(),
        Some(Payload::Object(map)) => compact_json(&serde_json::Value::Object(map.clone())),
        Some(Payload::Other(v)) => compact_json(v),
    }
}

fn compact_json(value: &serde_json::Value) -> String {
    serde_json::to_string(value).unwrap_or_else(|_| value.to_string())
}

fn decimal_digits(n: usize) -> usize {
    if n == 0 { 1 } else { n.ilog10() as usize + 1 }
}

#[cfg(test)]
mod tests {
    use super::*;
    use amberfork_model::{
        Attribution, DiffResult, FieldDiff, Fork, Meta, Move, RunPair, RunRef, Source, Warning,
        WarningCode, test_support,
    };
    use serde_json::json;

    // Field lists live in amberfork-model's test-support builders (issue #22); these one-line
    // adapters keep call sites in the shape the assertions read.

    fn step(idx: usize, name: &str, out: &str) -> Step {
        test_support::step(idx, name).text_output(out).build()
    }

    fn run(id: &str, outcome: Outcome, steps: Vec<Step>) -> Run {
        test_support::run(id, steps).outcome(outcome).build()
    }

    fn result(a: &Run, b: &Run, alignment: Vec<Move>, fork: Option<Fork>) -> DiffResult {
        DiffResult {
            runs: RunPair {
                a: RunRef {
                    id: a.id.clone(),
                    task: None,
                    outcome: a.outcome,
                    n_steps: a.steps.len(),
                },
                b: RunRef {
                    id: b.id.clone(),
                    task: None,
                    outcome: b.outcome,
                    n_steps: b.steps.len(),
                },
            },
            alignment,
            fork,
            field_diffs: Vec::new(),
            attribution: None,
            deltas: None,
            warnings: Vec::new(),
            meta: Meta::current(Source::Passive),
        }
    }

    /// Forked pair: two clean syncs, a high-cost sync (the fork), one log move downstream,
    /// with field diffs and a static attribution attached at the fork.
    fn forked(confidence: f64) -> (Run, Run, DiffResult) {
        let a = run(
            "good",
            Outcome::Pass,
            vec![
                step(0, "plan", "search for census data"),
                step(1, "web.search", "9 results, top census.gov"),
                step(2, "web.fetch", "census.gov page: population 8,443,000"),
            ],
        );
        let b = run(
            "bad",
            Outcome::Fail,
            vec![
                step(0, "plan", "search for census data"),
                step(1, "web.search", "9 results, top census.gov"),
                step(
                    2,
                    "web.fetch",
                    "blogspot page: the city has grown to 9,100,000",
                ),
                step(3, "reader", "blog says about 9,100,000 people"),
            ],
        );
        let alignment = vec![
            Move::sync(0, 0, 0.02, 0.98),
            Move::sync(1, 1, 0.05, 0.95),
            Move::sync(2, 2, 0.82, 0.18),
            Move::log(3, 0.6, 0.9),
        ];
        let fork = Fork {
            index: 2,
            a_step: Some(2),
            b_step: Some(2),
            confidence,
        };
        let mut res = result(&a, &b, alignment, Some(fork));
        res.field_diffs = vec![FieldDiff {
            step: 2,
            path: "outputs".to_string(),
            before: Some(json!("census.gov page")),
            after: Some(json!("blogspot page")),
            kind: FieldDiffKind::Changed,
        }];
        res.attribution = Some(Attribution {
            mode: AttributionMode::Static,
            origin_step: Some(2),
            propagation: vec![3],
            counterfactual: None,
            cause_label: None,
            confidence,
        });
        (a, b, res)
    }

    #[test]
    fn forked_rows_carry_roles_in_alignment_order() {
        let (a, b, res) = forked(0.47);
        let view = ViewModel::compute(&res, &a, &b);

        let roles: Vec<&str> = view
            .rows
            .iter()
            .map(|row| match row {
                Row::Step(s) if s.role == RowRole::Spine => "spine",
                Row::Step(_) => "downstream",
                Row::Fork(_) => "fork",
            })
            .collect();
        assert_eq!(roles, ["spine", "spine", "fork", "downstream"]);
        assert_eq!(view.verdict, Verdict::Forked);
        assert_eq!(view.verdict.converged_text(), None);
    }

    #[test]
    fn fork_row_resolves_sides_confidence_and_evidence() {
        let (a, b, res) = forked(0.47);
        let view = ViewModel::compute(&res, &a, &b);

        let Some(Row::Fork(fork)) = view.rows.get(2) else {
            panic!("row 2 is the fork");
        };
        assert_eq!(fork.side_a, "census.gov page: population 8,443,000");
        assert_eq!(
            fork.side_b,
            "blogspot page: the city has grown to 9,100,000"
        );
        assert_eq!(fork.confidence, "conf 0.47");
        assert_eq!(
            fork.step.field_diffs,
            [FieldDiffView {
                path: "outputs".to_string(),
                removed: Some(SlotText::new("\"census.gov page\"")),
                added: Some(SlotText::new("\"blogspot page\"")),
            }]
        );
        // The observed run fronts the row; both sides stay available for the web columns.
        assert_eq!(fork.step.front().unwrap().name, "web.fetch");
        assert_eq!(fork.step.display_idx(), Some(2));
        assert!(fork.step.a.is_some() && fork.step.b.is_some());
    }

    #[test]
    fn attribution_parts_follow_the_reading_order() {
        let (a, b, res) = forked(0.47);
        let view = ViewModel::compute(&res, &a, &b);

        assert_eq!(
            view.attribution,
            Some(AttributionView {
                mode: "static".to_string(),
                origin: "origin step 02".to_string(),
                propagation: "step 03".to_string(),
                confidence: "conf 0.47".to_string(),
                // Static attribution carries no counterfactual evidence, so no verdict — the
                // reading order and wire form are unchanged from before re-execution existed.
                verdict: None,
            })
        );
    }

    /// A counterfactual attribution is the same reading order plus the recovery verdict as a
    /// distinct part — the terminal appends it, the web pane will render it separately.
    #[test]
    fn a_counterfactual_attribution_adds_the_recovery_verdict() {
        let attribution = Attribution {
            mode: AttributionMode::Counterfactual,
            origin_step: Some(2),
            propagation: vec![3],
            counterfactual: Some(Counterfactual {
                recovered: Recovery::Recovered,
                runs: 3,
            }),
            cause_label: None,
            confidence: 0.86,
        };
        let view = attribution_view(&attribution, 2);
        assert_eq!(view.mode, "counterfactual");
        assert_eq!(view.verdict.as_deref(), Some("recovered · 3 runs"));
    }

    /// Every `Recovery` state has its own honest wording, and the run count is pluralized — so a
    /// single-run verify never reads `1 runs` and `unverified` never reads as a silent absence.
    #[test]
    fn each_recovery_state_has_its_designed_verdict_wording() {
        let verdict = |recovered, runs| verdict_text(&Counterfactual { recovered, runs });
        assert_eq!(verdict(Recovery::Recovered, 3), "recovered · 3 runs");
        assert_eq!(verdict(Recovery::NotRecovered, 3), "not recovered · 3 runs");
        assert_eq!(verdict(Recovery::Unverified, 3), "unverified · 3 runs");
        assert_eq!(verdict(Recovery::Recovered, 1), "recovered · 1 run");
    }

    #[test]
    fn compute_carries_deltas_from_the_result_into_the_view() {
        let (a, b, mut res) = forked(0.47);
        res.deltas = Some(ResourceDeltas {
            total: ResourceDelta {
                latency_ms: Some(5_200),
                tokens: Some(300),
            },
            at_fork: Some(ResourceDelta {
                latency_ms: Some(1_200),
                tokens: None,
            }),
        });
        let view = ViewModel::compute(&res, &a, &b);

        assert_eq!(
            view.deltas,
            Some(DeltasView {
                total: Some("+5.20s · +300 tok".to_string()),
                at_fork: Some("+1.20s".to_string()),
            })
        );
    }

    #[test]
    fn compute_leaves_deltas_none_when_the_result_has_none() {
        let (a, b, res) = forked(0.47);
        let view = ViewModel::compute(&res, &a, &b);
        assert_eq!(view.deltas, None);
    }

    #[test]
    fn latency_deltas_switch_units_at_one_second() {
        assert_eq!(latency_text(120), "+120ms");
        assert_eq!(latency_text(-40), "-40ms");
        assert_eq!(latency_text(5_200), "+5.20s");
        assert_eq!(latency_text(-1_000), "-1.00s");
        assert_eq!(latency_text(0), "+0ms");
    }

    #[test]
    fn token_deltas_are_signed() {
        assert_eq!(token_text(300), "+300 tok");
        assert_eq!(token_text(-40), "-40 tok");
    }

    #[test]
    fn a_delta_with_only_tokens_omits_the_latency_segment() {
        let delta = ResourceDelta {
            latency_ms: None,
            tokens: Some(300),
        };
        assert_eq!(delta_text(&delta).as_deref(), Some("+300 tok"));
    }

    #[test]
    fn an_empty_delta_has_no_text() {
        let delta = ResourceDelta {
            latency_ms: None,
            tokens: None,
        };
        assert_eq!(delta_text(&delta), None);
    }

    #[test]
    fn deltas_view_joins_total_and_at_fork() {
        let deltas = ResourceDeltas {
            total: ResourceDelta {
                latency_ms: Some(5_200),
                tokens: Some(300),
            },
            at_fork: Some(ResourceDelta {
                latency_ms: Some(1_200),
                tokens: None,
            }),
        };
        let view = deltas_view(&deltas).expect("both granularities carry data");
        assert_eq!(view.total.as_deref(), Some("+5.20s · +300 tok"));
        assert_eq!(view.at_fork.as_deref(), Some("+1.20s"));
    }

    #[test]
    fn deltas_view_is_none_when_nothing_has_data() {
        let deltas = ResourceDeltas {
            total: ResourceDelta {
                latency_ms: None,
                tokens: None,
            },
            at_fork: None,
        };
        assert!(deltas_view(&deltas).is_none());
    }

    #[test]
    fn every_sync_pair_carries_its_own_field_diff() {
        // The content-diff pane shows the SELECTED row's field diff, so the evidence must ride
        // every sync pair, not only the fork (issue #27). A spine sync whose payloads match
        // stays empty (a recede-worthy pair); a divergent sync downstream of the fork surfaces
        // its own diff — proof the layout no longer discards what the engine already computes.
        let a = run(
            "good",
            Outcome::Pass,
            vec![
                step(0, "plan", "same"),
                step(1, "lookup", "reference value"),
                step(2, "send", "reference tail"),
            ],
        );
        let b = run(
            "bad",
            Outcome::Fail,
            vec![
                step(0, "plan", "same"),
                step(1, "lookup", "observed value"),
                step(2, "send", "observed tail"),
            ],
        );
        // Two costly syncs after a clean one: index 1 is the fork, index 2 the divergent
        // downstream pair.
        let alignment = vec![
            Move::sync(0, 0, 0.0, 1.0),
            Move::sync(1, 1, 0.8, 0.2),
            Move::sync(2, 2, 0.8, 0.2),
        ];
        let fork = Fork {
            index: 1,
            a_step: Some(1),
            b_step: Some(1),
            confidence: 0.8,
        };
        // The engine keys field diffs by alignment index; here we inject the two divergent
        // pairs it would emit (the identical pair 0 emits nothing, by construction).
        let mut res = result(&a, &b, alignment, Some(fork));
        res.field_diffs = vec![
            FieldDiff {
                step: 1,
                path: "outputs".to_string(),
                before: Some(json!("reference value")),
                after: Some(json!("observed value")),
                kind: FieldDiffKind::Changed,
            },
            FieldDiff {
                step: 2,
                path: "outputs".to_string(),
                before: Some(json!("reference tail")),
                after: Some(json!("observed tail")),
                kind: FieldDiffKind::Changed,
            },
        ];
        let view = ViewModel::compute(&res, &a, &b);

        let Some(Row::Step(spine)) = view.rows.first() else {
            panic!("row 0 is the spine");
        };
        assert!(
            spine.step.field_diffs.is_empty(),
            "an identical sync pair carries no field diff: {:?}",
            spine.step.field_diffs
        );

        let Some(Row::Step(down)) = view.rows.get(2) else {
            panic!("row 2 is the divergent downstream sync");
        };
        assert_eq!(down.role, RowRole::Downstream);
        assert_eq!(
            down.step.field_diffs,
            [FieldDiffView {
                path: "outputs".to_string(),
                removed: Some(SlotText::new("\"reference tail\"")),
                added: Some(SlotText::new("\"observed tail\"")),
            }],
            "the divergent downstream pair surfaces its own field diff"
        );
    }

    #[test]
    fn zero_confidence_is_an_explicit_marginal_call() {
        let (a, b, res) = forked(0.0);
        let view = ViewModel::compute(&res, &a, &b);

        let Some(Row::Fork(fork)) = view.rows.get(2) else {
            panic!("row 2 is the fork");
        };
        assert_eq!(fork.confidence, "marginal call");
        assert_eq!(view.attribution.unwrap().confidence, "marginal call");
        assert_eq!(confidence_text(0.47), "conf 0.47");
    }

    #[test]
    fn model_move_fronts_the_reference_side() {
        // A model move exists only on the reference (a) side; the front and the gutter
        // index must follow it there.
        let a = run("good", Outcome::Pass, vec![step(0, "plan", "x")]);
        let b = run("bad", Outcome::Fail, vec![]);
        let res = result(&a, &b, vec![Move::model(0, 0.6, 0.0)], None);
        let view = ViewModel::compute(&res, &a, &b);

        let Some(Row::Step(row)) = view.rows.first() else {
            panic!("one row");
        };
        assert_eq!(row.kind, MoveKind::Model);
        assert_eq!(row.step.front().unwrap().name, "plan");
        assert_eq!(row.step.display_idx(), Some(0));
        assert!(row.step.b.is_none(), "no observed side on a model move");
    }

    #[test]
    fn converged_identical_is_earned_by_all_zero_cost_syncs() {
        let steps = || vec![step(0, "plan", "x"), step(1, "answer", "y")];
        let a = run("good", Outcome::Pass, steps());
        let b = run("good_again", Outcome::Pass, steps());
        let alignment = vec![Move::sync(0, 0, 0.0, 1.0), Move::sync(1, 1, 0.0, 1.0)];
        let view = ViewModel::compute(&result(&a, &b, alignment, None), &a, &b);

        assert_eq!(view.verdict, Verdict::Identical { steps: 2 });
        assert_eq!(
            view.verdict.converged_text().unwrap(),
            "converged — identical through 2 steps"
        );
        assert!(view.attribution.is_none());
    }

    #[test]
    fn headline_forked_names_the_step_and_confidence() {
        let (a, b, res) = forked(0.86);
        let view = ViewModel::compute(&res, &a, &b);
        assert_eq!(view.headline(), "⑂ forked at step 02 · conf 0.86");
    }

    #[test]
    fn headline_composes_the_designed_weak_call_wording() {
        let (a, b, res) = forked(0.0);
        let view = ViewModel::compute(&res, &a, &b);
        assert_eq!(view.headline(), "⑂ forked at step 02 · marginal call");
    }

    #[test]
    fn headline_converged_is_exactly_the_converged_text() {
        let steps = || vec![step(0, "plan", "x"), step(1, "answer", "y")];
        let a = run("good", Outcome::Pass, steps());
        let b = run("good_again", Outcome::Pass, steps());
        let alignment = vec![Move::sync(0, 0, 0.0, 1.0), Move::sync(1, 1, 0.0, 1.0)];
        let view = ViewModel::compute(&result(&a, &b, alignment, None), &a, &b);
        assert_eq!(view.headline(), "converged — identical through 2 steps");
        assert_eq!(Some(view.headline()), view.verdict.converged_text());
    }

    #[test]
    fn absorbed_divergence_never_claims_identical() {
        let a = run(
            "good",
            Outcome::Pass,
            vec![step(0, "plan", "x"), step(1, "answer", "y")],
        );
        let b = run("good_retry", Outcome::Pass, vec![step(0, "plan", "x")]);
        let alignment = vec![Move::sync(0, 0, 0.0, 1.0), Move::model(1, 0.6, 0.0)];
        let view = ViewModel::compute(&result(&a, &b, alignment, None), &a, &b);

        assert_eq!(
            view.verdict,
            Verdict::Absorbed {
                absorbed: 1,
                a_steps: 2,
                b_steps: 1,
            }
        );
        let text = view.verdict.converged_text().unwrap();
        assert_eq!(
            text,
            "converged — no fork (1 absorbed divergence across 2⇄1 steps)"
        );
        assert!(!text.contains("identical"));
    }

    #[test]
    fn missing_fork_side_resolves_to_the_designed_absence() {
        let a = run("good", Outcome::Pass, vec![step(0, "plan", "x")]);
        let b = run("bad", Outcome::Fail, vec![step(0, "other", "y")]);
        let fork = Fork {
            index: 0,
            a_step: None,
            b_step: Some(0),
            confidence: 0.9,
        };
        let res = result(&a, &b, vec![Move::sync(0, 0, 0.9, 0.1)], Some(fork));
        let view = ViewModel::compute(&res, &a, &b);

        let Some(Row::Fork(fork)) = view.rows.first() else {
            panic!("one fork row");
        };
        assert_eq!(fork.side_a, "(no aligned step)");
        assert_eq!(fork.side_b, "y");
    }

    #[test]
    fn contiguous_propagation_collapses_to_a_padded_range() {
        let (a, b, mut res) = forked(0.47);
        res.attribution.as_mut().unwrap().propagation = vec![3, 4, 5];
        let view = ViewModel::compute(&res, &a, &b);
        assert_eq!(view.attribution.unwrap().propagation, "steps 03–05");
    }

    #[test]
    fn document_roundtrips_through_json() {
        let (a, b, res) = forked(0.47);
        let doc = Document::new(ViewModel::compute(&res, &a, &b));
        assert_eq!(doc.schema_version, DOCUMENT_VERSION);

        let json = serde_json::to_string(&doc).unwrap();
        let back: Document = serde_json::from_str(&json).unwrap();
        assert_eq!(back, doc);
    }

    #[test]
    fn roundtripped_roles_match_the_fork() {
        let (a, b, res) = forked(0.47);
        let doc = Document::new(ViewModel::compute(&res, &a, &b));
        let back: Document = serde_json::from_str(&serde_json::to_string(&doc).unwrap()).unwrap();

        let fork_index = res.fork.unwrap().index;
        for (i, row) in back.view.rows.iter().enumerate() {
            match row {
                Row::Fork(_) => assert_eq!(i, fork_index),
                Row::Step(s) if i < fork_index => assert_eq!(s.role, RowRole::Spine),
                Row::Step(s) => assert_eq!(s.role, RowRole::Downstream),
            }
        }
    }

    #[test]
    fn converged_verdicts_survive_the_wire() {
        let steps = || vec![step(0, "plan", "x"), step(1, "answer", "y")];
        let a = run("good", Outcome::Pass, steps());
        let b = run("good_again", Outcome::Pass, steps());
        let alignment = vec![Move::sync(0, 0, 0.0, 1.0), Move::sync(1, 1, 0.0, 1.0)];
        let doc = Document::new(ViewModel::compute(&result(&a, &b, alignment, None), &a, &b));
        let back: Document = serde_json::from_str(&serde_json::to_string(&doc).unwrap()).unwrap();
        assert_eq!(back.view.verdict, Verdict::Identical { steps: 2 });
        assert_eq!(
            back.view.verdict.converged_text().unwrap(),
            "converged — identical through 2 steps"
        );

        // The absorbed distinction (issue #19) must survive the wire too — the web surface
        // may never flatten "converged with absorbed divergence" into "identical".
        let b = run("good_retry", Outcome::Pass, vec![step(0, "plan", "x")]);
        let alignment = vec![Move::sync(0, 0, 0.0, 1.0), Move::model(1, 0.6, 0.0)];
        let doc = Document::new(ViewModel::compute(&result(&a, &b, alignment, None), &a, &b));
        let back: Document = serde_json::from_str(&serde_json::to_string(&doc).unwrap()).unwrap();
        assert_eq!(
            back.view.verdict,
            Verdict::Absorbed {
                absorbed: 1,
                a_steps: 2,
                b_steps: 1,
            }
        );
        assert!(
            !back
                .view
                .verdict
                .converged_text()
                .unwrap()
                .contains("identical")
        );
    }

    #[test]
    fn envelope_truncates_and_marks_over_limit_slots() {
        let huge = "x".repeat(SLOT_TEXT_LIMIT + 100);
        let a = run("good", Outcome::Pass, vec![step(0, "fetch", &huge)]);
        let b = run("bad", Outcome::Fail, vec![step(0, "fetch", "small")]);
        let fork = Fork {
            index: 0,
            a_step: Some(0),
            b_step: Some(0),
            confidence: 0.9,
        };
        let mut res = result(&a, &b, vec![Move::sync(0, 0, 0.9, 0.1)], Some(fork));
        res.field_diffs = vec![FieldDiff {
            step: 0,
            path: "outputs".to_string(),
            before: Some(json!(huge.clone())),
            after: Some(json!("small")),
            kind: FieldDiffKind::Changed,
        }];
        let doc = Document::new(ViewModel::compute(&res, &a, &b));

        let Some(Row::Fork(fork)) = doc.view.rows.first() else {
            panic!("one fork row");
        };
        // The same over-limit payload feeds side_a and the a-side summary; both arrive cut,
        // each with its OWN address (issue #30) — they are two distinct slots, not aliases.
        assert!(fork.side_a.truncated);
        assert_eq!(fork.side_a.text.len(), SLOT_TEXT_LIMIT);
        assert!(huge.starts_with(&fork.side_a.text));
        assert_eq!(
            fork.side_a.address,
            Some(SlotAddress {
                row: 0,
                kind: SlotKind::ForkSide { side: Side::A },
            })
        );
        let a_summary = &fork.step.a.as_ref().unwrap().summary;
        assert!(a_summary.truncated);
        assert_eq!(a_summary.text.len(), SLOT_TEXT_LIMIT);
        assert!(huge.starts_with(&a_summary.text));
        assert_eq!(
            a_summary.address,
            Some(SlotAddress {
                row: 0,
                kind: SlotKind::StepSummary { side: Side::A },
            })
        );

        assert!(!fork.side_b.truncated);
        assert_eq!(fork.side_b.address, None);
        let removed = fork.step.field_diffs[0].removed.as_ref().unwrap();
        assert!(removed.truncated);
        assert!(removed.text.len() <= SLOT_TEXT_LIMIT);
        assert_eq!(
            removed.address,
            Some(SlotAddress {
                row: 0,
                kind: SlotKind::FieldRemoved {
                    path: "outputs".to_string()
                },
            })
        );
        let added = fork.step.field_diffs[0].added.as_ref().unwrap();
        assert!(!added.truncated);
        assert_eq!(added.address, None);

        // The marker itself survives the wire.
        let back: Document = serde_json::from_str(&serde_json::to_string(&doc).unwrap()).unwrap();
        assert_eq!(back, doc);
    }

    #[test]
    fn full_text_resolves_every_truncated_slot_kind_back_to_the_untruncated_view() {
        // Issue #30: the server keeps ViewModel::compute's own (pre-envelope, full-fidelity)
        // output around so it can answer an expand-on-demand request. Every address stamped
        // by envelope() on the served Document must resolve against that full view.
        let huge = "x".repeat(SLOT_TEXT_LIMIT + 100);
        let a = run("good", Outcome::Pass, vec![step(0, "fetch", &huge)]);
        let b = run("bad", Outcome::Fail, vec![step(0, "fetch", &huge)]);
        let fork = Fork {
            index: 0,
            a_step: Some(0),
            b_step: Some(0),
            confidence: 0.9,
        };
        let mut res = result(&a, &b, vec![Move::sync(0, 0, 0.9, 0.1)], Some(fork));
        res.field_diffs = vec![FieldDiff {
            step: 0,
            path: "outputs".to_string(),
            before: Some(json!(huge.clone())),
            after: Some(json!(huge.clone())),
            kind: FieldDiffKind::Changed,
        }];
        // The full view is exactly what a server would hold onto before calling Document::new.
        let full_view = ViewModel::compute(&res, &a, &b);
        let doc = Document::new(full_view.clone());

        let Some(Row::Fork(fork)) = doc.view.rows.first() else {
            panic!("one fork row");
        };
        // side_a/side_b and both step summaries carry the raw step text verbatim.
        let raw_text_addresses = [
            fork.side_a.address.clone().unwrap(),
            fork.side_b.address.clone().unwrap(),
            fork.step
                .a
                .as_ref()
                .unwrap()
                .summary
                .address
                .clone()
                .unwrap(),
            fork.step
                .b
                .as_ref()
                .unwrap()
                .summary
                .address
                .clone()
                .unwrap(),
        ];
        for address in &raw_text_addresses {
            assert_eq!(
                full_view.full_text(address),
                Some(huge.as_str()),
                "address {address:?} must resolve to the full, untruncated payload"
            );
        }
        // Field-diff slots hold the value in its display form (compact JSON) — a JSON string
        // literal, quotes included — not the bare payload text.
        let quoted = format!("\"{huge}\"");
        for address in [
            fork.step.field_diffs[0]
                .removed
                .as_ref()
                .unwrap()
                .address
                .clone()
                .unwrap(),
            fork.step.field_diffs[0]
                .added
                .as_ref()
                .unwrap()
                .address
                .clone()
                .unwrap(),
        ] {
            assert_eq!(
                full_view.full_text(&address),
                Some(quoted.as_str()),
                "address {address:?} must resolve to the full, untruncated field value"
            );
        }
    }

    #[test]
    fn full_text_is_none_for_an_address_that_does_not_resolve() {
        let (a, b, res) = forked(0.47);
        let view = ViewModel::compute(&res, &a, &b);

        // Row out of range.
        assert_eq!(
            view.full_text(&SlotAddress {
                row: 99,
                kind: SlotKind::ForkSide { side: Side::A },
            }),
            None
        );
        // A step-row address asking for a fork-only slot.
        assert_eq!(
            view.full_text(&SlotAddress {
                row: 0,
                kind: SlotKind::ForkSide { side: Side::A },
            }),
            None
        );
        // A field path that was never in this row's diffs.
        assert_eq!(
            view.full_text(&SlotAddress {
                row: 2,
                kind: SlotKind::FieldRemoved {
                    path: "no-such-field".to_string(),
                },
            }),
            None
        );
    }

    #[test]
    fn envelope_backs_off_to_a_char_boundary() {
        // Two ASCII bytes then 4-byte chars: byte SLOT_TEXT_LIMIT lands mid-char, so the
        // cut must back off to the last boundary below it instead of panicking.
        let text = format!("ab{}", "🌲".repeat(SLOT_TEXT_LIMIT / 4));
        let a = run("good", Outcome::Pass, vec![step(0, "fetch", &text)]);
        let b = run("bad", Outcome::Fail, vec![step(0, "fetch", "small")]);
        let fork = Fork {
            index: 0,
            a_step: Some(0),
            b_step: Some(0),
            confidence: 0.9,
        };
        let res = result(&a, &b, vec![Move::sync(0, 0, 0.9, 0.1)], Some(fork));
        let doc = Document::new(ViewModel::compute(&res, &a, &b));

        let Some(Row::Fork(fork)) = doc.view.rows.first() else {
            panic!("one fork row");
        };
        assert!(fork.side_a.truncated);
        assert_eq!(fork.side_a.text.len(), SLOT_TEXT_LIMIT - 2);
        assert!(text.starts_with(&fork.side_a.text));
    }

    #[test]
    fn under_limit_slots_pass_through_unmarked() {
        let (a, b, res) = forked(0.47);
        let doc = Document::new(ViewModel::compute(&res, &a, &b));

        // Nothing in the standard fixture is near the limit: no slot is marked, and the
        // lean wire never mentions the marker at all.
        let json = serde_json::to_string(&doc).unwrap();
        assert!(!json.contains("truncated"));
        let Some(Row::Fork(fork)) = doc.view.rows.get(2) else {
            panic!("row 2 is the fork");
        };
        assert_eq!(fork.side_a, "census.gov page: population 8,443,000");
    }

    #[test]
    fn headers_idx_width_and_warnings_come_through() {
        let (a, b, mut res) = forked(0.47);
        res.warnings = vec![Warning {
            code: WarningCode::ContentAbsent,
            msg: "run b: step 3 carried no content".to_string(),
        }];
        let view = ViewModel::compute(&res, &a, &b);

        assert_eq!(view.run_a.role.label(), "reference");
        assert_eq!(view.run_b.role.label(), "observed");
        assert_eq!((view.run_a.n_steps, view.run_b.n_steps), (3, 4));
        assert_eq!(view.run_a.outcome, Some(Outcome::Pass));
        assert_eq!(view.idx_width, 2, "indices are at least two digits");
        assert_eq!(view.warnings.len(), 1);
    }
}