newt-tui 0.8.0

Newt-Agent TUI surfaces (ratatui): code mode + pilot mode
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
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
use super::*;
use crate::tabs::{TabAction, TabSet};
use newt_core::lifecycle::new_session_id;

/// Every backend shares one endpoint AND one model, so no route change ever
/// fires `refresh_backend`'s served-adoption probe — the tier stays
/// network-free while still exercising the real posture machinery.
fn cfg_with(names: &[&str]) -> newt_core::ResolvedConfig {
    newt_core::ResolvedConfig::unrequested(newt_core::Config {
        default_backend: names.first().map(|n| (*n).to_string()),
        backends: names
            .iter()
            .map(|name| newt_core::BackendConfig {
                name: (*name).to_string(),
                endpoint: "http://backend.test:1".to_string(),
                model: Some("m0".to_string()),
                kind: Some(newt_core::BackendKind::Openai),
                ..Default::default()
            })
            .collect(),
        ..Default::default()
    })
}

/// Owns every piece of live session state a switch touches, so a test can
/// drive `activate_tab` / `create_fresh_tab` / `adopt_conversation` /
/// `close_tab` exactly as `run_chat` does.
struct Harness {
    _root: tempfile::TempDir,
    _ws: tempfile::TempDir,
    store: newt_core::ConversationStore,
    persona_store: crate::PersonaStore,
    workspace: String,
    memory: newt_core::MemoryManager,
    system: String,
    active_persona: Option<crate::Persona>,
    active_conversation_id: String,
    compress_state: newt_core::CompressState,
    scratchpad: newt_core::SessionScratchpadStore,
    step_ledger: newt_core::SessionStepLedger,
    active_prompt_context: Option<newt_core::TurnPromptContext>,
    mode_states: crate::ConversationModeStates,
    baseline: crate::PreferenceBaseline,
    pending: newt_core::PreferenceActions,
    base_provider: Option<String>,
    base_model: Option<String>,
    cfg: newt_core::ResolvedConfig,
    choice: crate::BackendChoice,
    inf_url: String,
    inf_model: String,
    inf_kind: newt_core::BackendKind,
    inf_key: Option<String>,
    inf_context_window: Option<u32>,
    turns_this_conversation: usize,
    last_resume_listing: Vec<String>,
    active_roadmap_id: Option<String>,
    interrupted_objective: Option<newt_core::TurnPromptContext>,
    input_stash: String,
}

impl Harness {
    fn new(backends: &[&str]) -> (Self, TabSet) {
        let root = tempfile::tempdir().unwrap();
        let ws = tempfile::tempdir().unwrap();
        let store = newt_core::ConversationStore::new(root.path(), ws.path(), 100).unwrap();
        let cfg = cfg_with(backends);
        let choice = crate::resolve_backend_choice(&cfg).expect("test configs resolve");
        let first = newt_core::new_conversation_id();
        store.claim(&first).unwrap();
        let workspace = ws.path().to_string_lossy().into_owned();
        let memory = newt_core::MemoryManager::new();
        let system = String::new();
        let tabs = TabSet::new(new_session_id(), &first);
        (
            Self {
                _root: root,
                _ws: ws,
                store,
                persona_store: crate::PersonaStore::new(std::path::PathBuf::from("/nonexistent")),
                workspace,
                memory,
                system,
                active_persona: None,
                active_conversation_id: first,
                compress_state: newt_core::CompressState::new(),
                scratchpad: newt_core::SessionScratchpadStore::default(),
                step_ledger: newt_core::SessionStepLedger::default(),
                active_prompt_context: None,
                mode_states: crate::ConversationModeStates::default(),
                baseline: crate::PreferenceBaseline::snapshot(None, None),
                pending: newt_core::PreferenceActions::default(),
                base_provider: None,
                base_model: None,
                inf_url: choice.url.clone(),
                inf_model: choice.active_model.clone().unwrap_or_default(),
                inf_kind: choice.kind,
                inf_key: choice.api_key.clone(),
                inf_context_window: choice.context_window,
                choice,
                cfg,
                turns_this_conversation: 0,
                last_resume_listing: Vec::new(),
                active_roadmap_id: None,
                interrupted_objective: None,
                input_stash: String::new(),
            },
            tabs,
        )
    }

    fn ctx(&mut self) -> TabSwitchCtx<'_> {
        TabSwitchCtx {
            store: &self.store,
            persona_store: &self.persona_store,
            workspace: &self.workspace,
            memory: &mut self.memory,
            system: &mut self.system,
            active_persona: &mut self.active_persona,
            active_conversation_id: &mut self.active_conversation_id,
            compress_state: &mut self.compress_state,
            scratchpad: &self.scratchpad,
            step_ledger: &self.step_ledger,
            active_prompt_context: &mut self.active_prompt_context,
            mode_states: &self.mode_states,
            baseline: &self.baseline,
            pending: &mut self.pending,
            base_provider: &mut self.base_provider,
            base_model: &mut self.base_model,
            cfg: &self.cfg,
            choice: &mut self.choice,
            inf_url: &mut self.inf_url,
            inf_model: &mut self.inf_model,
            inf_kind: &mut self.inf_kind,
            inf_key: &mut self.inf_key,
            inf_context_window: &mut self.inf_context_window,
            turns_this_conversation: &mut self.turns_this_conversation,
            last_resume_listing: &mut self.last_resume_listing,
            active_roadmap_id: &mut self.active_roadmap_id,
            interrupted_objective: &mut self.interrupted_objective,
            input_stash: &mut self.input_stash,
            color: false,
            verbose: false,
        }
    }

    /// Open a second tab already holding `id`, **through the real
    /// transitions**: deactivate the outgoing tab first (so its state is
    /// stashed into ITS `TabState`), then open and hydrate.
    ///
    /// Calling `TabSet::open` directly skips the deactivate, so the
    /// outgoing tab's live state is stashed into the INCOMING tab — a
    /// fixture bug that silently invalidates every round-trip assertion.
    /// It cost me two red tests to notice, which is the argument for the
    /// helper.
    fn open_tab_on(&mut self, tabs: &mut TabSet, id: &str) {
        self.store.claim(id).unwrap();
        let mut ctx = self.ctx();
        ctx.deactivate(tabs);
        let (_, handoff) = tabs.open(new_session_id(), id);
        *ctx.active_conversation_id = id.to_string();
        let incoming =
            preflight(ctx.store, ctx.persona_store, id, None).expect("fixture row must preflight");
        ctx.commit_incoming(tabs, id, incoming);
        handoff.apply();
    }

    /// A durable conversation row (rows materialize on the first saved turn).
    fn durable(&self, title: &str) -> String {
        let id = self.store.create(title, None).unwrap();
        self.store.append_turn(&id, "q", "a").unwrap();
        id
    }

    /// Everything the ADR promises is restored exactly, as one comparable
    /// value — so a round-trip assertion cannot quietly omit a field.
    fn snapshot(&self, tabs: &TabSet) -> Snapshot {
        use newt_core::{ScratchpadStore, StepLedger};
        let scratchpad: Vec<(String, String)> = self.scratchpad.entries().into_iter().collect();
        Snapshot {
            conversation_id: self.active_conversation_id.clone(),
            inf_url: self.inf_url.clone(),
            inf_model: self.inf_model.clone(),
            inf_kind: self.inf_kind,
            inf_key_fingerprint: fingerprint(self.inf_key.as_deref()),
            inf_context_window: self.inf_context_window,
            choice_name: self.choice.name.clone(),
            provider: std::env::var("NEWT_PROVIDER").ok(),
            model: std::env::var("NEWT_DGX_MODEL").ok(),
            cognition: newt_core::cognition::cli_cognition(),
            tenacity: newt_core::tenacity::cli_tenacity(),
            initiative: newt_core::initiative::cli_initiative(),
            persona_cognition: newt_core::cognition::persona_cognition(),
            persona_initiative: newt_core::initiative::persona_initiative(),
            persona: self.active_persona.as_ref().map(|p| p.name.clone()),
            scratchpad,
            plan_steps: self.step_ledger.steps(),
            has_prompt_context: self.active_prompt_context.is_some(),
            system: self.system.clone(),
            turns: self.turns_this_conversation,
            roadmap: self.active_roadmap_id.clone(),
            resume_listing: self.last_resume_listing.clone(),
            input_stash: self.input_stash.clone(),
            degraded: tabs.active().pin_degraded.as_ref().map(|d| d.summary()),
        }
    }
}

/// The whole state surface a transition may touch.
///
/// Every field here is compared exactly. `inf_key` is represented by a
/// non-reversible fingerprint rather than its value, so a mismatch can be
/// DETECTED without a secret ever reaching a test log or a panic message —
/// an assertion that prints the API key on failure would be a worse bug
/// than the one it was written to catch.
#[derive(Debug, Clone, PartialEq)]
struct Snapshot {
    conversation_id: String,
    // backend quintet
    inf_url: String,
    inf_model: String,
    inf_kind: newt_core::BackendKind,
    inf_key_fingerprint: Option<u64>,
    inf_context_window: Option<u32>,
    choice_name: String,
    // projected dials + route env
    provider: Option<String>,
    model: Option<String>,
    cognition: newt_core::cognition::CognitionOverride,
    tenacity: Option<newt_core::Tenacity>,
    initiative: Option<newt_core::Initiative>,
    persona_cognition: Option<newt_core::role_profile::Cognition>,
    persona_initiative: Option<newt_core::Initiative>,
    // conversation-owned live state
    persona: Option<String>,
    scratchpad: Vec<(String, String)>,
    plan_steps: Vec<newt_core::Step>,
    has_prompt_context: bool,
    system: String,
    // sidecar + input
    turns: usize,
    roadmap: Option<String>,
    resume_listing: Vec<String>,
    input_stash: String,
    degraded: Option<String>,
}

/// Non-reversible, stable within a process — enough to prove "unchanged" or
/// "changed" without ever materializing the secret.
fn fingerprint(secret: Option<&str>) -> Option<u64> {
    use std::hash::{Hash, Hasher};
    secret.map(|s| {
        let mut h = std::collections::hash_map::DefaultHasher::new();
        s.hash(&mut h);
        h.finish()
    })
}

fn guard() -> newt_core::test_guard::GlobalSettingsGuard {
    newt_core::test_guard::GlobalSettingsGuard::acquire()
}

// ── 1. `/tab new` produces genuinely isolated state ───────────────────

/// Blocker 1. A fresh tab must not inherit conversation-shaped state from
/// the tab it was opened from. Minting an id and relabelling the tab would
/// leave the outgoing conversation's memory, plan, scratchpad and prompt
/// receipt in place under a new name.
#[test]
fn tab_new_produces_genuinely_isolated_state() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    // Dirty everything a conversation owns.
    {
        use newt_core::{ScratchpadStore, StepLedger};
        h.scratchpad.set("current_task", "tab A's task".into());
        h.step_ledger.restore(&newt_core::PlanSnapshot::default());
        assert!(h.scratchpad.get("current_task").is_some());
    }
    h.turns_this_conversation = 9;
    h.active_roadmap_id = Some("road-a".into());
    h.interrupted_objective = None;
    let outgoing = h.active_conversation_id.clone();

    let mut ctx = h.ctx();
    let _ = create_fresh_tab(&mut ctx, &mut tabs).expect("a brand-new id always claims");

    assert_ne!(h.active_conversation_id, outgoing, "a NEW conversation");
    assert_eq!(tabs.len(), 2);
    assert_eq!(tabs.active().conversation_id(), h.active_conversation_id);
    {
        use newt_core::ScratchpadStore;
        assert!(
            h.scratchpad.get("current_task").is_none(),
            "a fresh tab must not inherit the outgoing conversation's scratchpad"
        );
    }
    assert_eq!(h.turns_this_conversation, 0, "fresh turn count");
    assert_eq!(h.active_roadmap_id, None, "fresh roadmap binding");
    assert!(h.active_prompt_context.is_none(), "fresh prompt receipt");
    // `/tab new` deliberately does NOT opt the session out of auto-resume
    // the way `/new` does: it does not abandon the resumed conversation —
    // that one is still open in its own tab — so next launch's auto-resume
    // is none of this command's business. The switch machinery therefore
    // never touches that flag, which is why it is not in `TabSwitchCtx`.
}

// ── 2. switching back to a never-used fresh tab works ─────────────────

/// Blocker 1's edge case, verbatim: `startup / tab new / tab 1 / tab 2`.
///
/// Tab 2 has never been prompted, so its conversation is **claimed but has
/// no row** — rows materialize on the first saved turn. Activation must not
/// assume a row exists.
#[test]
fn startup_then_tab_new_then_tab_1_then_tab_2() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let tab1_conversation = h.active_conversation_id.clone();

    {
        let mut ctx = h.ctx();
        let _ = create_fresh_tab(&mut ctx, &mut tabs).unwrap();
    }
    let tab2_conversation = h.active_conversation_id.clone();
    assert!(
        !h.store.exists(&tab2_conversation).unwrap(),
        "fixture precondition: the fresh tab has no materialized row"
    );

    // /tab 1
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).expect("/tab 1");
    }
    assert_eq!(h.active_conversation_id, tab1_conversation);

    // /tab 2 — the step that used to fail
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 1)
            .expect("/tab 2 must work even though tab 2 has no conversation row yet");
    }
    assert_eq!(h.active_conversation_id, tab2_conversation);
    assert_eq!(tabs.active_index(), 1);
}

// ── P0-2: the claimed-but-unmaterialized interval ─────────────────────

fn persona_named(name: &str) -> crate::Persona {
    crate::test_persona(name, "be helpful", std::path::PathBuf::from("/dev/null"))
}

/// A fresh tab owns its persona rather than borrowing the session's.
///
/// Create B while persona **P** is active, select **Q** in A, then return
/// to still-rowless B: B must be back on P.
/// Before the seed, the `Fresh` arm restored no persona at all, so B
/// silently ran under Q — and would have been STAMPED with Q at its first
/// prompt, permanently, since the store has no persona UPDATE path.
#[test]
fn a_rowless_tab_keeps_its_own_persona_across_a_visit_to_another() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let dir = h._root.path().join("personas");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("p.md"), "Be helpful as persona P.").unwrap();
    std::fs::write(dir.join("q.md"), "Be helpful as persona Q.").unwrap();
    h.persona_store = crate::PersonaStore::new(dir);
    let p = h.persona_store.load("p").unwrap();
    let q = h.persona_store.load("q").unwrap();
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();

    // P is active when B is created.
    h.active_persona = Some(p.clone());
    {
        let mut ctx = h.ctx();
        let _ = create_fresh_tab(&mut ctx, &mut tabs).unwrap();
    }
    let b = h.active_conversation_id.clone();
    assert!(!h.store.exists(&b).unwrap(), "B is rowless");
    assert_eq!(
        h.active_persona,
        Some(p.clone()),
        "a fresh tab keeps the persona active when it was opened, as /new does"
    );

    // Visit A: its later selection of P survives even though its birth had
    // no persona. Then explicitly select Q, as an operator could with
    // `/persona set q --keep-context`, before returning to B.
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    assert_eq!(h.active_persona, Some(p.clone()));
    h.active_persona = Some(q);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 1).unwrap();
    }
    assert_eq!(
        h.active_persona,
        Some(p),
        "returning to the rowless tab restores ITS persona, not the other tab's"
    );
    assert!(
        !h.store.exists(&b).unwrap(),
        "and visiting a tab still creates no ghost /resume row"
    );
}

/// Regression (slice 1b): a fresh tab re-seats its persona's INITIATIVE, not
/// only its cognition. The Fresh arm re-seated persona cognition alone, so
/// the outgoing tab's persona tenacity (now initiative) stayed installed in
/// the incoming tab.
#[test]
fn a_fresh_tab_reseats_its_personas_initiative() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let dir = h._root.path().join("personas");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("eager.md"),
        "+++\ninitiative = \"eager\"\n+++\n\nAct early.",
    )
    .unwrap();
    std::fs::write(dir.join("calm.md"), "Take your time.").unwrap();
    h.persona_store = crate::PersonaStore::new(dir);
    let eager = h.persona_store.load("eager").unwrap();
    let calm = h.persona_store.load("calm").unwrap();
    assert_eq!(eager.profile.initiative, Some(newt_core::Initiative::Eager));
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();

    // B opens under `eager`.
    h.active_persona = Some(eager.clone());
    crate::seat_persona_dials(Some(&eager));
    {
        let mut ctx = h.ctx();
        let _ = create_fresh_tab(&mut ctx, &mut tabs).unwrap();
    }
    // Back in A, the operator activates `calm`, which declares no initiative.
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    h.active_persona = Some(calm.clone());
    crate::seat_persona_dials(Some(&calm));
    assert_eq!(newt_core::initiative::persona_initiative(), None);

    // Returning to rowless B re-seats B's persona and its initiative.
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 1).unwrap();
    }
    assert_eq!(
        h.active_persona.as_ref().map(|p| p.name.as_str()),
        Some("eager")
    );
    assert_eq!(
        newt_core::initiative::persona_initiative(),
        Some(newt_core::Initiative::Eager),
        "the fresh tab's persona initiative is back in force"
    );
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    assert_eq!(
        newt_core::initiative::persona_initiative(),
        None,
        "and does not leak into a tab without it"
    );
}

/// Renaming an INACTIVE rowless tab materializes its row — and must stamp
/// that tab's persona, not whatever is active in the tab doing the renaming.
#[test]
fn renaming_an_inactive_rowless_tab_does_not_capture_the_live_persona() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();

    // B is created with NO persona.
    h.active_persona = None;
    {
        let mut ctx = h.ctx();
        let _ = create_fresh_tab(&mut ctx, &mut tabs).unwrap();
    }
    let b = h.active_conversation_id.clone();
    // Back to A, and make Q active there.
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    h.active_persona = Some(persona_named("Q"));

    // Rename the inactive rowless tab B from here.
    {
        let mut ctx = h.ctx();
        handle_tab_action(
            TabAction::Rename {
                index: Some(1),
                title: "B titled".into(),
            },
            &mut ctx,
            &mut tabs,
        );
    }
    assert!(h.store.exists(&b).unwrap(), "rename materialized B's row");
    let record = h.store.load(&b).unwrap();
    assert_eq!(
        record.persona, None,
        "B was created with no persona; renaming it from a Q tab must not stamp Q"
    );
    assert_eq!(record.title, "B titled");
    assert!(
        tabs.get(1).unwrap().fresh_seed.is_none(),
        "the seed is consumed once the row exists"
    );
}

/// A preference change made in a rowless tab survives a switch away and
/// back. `persist_preference_actions` cannot write it (no row) and the
/// overlay zeroes `pending` on every switch, so without the seed it was
/// silently discarded by the next `/tab`.
#[test]
fn a_preference_change_in_a_rowless_tab_survives_a_switch() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol", "other"]);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();
    {
        let mut ctx = h.ctx();
        let _ = create_fresh_tab(&mut ctx, &mut tabs).unwrap();
    }
    let b = h.active_conversation_id.clone();

    // Operator picks a backend in the rowless tab.
    newt_core::runtime::mark_backend_pick("other");
    {
        let mut ctx = h.ctx();
        *ctx.pending = newt_core::runtime::drain_preference_actions();
        activate_tab(&mut ctx, &mut tabs, 0).expect("switch away");
    }
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 1).expect("switch back");
    }
    assert!(
        !h.pending.is_empty(),
        "the rowless tab's unwritten preference action came back with it"
    );
    assert!(!h.store.exists(&b).unwrap(), "still no ghost row");

    // And once the row materializes, the held action lands on it.
    h.store.create_with_id(&b, "B", None).unwrap();
    crate::persist_preference_actions(
        Some(&h.store),
        &b,
        &mut h.pending,
        &mut h.base_provider,
        &mut h.base_model,
    )
    .unwrap();
    assert_eq!(
        h.store.preference_pin(&b).unwrap().and_then(|p| p.backend),
        Some("other".to_string()),
        "the first durable write materializes the preference chosen while rowless"
    );
}

/// The seed's LIFETIME, which was previously only an argument: once the row
/// materializes, the seed is dropped and can never re-apply stale state.
///
/// The hazard it rules out: a tab whose row appeared (first prompt, or a
/// rename) still carrying a seed would, on its next activation, overwrite
/// the persona the store now owns with the one captured at `/tab new`.
/// Since `persona` is write-once at row birth, a stale re-apply would
/// disagree with the durable record permanently.
#[test]
fn the_seed_is_dropped_once_the_row_materializes_and_cannot_re_apply() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let dir = h._root.path().join("personas");
    std::fs::create_dir_all(&dir).unwrap();
    h.persona_store = crate::PersonaStore::new(&dir);
    for (name, prompt) in [
        ("seeded", "The persona captured before the first turn."),
        (
            "durable",
            "The persona selected before the row materializes.",
        ),
    ] {
        std::fs::write(dir.join(format!("{name}.md")), prompt).unwrap();
    }
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();

    h.active_persona = Some(h.persona_store.load("seeded").unwrap());
    {
        let mut ctx = h.ctx();
        let _ = create_fresh_tab(&mut ctx, &mut tabs).unwrap();
    }
    let b = h.active_conversation_id.clone();
    assert!(tabs.active().fresh_seed.is_some(), "rowless: seed present");

    // The row materializes with a DIFFERENT persona than the seed captured
    // — as it would if the operator switched persona before the first turn.
    // Real row birth stamps the live selection; do not invent a mismatch
    // between that selection and the newly written conversation metadata.
    let durable = h.persona_store.load("durable").unwrap();
    h.active_persona = Some(durable.clone());
    h.store.create_with_id(&b, "B", Some("durable")).unwrap();

    // Any switch away deactivates, which is where the seed is retired.
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    assert!(
        tabs.get(1).unwrap().fresh_seed.is_none(),
        "the seed is retired the moment the row exists"
    );

    // Coming back reads the STORE, not the stale seed.
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 1).unwrap();
    }
    assert_eq!(
        h.active_persona,
        Some(durable),
        "restore must use the current selected persona, not resurrect the stale seed"
    );
    assert!(tabs.active().fresh_seed.is_none());
}

/// `/tab new` alone still creates no `/resume`-visible row — the rule the
/// seed exists to preserve rather than work around.
#[test]
fn tab_new_alone_creates_no_ghost_resume_row() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let before = h.store.list().map(|v| v.len()).unwrap_or(0);
    {
        let mut ctx = h.ctx();
        let _ = create_fresh_tab(&mut ctx, &mut tabs).unwrap();
        let _ = create_fresh_tab(&mut ctx, &mut tabs).unwrap();
    }
    assert_eq!(
        h.store.list().map(|v| v.len()).unwrap_or(0),
        before,
        "two fresh tabs, zero new rows in the resume listing"
    );
}

// ── 3. A -> B -> A exact restoration ──────────────────────────────────

/// The ADR's round-trip property, over every field the contract promises —
/// compared as one struct so a field cannot be silently omitted.
#[test]
fn a_to_b_to_a_restores_a_exactly() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol", "other"]);
    let a_conversation = h.active_conversation_id.clone();
    h.store.create_with_id(&a_conversation, "A", None).unwrap();
    let b_conversation = h.durable("B");

    h.open_tab_on(&mut tabs, &b_conversation);
    // Back to A and hydrate it once, so the baseline snapshot is taken of a
    // tab that has actually been activated — not of a half-built fixture.
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).expect("settle on A");
    }
    h.turns_this_conversation = 4;
    h.active_roadmap_id = Some("road-a".into());
    h.input_stash = "half typed in A".into();
    let a_before = h.snapshot(&tabs);

    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 1).expect("A→B");
    }
    h.turns_this_conversation = 77;
    h.active_roadmap_id = Some("road-b".into());
    h.input_stash = "half typed in B".into();

    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).expect("B→A");
    }
    assert_eq!(
        h.snapshot(&tabs),
        a_before,
        "A must come back exactly as it was left"
    );
    assert_eq!(h.active_conversation_id, a_conversation);
}

// ── 4. no cross-tab leakage of dials / pins ───────────────────────────

/// Unpinned baseline semantics: an unpinned tab must resolve to the
/// invocation baseline, never to whatever the previous tab pinned.
#[test]
fn an_unpinned_tab_does_not_inherit_another_tabs_pin() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol", "other"]);
    let unpinned = h.active_conversation_id.clone();

    // B is pinned to `other` with a dial.
    let pinned = h.durable("pinned");
    h.store.claim(&pinned).unwrap();
    h.store
        .update_preference_pin(
            &pinned,
            &newt_core::OperatorPreferencePin {
                backend: Some("other".into()),
                tenacity: Some(newt_core::Tenacity::Relentless),
                ..Default::default()
            },
        )
        .unwrap();
    h.open_tab_on(&mut tabs, &pinned);
    // Settle on the unpinned tab first, so activating the pinned one is a
    // real switch rather than a no-op on the already-active tab.
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).expect("settle on the unpinned tab");
        activate_tab(&mut ctx, &mut tabs, 1).expect("activate the pinned tab");
    }
    assert_eq!(
        std::env::var("NEWT_PROVIDER").ok().as_deref(),
        Some("other"),
        "the pinned tab routes to its pin"
    );
    assert_eq!(
        newt_core::tenacity::cli_tenacity(),
        Some(newt_core::Tenacity::Relentless)
    );

    // Back to the UNPINNED tab: baseline, not B's pin.
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).expect("back to the unpinned tab");
    }
    assert_eq!(h.active_conversation_id, unpinned);
    assert!(
        std::env::var("NEWT_PROVIDER").is_err(),
        "an unpinned tab resolves to the baseline, never the other tab's backend"
    );
    assert_eq!(
        newt_core::tenacity::cli_tenacity(),
        None,
        "and never the other tab's dials"
    );
}

/// Dial change → immediate switch → return restores the change.
#[test]
fn a_dial_change_survives_a_switch_away_and_back() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol", "other"]);
    let a = h.active_conversation_id.clone();
    // A durable row so A's flush has somewhere to land.
    h.store.create_with_id(&a, "A", None).unwrap();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 1).unwrap();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }

    // Operator turns a dial on A, then leaves immediately.
    newt_core::runtime::mark_tenacity_choice(Some(newt_core::Tenacity::Relentless));
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 1).expect("switch away");
    }
    assert_eq!(
        newt_core::tenacity::cli_tenacity(),
        None,
        "B is unpinned, so it shows the baseline — not A's change"
    );
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).expect("switch back");
    }
    assert_eq!(
        newt_core::tenacity::cli_tenacity(),
        Some(newt_core::Tenacity::Relentless),
        "the dial change was flushed on deactivation and comes back with A"
    );
}

/// The ADR's #1668 contract test: **two tabs with DIFFERENT pins**.
///
/// The unpinned-vs-pinned case above proves a tab does not inherit; this
/// proves the stronger thing — two tabs each carrying their own pin swap
/// the whole route quintet and both dials cleanly, in both directions, with
/// no residue from the other.
#[test]
fn two_tabs_with_different_pins_swap_cleanly_in_both_directions() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol", "other"]);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();
    h.store
        .update_preference_pin(
            &a,
            &newt_core::OperatorPreferencePin {
                backend: Some("sol".into()),
                tenacity: Some(newt_core::Tenacity::Relentless),
                ..Default::default()
            },
        )
        .unwrap();
    let b = h.durable("B");
    h.store
        .update_preference_pin(
            &b,
            &newt_core::OperatorPreferencePin {
                backend: Some("other".into()),
                cognition: Some("meticulous".into()),
                ..Default::default()
            },
        )
        .unwrap();
    h.open_tab_on(&mut tabs, &b);

    let posture = |h: &Harness| {
        (
            std::env::var("NEWT_PROVIDER").ok(),
            h.choice.name.clone(),
            h.inf_url.clone(),
            h.inf_model.clone(),
            h.inf_kind,
            newt_core::cognition::cli_cognition(),
            newt_core::tenacity::cli_tenacity(),
        )
    };

    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    let on_a = posture(&h);
    assert_eq!(on_a.0.as_deref(), Some("sol"));
    assert_eq!(on_a.6, Some(newt_core::Tenacity::Relentless));
    assert_eq!(
        newt_core::cognition::cli_cognition(),
        newt_core::cognition::CognitionOverride::Unset,
        "A pins no cognition, so it must show the baseline — not B's"
    );

    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 1).unwrap();
    }
    let on_b = posture(&h);
    assert_eq!(on_b.0.as_deref(), Some("other"));
    assert_eq!(
        on_b.6, None,
        "B pins no tenacity, so A's Relentless must NOT survive the switch"
    );

    // And back — history-independent, so A's posture is byte-identical.
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    assert_eq!(
        posture(&h),
        on_a,
        "A→B→A restores A's whole posture exactly"
    );
}

/// The outgoing tab keeps its claim across a switch — that is what makes it
/// a tab rather than a replaced conversation. Only close and exit release.
#[test]
fn the_outgoing_tabs_claim_is_held_across_a_switch() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
        activate_tab(&mut ctx, &mut tabs, 1).unwrap();
    }
    // Both conversations are still this session's, and both tabs still name
    // them — a switch released nothing.
    let mut held = tabs.claimed_conversations();
    held.sort_unstable();
    let mut expected = vec![a.as_str(), b.as_str()];
    expected.sort_unstable();
    assert_eq!(held, expected, "both claims survive the switch");
}

/// Close is release-WITHOUT-end: the conversation stays open and resumable.
#[test]
fn closing_a_tab_leaves_its_conversation_resumable() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
        close_tab(&mut ctx, &mut tabs, 1).unwrap();
    }
    assert!(
        h.store.exists(&b).unwrap(),
        "close must not end the conversation — /end is that verb"
    );
    // Released, so it can be claimed and resumed again.
    assert!(matches!(
        h.store.claim(&b).unwrap(),
        newt_core::ClaimOutcome::Claimed
    ));
    assert!(
        tabs.find_by_conversation(&b).is_none(),
        "and no tab still names it"
    );
}

// ── 5-7. duplicate conversations are impossible ───────────────────────

/// Blocker 2, front door one: `/resume`'s target.
#[test]
fn resume_of_a_conversation_open_elsewhere_activates_that_tab() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let a = h.active_conversation_id.clone();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }

    let adopted = {
        let mut ctx = h.ctx();
        adopt_conversation(&mut ctx, &mut tabs, &b).unwrap()
    };
    assert!(
        matches!(adopted, Adopted::ActivatedExistingTab { index: 1, .. }),
        "got {adopted:?}"
    );
    assert_eq!(h.active_conversation_id, b);
    assert_eq!(tabs.len(), 2, "no second tab was opened for the same row");
    assert_eq!(h.active_conversation_id, tabs.active().conversation_id());
    assert_ne!(a, b);
}

/// Blocker 2, front door two: the same conversation reached through the
/// roadmap/`/conversation restore` path. Both call the same seam, so this
/// proves the invariant is a property of the SEAM, not of one command.
#[test]
fn a_second_front_door_also_activates_rather_than_duplicating() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    // Whatever the caller is, it asks the seam.
    for _ in 0..2 {
        let adopted = {
            let mut ctx = h.ctx();
            adopt_conversation(&mut ctx, &mut tabs, &b).unwrap()
        };
        assert!(matches!(
            adopted,
            Adopted::ActivatedExistingTab { .. } | Adopted::AlreadyHere
        ));
    }
    assert_eq!(tabs.len(), 2);
}

/// The invariant itself: no two tabs may name the same conversation.
///
/// Note this cannot be delegated to the store — `claim` returns `Claimed`
/// for a re-affirmation by the SAME process, so a second tab would be told
/// its duplicate claim succeeded.
#[test]
fn two_tabs_can_never_hold_the_same_conversation() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let shared = h.durable("shared");
    // The store happily re-affirms our own claim — this is the trap.
    assert!(matches!(
        h.store.claim(&shared).unwrap(),
        newt_core::ClaimOutcome::Claimed
    ));
    assert!(matches!(
        h.store.claim(&shared).unwrap(),
        newt_core::ClaimOutcome::Claimed
    ));

    h.open_tab_on(&mut tabs, &shared);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    let adopted = {
        let mut ctx = h.ctx();
        adopt_conversation(&mut ctx, &mut tabs, &shared).unwrap()
    };
    assert!(matches!(adopted, Adopted::ActivatedExistingTab { .. }));

    let mut ids: Vec<&str> = tabs.claimed_conversations();
    ids.sort_unstable();
    let before = ids.len();
    ids.dedup();
    assert_eq!(
        ids.len(),
        before,
        "every open tab names a DISTINCT conversation"
    );
}

// ── 8-10. failure containment ─────────────────────────────────────────

/// Stage-0 failure is non-mutating: a tab whose conversation cannot be
/// preflighted leaves the session exactly as it was.
#[test]
fn a_failed_activation_leaves_the_current_tab_untouched() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    h.input_stash = "typed in A".into();
    h.turns_this_conversation = 3;
    let before = h.snapshot(&tabs);
    let active_before = tabs.active_index();
    let owner_before = newt_core::lifecycle::active_session();

    // An out-of-range target is refused at Stage 0, before anything moves.
    let err = {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 9).unwrap_err()
    };
    assert!(matches!(err, TabError::OutOfRange { .. }));
    assert_eq!(
        h.snapshot(&tabs),
        before,
        "a refused switch mutates nothing"
    );
    assert_eq!(tabs.active_index(), active_before);
    assert_eq!(newt_core::lifecycle::active_session(), owner_before);
}

/// **P0 — Stage 0 is a transaction, not an ordering.**
///
/// The row `load()`s cleanly and a LATER validation — the prompt receipt's
/// context — fails. Under the previous shape, preflight proved only
/// `exists + load`, so this failure surfaced INSIDE the restore, after the
/// outgoing tab had been deactivated and the active pointer moved; the
/// hydrate then logged a warning and carried on, leaving the session with
/// one conversation's memory under another's identity.
///
/// Asserts the whole state surface is byte-identical: active index,
/// lifecycle owner, conversation id, claims, memory/system, persona,
/// scratchpad, plan, prompt context, the backend quintet, projected dials,
/// sidecar, and input.
#[test]
fn a_late_validation_failure_leaves_the_session_completely_untouched() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol", "other"]);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).expect("settle on A");
    }
    // Give A a full, distinguishable live state.
    {
        use newt_core::ScratchpadStore;
        h.scratchpad.set("current_task", "A's task".into());
    }
    h.turns_this_conversation = 6;
    h.active_roadmap_id = Some("road-a".into());
    h.last_resume_listing = vec!["row-1".into()];
    h.input_stash = "half typed in A".into();

    let before = h.snapshot(&tabs);
    let active_before = tabs.active_index();
    let owner_before = newt_core::lifecycle::active_session();
    let claims_before = {
        let mut c = tabs.claimed_conversations();
        c.sort_unstable();
        c.iter().map(|s| s.to_string()).collect::<Vec<_>>()
    };
    // The row loads; the receipt context does not validate.
    assert!(h.store.exists(&b).unwrap(), "B's row exists and loads");
    crate::restore_prepare_seam::fail_after_load_for(&b);

    let err = {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 1).unwrap_err()
    };
    crate::restore_prepare_seam::clear();

    assert!(
        matches!(err, TabError::PreflightFailed { .. }),
        "a late validation failure must abort at Stage 0, got {err:?}"
    );
    assert_eq!(
        h.snapshot(&tabs),
        before,
        "no field of the live session may change on a refused switch"
    );
    assert_eq!(tabs.active_index(), active_before, "active tab unchanged");
    assert_eq!(
        newt_core::lifecycle::active_session(),
        owner_before,
        "lifecycle ownership did not move"
    );
    let mut claims_after = tabs.claimed_conversations();
    claims_after.sort_unstable();
    assert_eq!(
        claims_after
            .iter()
            .map(|s| s.to_string())
            .collect::<Vec<_>>(),
        claims_before,
        "no claim was taken or released"
    );
    // And the session is still usable: switching to a HEALTHY tab works.
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).expect("A is still activatable");
    }
}

/// The same failure reached through the ADOPTION seam rather than `/tab <n>`,
/// because a transaction that only holds for one front door is not a
/// transaction.
#[test]
fn a_late_validation_failure_through_adoption_also_changes_nothing() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    let before = h.snapshot(&tabs);
    let owner_before = newt_core::lifecycle::active_session();

    crate::restore_prepare_seam::fail_after_load_for(&b);
    let outcome = {
        let mut ctx = h.ctx();
        adopt_conversation(&mut ctx, &mut tabs, &b)
    };
    crate::restore_prepare_seam::clear();

    assert!(outcome.is_err(), "adoption must propagate the abort");
    assert_eq!(h.snapshot(&tabs), before);
    assert_eq!(newt_core::lifecycle::active_session(), owner_before);
    assert_eq!(tabs.active_index(), 0);
}

/// Closing the ACTIVE tab activates the neighbor BEFORE the closing tab's
/// claim is released — never the other way round.
#[test]
fn closing_the_active_tab_activates_the_neighbor_before_releasing() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let a = h.active_conversation_id.clone();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    // active = B (index 1); close it.
    let closed = {
        let mut ctx = h.ctx();
        close_tab(&mut ctx, &mut tabs, 1).expect("close the active tab")
    };
    assert_eq!(closed.tab.conversation_id(), b);
    assert_eq!(tabs.len(), 1);
    assert_eq!(
        h.active_conversation_id, a,
        "the neighbor is live before anything is released"
    );
    assert_eq!(
        newt_core::lifecycle::active_session().as_deref(),
        Some(tabs.active().session_id().as_str()),
        "ownership names a tab that is still open"
    );
    // Release-without-end: the conversation is still resumable.
    assert!(
        h.store.exists(&b).unwrap(),
        "closing a tab must not end its conversation"
    );
}

/// Blocker 3, the load-bearing case: if the NEIGHBOR cannot be activated,
/// closing the active tab must leave the session operational on the tab the
/// operator tried to close — not half-torn-down between the two.
///
/// Before the transactional rewrite, close removed the tab from the set and
/// *then* hydrated the neighbor, so this failure left the closed tab gone,
/// the neighbor partially hydrated, and ownership already transferred.
#[test]
fn a_failed_neighbor_activation_leaves_the_closing_tab_intact() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    // Land on B (index 1) — the tab we will try to close.
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 1).unwrap();
    }
    h.input_stash = "typed in B".into();
    h.turns_this_conversation = 5;
    let before = h.snapshot(&tabs);
    let owner_before = newt_core::lifecycle::active_session();

    // A (the neighbor) becomes unactivatable.
    test_seam::fail_preflight_for(&a);
    let err = {
        let mut ctx = h.ctx();
        close_tab(&mut ctx, &mut tabs, 1).unwrap_err()
    };
    test_seam::clear();

    assert!(matches!(err, TabError::PreflightFailed { .. }), "{err:?}");
    assert_eq!(tabs.len(), 2, "nothing was removed");
    assert_eq!(tabs.active_index(), 1, "B is still the active tab");
    assert_eq!(h.snapshot(&tabs), before, "B's live state is untouched");
    assert_eq!(
        newt_core::lifecycle::active_session(),
        owner_before,
        "ownership did not transfer on a failed close"
    );
    assert!(
        h.store.exists(&b).unwrap(),
        "and B's conversation was never released or ended"
    );
}

/// Closing one tab must not release a claim another tab still needs.
#[test]
fn closing_one_tab_cannot_release_another_tabs_claim() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let a = h.active_conversation_id.clone();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    // Close the INACTIVE tab B while A is live.
    {
        let mut ctx = h.ctx();
        close_tab(&mut ctx, &mut tabs, 1).unwrap();
    }
    assert_eq!(tabs.claimed_conversations(), vec![a.as_str()]);
    // A's claim is intact: re-claiming it still succeeds for this process
    // and no other tab lost anything.
    assert!(matches!(
        h.store.claim(&a).unwrap(),
        newt_core::ClaimOutcome::Claimed
    ));
}

// ── 11-12. pin failure is explicit and refuses turns ──────────────────

/// Blocker 4. A tab pinned to a backend this process cannot resolve lands
/// at baseline, is marked degraded, and the marker retains the pin so a
/// retry is possible.
#[test]
fn an_unestablishable_pin_degrades_the_tab_instead_of_running_at_baseline() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let b = h.durable("B");
    h.store.claim(&b).unwrap();
    h.store
        .update_preference_pin(
            &b,
            &newt_core::OperatorPreferencePin {
                // Not in `cfg.backends` — the config no longer defines it.
                backend: Some("a-backend-that-is-gone".into()),
                ..Default::default()
            },
        )
        .unwrap();
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }

    let switched = {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 1).expect("activation itself succeeds")
    };
    let degraded = switched
        .degraded
        .expect("a pin that cannot be established must degrade the tab");
    assert!(
        degraded.summary().starts_with("!pin"),
        "visible marker: {}",
        degraded.summary()
    );
    assert_eq!(
        degraded.pin.backend.as_deref(),
        Some("a-backend-that-is-gone"),
        "the pin is retained so a retry has something to retry"
    );
    assert_eq!(
        tabs.active().pin_degraded.as_ref().map(|d| d.summary()),
        Some(degraded.summary()),
        "the tab carries the degraded state, which is what refuses turns"
    );
    assert!(
        std::env::var("NEWT_PROVIDER").is_err(),
        "and the session sits at a KNOWN baseline, not a half-applied pin"
    );
}

/// The retry path: once the backend exists again, `/tab retry` clears it.
#[test]
fn a_degraded_tab_can_retry_once_the_pin_is_satisfiable() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let b = h.durable("B");
    h.store.claim(&b).unwrap();
    h.store
        .update_preference_pin(
            &b,
            &newt_core::OperatorPreferencePin {
                backend: Some("later".into()),
                ..Default::default()
            },
        )
        .unwrap();
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
        activate_tab(&mut ctx, &mut tabs, 1).unwrap();
    }
    assert!(tabs.active().pin_degraded.is_some());

    // The operator adds the backend the pin names, then retries.
    h.cfg = cfg_with(&["sol", "later"]);
    {
        let mut ctx = h.ctx();
        handle_tab_action(TabAction::Retry, &mut ctx, &mut tabs);
    }
    assert!(
        tabs.active().pin_degraded.is_none(),
        "a satisfiable pin clears the degraded state"
    );
    assert_eq!(
        std::env::var("NEWT_PROVIDER").ok().as_deref(),
        Some("later"),
        "and the pin is now actually in force"
    );
}

// ── P1: transition results and degraded visibility ───────────────────

/// P1-3. A tab pinned to endpoint X, then `/tab new` onto the baseline
/// endpoint Y, is an ENDPOINT CHANGE. `create_fresh_tab` discarded its
/// `PinRestore`, so `/tab new` reported `url_changed = false` and telemetry
/// kept pointing at the box the previous tab was talking to.
/// Runs on a runtime because a REAL endpoint change is what we are proving,
/// and `refresh_backend` fires its served-adoption probe on one — that probe
/// is the "normal reprobe path" the brief asks this to exercise. The hosts
/// are unresolvable, so it fails fast without touching a network.
#[tokio::test(flavor = "multi_thread")]
async fn tab_new_from_a_pinned_tab_reports_the_endpoint_change() {
    let _g = guard();
    // Two DIFFERENT endpoints, so a route change is a real url change.
    let mut base = cfg_with(&["sol", "other"]).into_config();
    base.backends[1].endpoint = "http://elsewhere.test:2".to_string();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    h.cfg = newt_core::ResolvedConfig::unrequested(base);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();
    h.store
        .update_preference_pin(
            &a,
            &newt_core::OperatorPreferencePin {
                backend: Some("other".into()),
                ..Default::default()
            },
        )
        .unwrap();
    // Land on A so its pin is in force at endpoint Y.
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    assert_eq!(h.inf_url, "http://elsewhere.test:2", "A is pinned away");

    // `/tab new` returns to the baseline endpoint — that IS a url change.
    let outcome = {
        let mut ctx = h.ctx();
        create_fresh_tab(&mut ctx, &mut tabs).unwrap()
    };
    assert_eq!(
        h.inf_url, "http://backend.test:1",
        "fresh tab is at baseline"
    );
    assert!(
        outcome.url_changed,
        "a fresh tab that moves the endpoint must report it so telemetry re-probes"
    );
}

/// P1-4. Adopting an already-open DEGRADED tab must report `!pin`
/// immediately — the operator must not first learn of it from a refused
/// turn.
#[test]
fn adopting_a_degraded_tab_reports_the_degradation_in_its_outcome() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();
    let b = h.durable("B");
    h.store
        .update_preference_pin(
            &b,
            &newt_core::OperatorPreferencePin {
                backend: Some("a-backend-that-is-gone".into()),
                ..Default::default()
            },
        )
        .unwrap();
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }

    let adopted = {
        let mut ctx = h.ctx();
        adopt_conversation(&mut ctx, &mut tabs, &b).unwrap()
    };
    match adopted {
        Adopted::ActivatedExistingTab { index, outcome } => {
            assert_eq!(index, 1);
            let d = outcome
                .degraded
                .expect("adoption must carry the degradation, not drop it");
            assert!(d.summary().starts_with("!pin"), "{}", d.summary());
        }
        other => panic!("expected an activation, got {other:?}"),
    }
    assert!(
        tabs.active().pin_degraded.is_some(),
        "and the tab itself is marked, which is what refuses turns"
    );
}

/// P1-4. Closing into a degraded NEIGHBOR reports it too.
#[test]
fn closing_into_a_degraded_neighbor_reports_the_degradation() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();
    h.store
        .update_preference_pin(
            &a,
            &newt_core::OperatorPreferencePin {
                backend: Some("also-gone".into()),
                ..Default::default()
            },
        )
        .unwrap();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    // active = B (index 1); close it, landing on the degraded A.
    let closed = {
        let mut ctx = h.ctx();
        close_tab(&mut ctx, &mut tabs, 1).unwrap()
    };
    assert_eq!(closed.tab.conversation_id(), b);
    let d = closed
        .outcome
        .degraded
        .expect("close must carry the neighbor's degradation");
    assert!(d.summary().starts_with("!pin"), "{}", d.summary());
    assert!(tabs.active().pin_degraded.is_some());
}

// ── ADR slice tests the audit found missing or vacuous ────────────────

/// S7 — exit flushes the active tab AND releases every claim.
///
/// The flush half did not exist: exit released claims but never deactivated
/// the active tab, so a `/model` or `/psyche` change made after the last
/// turn was dropped on the way out. Every other way of leaving a tab
/// flushes; leaving newt did not.
#[test]
fn exit_flushes_the_active_tab_and_releases_every_claim() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol", "other"]);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).unwrap();
    }
    // An operator choice made after the last turn, not yet written.
    newt_core::runtime::mark_backend_pick("other");
    h.pending = newt_core::runtime::drain_preference_actions();
    assert!(!h.pending.is_empty(), "fixture: an unwritten action exists");

    let released = {
        let mut ctx = h.ctx();
        exit_release_all(&mut ctx, &mut tabs)
    };

    assert_eq!(
        h.store.preference_pin(&a).unwrap().and_then(|p| p.backend),
        Some("other".to_string()),
        "the active tab's last choice is flushed on exit, not dropped"
    );
    let mut expect = vec![a.clone(), b.clone()];
    expect.sort();
    let mut got = released;
    got.sort();
    assert_eq!(
        got, expect,
        "every open tab's claim is released, not just the active one"
    );
}

/// S9 — the lean / ephemeral / no-store refusals, now a tested value rather
/// than a string literal inside an 8000-line function.
#[test]
fn the_tab_surface_refusals_are_explicit_and_ordered() {
    // Lean wins outright: it is a surface fact, true regardless of storage.
    let lean = tab_surface_refusal(false, false, true).expect("lean refuses");
    assert!(lean.contains("rich-TUI"), "{lean}");
    assert!(
        lean.contains("/resume"),
        "names the lean equivalent: {lean}"
    );
    // Ephemeral next.
    let eph = tab_surface_refusal(true, true, true).expect("ephemeral refuses");
    assert!(eph.contains("ephemeral"), "{eph}");
    // No store at all.
    let none = tab_surface_refusal(true, false, false).expect("a storeless session refuses");
    assert!(none.contains("no store"), "{none}");
    // And the one case that proceeds.
    assert!(tab_surface_refusal(true, false, true).is_none());
    // Lean + ephemeral reports the SURFACE reason — the operator cannot fix
    // ephemerality into tabs on a lean surface, so naming lean is the
    // actionable message.
    assert!(tab_surface_refusal(false, true, true)
        .expect("still refuses")
        .contains("rich-TUI"));
}

/// S3b — the turn refusal itself, which the audit found asserted only by a
/// comment. The message must name the recovery path, because the operator's
/// only way out is a command.
#[test]
fn a_degraded_tab_refuses_the_turn_and_names_the_way_out() {
    let clean = degraded_turn_refusal(None);
    assert!(clean.is_none(), "a healthy tab does not refuse");

    let degraded = crate::PinDegraded {
        reasons: vec!["pinned backend `gone` is not configured".into()],
        pin: newt_core::OperatorPreferencePin {
            backend: Some("gone".into()),
            ..Default::default()
        },
    };
    let msg = degraded_turn_refusal(Some(&degraded)).expect("a degraded tab refuses");
    assert!(msg.starts_with("!pin"), "visible marker first: {msg}");
    assert!(
        msg.contains("was not accepted"),
        "the contract is that the PROMPT is not accepted, not merely unsent: {msg}"
    );
    assert!(
        msg.contains("/tab retry"),
        "names the recovery command: {msg}"
    );
}

/// S8 — `/resume` onto a conversation NOT open in any tab stays a resume:
/// the seam hands it back rather than converting it into an activation.
///
/// The activation branch is covered elsewhere; this is the opposite
/// property, and the regression it guards is exactly "someone simplifies
/// resume and activate into one operation".
#[test]
fn resume_of_an_unopened_conversation_stays_a_resume() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();
    // A durable conversation that NO tab holds.
    let elsewhere = h.durable("not open anywhere");
    let before = h.snapshot(&tabs);

    let adopted = {
        let mut ctx = h.ctx();
        adopt_conversation(&mut ctx, &mut tabs, &elsewhere).unwrap()
    };
    assert!(
        matches!(adopted, Adopted::ProceedInActiveTab),
        "the seam must hand an unopened conversation back to the resume verb, \
             not activate it: got {adopted:?}"
    );
    assert_eq!(
        h.snapshot(&tabs),
        before,
        "and the seam itself mutates nothing — resume's sparse overlay runs at the caller"
    );
    assert_eq!(tabs.len(), 1, "no tab was opened for it either");
}

/// S1 — `interrupted_objective` really is per-tab. The audit found the
/// existing coverage vacuous: no test ever set it to `Some(..)`, so it rode
/// on a `TabSidecar::default()` comparison that could not fail.
#[test]
fn an_interrupted_objective_does_not_leak_into_another_tab() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol"]);
    let a = h.active_conversation_id.clone();
    h.store.create_with_id(&a, "A", None).unwrap();
    // A REAL prompt context, from a real receipt.
    let receipt = h
        .store
        .begin_prompt(
            &a,
            "A",
            None,
            newt_core::NewPrompt::operator(b"objective".to_vec(), b"objective".to_vec()),
        )
        .unwrap();
    h.interrupted_objective = Some(receipt);
    assert!(h.interrupted_objective.is_some(), "fixture precondition");

    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    assert!(
        h.interrupted_objective.is_none(),
        "tab A's interrupted objective must not follow into B — otherwise B's bare \
             `continue` would silently resume A's work"
    );

    {
        let mut ctx = h.ctx();
        activate_tab(&mut ctx, &mut tabs, 0).expect("back to A");
    }
    assert!(
        h.interrupted_objective.is_some(),
        "and it comes back with A, which is why it is stashed rather than dropped"
    );
}

/// P1 — activation is history-independent over the PROJECTED posture, not
/// merely over the tab model. `A→B` and `C→B` must land byte-identical.
#[test]
fn activation_is_history_independent_over_the_full_projected_state() {
    let _g = guard();
    let build = || {
        let (mut h, mut tabs) = Harness::new(&["sol", "other"]);
        let a = h.active_conversation_id.clone();
        h.store.create_with_id(&a, "A", None).unwrap();
        h.store
            .update_preference_pin(
                &a,
                &newt_core::OperatorPreferencePin {
                    backend: Some("other".into()),
                    tenacity: Some(newt_core::Tenacity::Relentless),
                    initiative: Some(newt_core::Initiative::Eager),
                    ..Default::default()
                },
            )
            .unwrap();
        let b = h.durable("B");
        h.store
            .update_preference_pin(
                &b,
                &newt_core::OperatorPreferencePin {
                    backend: Some("sol".into()),
                    cognition: Some("meticulous".into()),
                    ..Default::default()
                },
            )
            .unwrap();
        let c = h.durable("C");
        h.open_tab_on(&mut tabs, &b);
        h.open_tab_on(&mut tabs, &c);
        (h, tabs)
    };

    // Reached from A (index 0).
    let (mut from_a, mut tabs_a) = build();
    {
        let mut ctx = from_a.ctx();
        activate_tab(&mut ctx, &mut tabs_a, 0).unwrap();
        activate_tab(&mut ctx, &mut tabs_a, 1).unwrap();
    }
    let via_a = from_a.snapshot(&tabs_a);

    // Reached from C (index 2).
    let (mut from_c, mut tabs_c) = build();
    {
        let mut ctx = from_c.ctx();
        activate_tab(&mut ctx, &mut tabs_c, 2).unwrap();
        activate_tab(&mut ctx, &mut tabs_c, 1).unwrap();
    }
    let via_c = from_c.snapshot(&tabs_c);

    // Conversation ids differ per harness (fresh tempdirs), so compare
    // everything the ADR promises is history-independent.
    assert_eq!(via_a.provider, via_c.provider);
    assert_eq!(via_a.model, via_c.model);
    assert_eq!(via_a.cognition, via_c.cognition);
    assert_eq!(via_a.tenacity, via_c.tenacity);
    assert_eq!(via_a.initiative, via_c.initiative);
    assert_eq!(via_a.persona_cognition, via_c.persona_cognition);
    assert_eq!(via_a.persona_initiative, via_c.persona_initiative);
    assert_eq!(via_a.inf_url, via_c.inf_url);
    assert_eq!(via_a.inf_model, via_c.inf_model);
    assert_eq!(via_a.inf_kind, via_c.inf_kind);
    assert_eq!(via_a.choice_name, via_c.choice_name);
    assert_eq!(via_a.inf_context_window, via_c.inf_context_window);
    assert_eq!(via_a.persona, via_c.persona);
    assert_eq!(via_a.scratchpad, via_c.scratchpad);
    assert_eq!(via_a.plan_steps, via_c.plan_steps);
    assert_eq!(via_a.turns, via_c.turns);
    assert_eq!(via_a.roadmap, via_c.roadmap);
    assert_eq!(via_a.input_stash, via_c.input_stash);
    assert_eq!(via_a.degraded, via_c.degraded);
    assert_eq!(
        via_a.cognition,
        newt_core::cognition::CognitionOverride::Set(
            newt_core::role_profile::Cognition::Meticulous
        ),
        "B's own pin is in force either way"
    );
    assert_eq!(
        via_a.tenacity, None,
        "and A's tenacity never survives into B, from either predecessor"
    );
    assert_eq!(via_a.initiative, None, "nor A's initiative");
}

// ── 13. authority/security state is untouched by tab machinery ────────

/// The ADR's security invariant — measured, not argued.
///
/// Two independent proofs, because "authority never migrates via tab
/// machinery" deserves better than a comment:
///
/// 1. **By construction.** `TabSwitchCtx` has no authority, permission, or
///    credential field. The preference pin cannot carry a permission posture.
/// 2. **By measurement.** A pin names backends and dials ONLY, so applying
///    one must leave every authority-relevant process global bit-identical.
///    This walks a full switch sequence and compares them exactly.
#[test]
fn authority_state_is_bit_identical_across_any_switch_sequence() {
    let _g = guard();
    let (mut h, mut tabs) = Harness::new(&["sol", "other"]);
    let b = h.durable("B");
    h.store.claim(&b).unwrap();
    h.store
        .update_preference_pin(
            &b,
            &newt_core::OperatorPreferencePin {
                backend: Some("other".into()),
                cognition: Some("meticulous".into()),
                tenacity: Some(newt_core::Tenacity::Relentless),
                initiative: Some(newt_core::Initiative::Eager),
                model: Some("m0".into()),
            },
        )
        .unwrap();
    h.open_tab_on(&mut tabs, &b);

    // The permission binding is shared session state, not a conversation pin.
    newt_core::posture::set_active_posture(Some(newt_core::posture::ActivePosture {
        name: "locked".into(),
        preset_name: "strict".into(),
        clamp: newt_core::Caveats::default(),
        clamp_summary: "deny writes".into(),
        skill_body: Some("Inspect only.".into()),
        framing: Some("Keep the session clamp across conversations.".into()),
    }));

    // Everything authority-shaped that a switch could plausibly disturb.
    // Deliberately exact comparison — no "close enough" for security state.
    let authority = || {
        (
            std::env::var("NEWT_TEAM").ok(),
            std::env::var(newt_core::denial_journal::DENIAL_JOURNAL_PATH_ENV).ok(),
            std::env::var("NEWT_POSTURE").ok(),
            std::env::var("NEWT_EPHEMERAL").ok(),
            newt_core::posture::active_posture().map(|p| {
                (
                    p.name,
                    p.preset_name,
                    p.clamp,
                    p.clamp_summary,
                    p.skill_body,
                    p.framing,
                )
            }),
        )
    };
    let before = authority();

    for target in [0usize, 1, 0, 1, 0] {
        let mut ctx = h.ctx();
        let _ = activate_tab(&mut ctx, &mut tabs, target);
        assert_eq!(
            authority(),
            before,
            "no tab switch may widen or narrow what the agent is allowed to do"
        );
    }

    // And the pin itself cannot carry authority: its axes are exactly the
    // five preference axes, so there is nothing security-shaped to migrate.
    let pin = h.store.preference_pin(&b).unwrap().unwrap();
    let newt_core::OperatorPreferencePin {
        backend: _,
        model: _,
        cognition: _,
        tenacity: _,
        initiative: _,
    } = pin;
}

// ── 14. a materialized tab owns its selected persona name ────────────

fn materialized_persona_fixture() -> (Harness, TabSet) {
    let (mut h, tabs) = Harness::new(&["sol"]);
    let dir = h._root.path().join("personas");
    std::fs::create_dir_all(&dir).unwrap();
    h.persona_store = crate::PersonaStore::new(&dir);
    for (name, prompt) in [
        ("birth", "The persona at conversation birth."),
        ("selected", "The persona selected later in this tab."),
    ] {
        std::fs::write(dir.join(format!("{name}.md")), prompt).unwrap();
    }
    h.store
        .create_with_id(&h.active_conversation_id, "A", Some("birth"))
        .unwrap();
    h.store
        .append_turn(
            &h.active_conversation_id,
            "Earlier question.",
            "Earlier answer.",
        )
        .unwrap();
    // The same live input a successful `/persona set selected --keep-context`
    // leaves for the production tab-switch state machine.
    h.active_persona = Some(h.persona_store.load("selected").unwrap());
    h.system = crate::rebuild_system_prompt(
        &h.workspace,
        &h.memory,
        h.active_persona.as_ref(),
        &h.active_conversation_id,
    );
    (h, tabs)
}

/// Grounds tab selection in real conversation/persona stores: a row's immutable
/// birth metadata must not undo a later session selection on a round trip.
#[test]
fn materialized_tab_restores_its_later_selected_persona() {
    let _g = guard();
    let (mut h, mut tabs) = materialized_persona_fixture();
    let a = h.active_conversation_id.clone();
    let selected = h.active_persona.clone().unwrap();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    assert!(h.active_persona.is_none(), "B has no selected persona");

    activate_tab(&mut h.ctx(), &mut tabs, 0).unwrap();

    assert_eq!(h.active_conversation_id, a);
    assert_eq!(h.active_persona, Some(selected.clone()));
    assert!(h.system.contains(&selected.prompt));
    assert!(!h.system.contains("The persona at conversation birth."));
    assert_eq!(
        h.store.load(&a).unwrap().persona.as_deref(),
        Some("birth"),
        "session selection must not rewrite historical birth metadata"
    );
}

/// Regression (slice 1b): a conversation restore re-seats the restored
/// persona's INITIATIVE. `commit_conversation_restore` re-seated persona
/// cognition alone, so the outgoing persona's tenacity (now initiative)
/// carried into the restored conversation.
#[test]
fn a_restored_conversation_reseats_its_personas_initiative() {
    let _g = guard();
    let (mut h, mut tabs) = materialized_persona_fixture();
    std::fs::write(
        &h.active_persona.as_ref().unwrap().path,
        "+++\ninitiative = \"eager\"\n+++\n\nThe persona selected later in this tab.",
    )
    .unwrap();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    assert_eq!(
        newt_core::initiative::persona_initiative(),
        None,
        "B has none"
    );

    activate_tab(&mut h.ctx(), &mut tabs, 0).unwrap();
    assert_eq!(
        newt_core::initiative::persona_initiative(),
        Some(newt_core::Initiative::Eager),
        "the restored persona's initiative is in force"
    );
    activate_tab(&mut h.ctx(), &mut tabs, 1).unwrap();
    assert_eq!(newt_core::initiative::persona_initiative(), None);
}

/// Grounds the name-only snapshot with a real file replacement: switching back
/// must reload current restrictions, never restore a cached RoleProfile.
#[test]
fn materialized_tab_reloads_the_selected_personas_current_profile() {
    let _g = guard();
    let (mut h, mut tabs) = materialized_persona_fixture();
    let original = h.active_persona.clone().unwrap();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    std::fs::write(
        &original.path,
        "+++\ntools = [\"read_file\"]\ncrew = false\n[caveats]\nfs_write = \"none\"\nexec = \"none\"\nnet = \"none\"\n+++\n\nThe newly restricted selected persona.",
    )
    .unwrap();
    let current = h.persona_store.load("selected").unwrap();
    assert_ne!(current.profile, original.profile, "the file really changed");

    activate_tab(&mut h.ctx(), &mut tabs, 0).unwrap();

    assert_eq!(h.active_persona, Some(current.clone()));
    assert!(h.system.contains(&current.prompt));
    assert!(!h.system.contains(&original.prompt));
}

/// Grounds synthetic identity in a real same-named persona file: the runtime
/// altitude carrier must never acquire that file's prompt or role metadata.
#[test]
fn materialized_tab_preserves_synthetic_altitude_without_loading_its_display_name() {
    let _g = guard();
    let (mut h, mut tabs) = materialized_persona_fixture();
    let synthetic = crate::synthetic_altitude_persona(newt_core::Altitude::Coach);
    std::fs::write(
        h._root.path().join("personas/coach.md"),
        "+++\ntools = [\"read_file\"]\ncrew = false\nmodel = \"disk-coach-model\"\n[caveats]\nfs_write = \"none\"\nexec = \"none\"\nnet = \"none\"\n+++\n\nDISK_COACH_PERSONA_MUST_NOT_BE_SELECTED.",
    )
    .unwrap();
    let disk = h.persona_store.load("coach").unwrap();
    assert_eq!(
        disk.name, synthetic.name,
        "the display names really collide"
    );
    assert_ne!(disk.profile, synthetic.profile);
    assert!(disk.profile.caveats.is_some());
    assert!(synthetic.path.as_os_str().is_empty());
    h.active_persona = Some(synthetic.clone());
    h.system = crate::rebuild_system_prompt(
        &h.workspace,
        &h.memory,
        h.active_persona.as_ref(),
        &h.active_conversation_id,
    );
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);

    activate_tab(&mut h.ctx(), &mut tabs, 0).unwrap();

    assert_eq!(h.active_persona, Some(synthetic));
    assert!(!h.system.contains(&disk.prompt));
    assert!(!h.system.contains("The persona at conversation birth."));
}

/// Grounds prepare-before-commit with an actual missing selected-persona file:
/// a failed reload must leave the outgoing tab and all its live state intact.
#[test]
fn missing_selected_persona_refuses_a_materialized_tab_switch_atomically() {
    let _g = guard();
    let (mut h, mut tabs) = materialized_persona_fixture();
    let selected = h.active_persona.clone().unwrap();
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);
    h.turns_this_conversation = 7;
    h.input_stash = "Unsubmitted text in B.".into();
    let before = h.snapshot(&tabs);
    let active_index = tabs.active_index();
    let active_tab_id = tabs.active().session_id().clone();
    let owner_before = newt_core::lifecycle::active_session();
    std::fs::remove_file(&selected.path).unwrap();
    assert!(h.persona_store.load("selected").is_err());

    let result = activate_tab(&mut h.ctx(), &mut tabs, 0);

    assert!(matches!(result, Err(TabError::PreflightFailed { .. })));
    assert_eq!(tabs.active_index(), active_index);
    assert_eq!(tabs.active().session_id(), &active_tab_id);
    assert_eq!(newt_core::lifecycle::active_session(), owner_before);
    assert_eq!(h.snapshot(&tabs), before);
}

/// A captured absence differs from an uncaptured selection. Ground that
/// distinction against a real row that still names a birth persona.
#[test]
fn materialized_tab_keeps_a_known_absent_persona_instead_of_resurrecting_birth() {
    let _g = guard();
    let (mut h, mut tabs) = materialized_persona_fixture();
    let a = h.active_conversation_id.clone();
    h.active_persona = None;
    h.system = crate::rebuild_system_prompt(&h.workspace, &h.memory, None, &a);
    let b = h.durable("B");
    h.open_tab_on(&mut tabs, &b);

    activate_tab(&mut h.ctx(), &mut tabs, 0).unwrap();

    assert_eq!(h.active_conversation_id, a);
    assert!(h.active_persona.is_none());
    assert!(!h.system.contains("The persona at conversation birth."));
    assert!(!h.system.contains("The persona selected later in this tab."));
    assert_eq!(h.store.load(&a).unwrap().persona.as_deref(), Some("birth"));
}