abstractcore-console 0.8.1

A terminal console for AbstractCore: configure models, providers and capability routes, browse, download and delete local models, and install local engines (Ollama, LM Studio, MLX, llama.cpp). Also a library of the shared Models/Engines screens, rendered by AbstractTUI.
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
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
2061
2062
2063
2064
2065
2066
2067
//! The worker thread: owns every file read/write and every
//! `abstractcore` subprocess. The UI thread owns all signals; this
//! thread never touches them directly — it posts closures through
//! `WakeHandle`, which run on the UI thread in the next frame's user
//! phase.
//!
//! Serial by design: one command at a time, total order. Writes are
//! three-phase BY CONSTRUCTION — refuse-unless-writable → run verbs →
//! verify against a FRESH re-read (+ fresh derived views) → journal —
//! so a screen cannot forget the verification (the CLI's own success
//! signals lie; docs/backlog/proposed/0001_write_lane_design.md).

use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::Receiver;
use std::time::Duration;

use abstracttui::reactive::WakeHandle;
use serde_json::{json, Value};

use crate::cli::{CliError, CliErrorKind, CoreCli};
use crate::config::{self, ConfigPath, FileState};
use crate::store::{
    models_from_payload, AvailabilityData, ConfigMirror, JournalEntry, Loadable, ProfilesData,
    RoutesData, Store,
};
use crate::writes::{eval_file_expect, Arg, Expect, StdinSecret, WriteSpec, WriteVerb};

static OP_ID: AtomicU64 = AtomicU64::new(1);

fn next_op() -> u64 {
    OP_ID.fetch_add(1, Ordering::Relaxed)
}

static FORM_ID: AtomicU64 = AtomicU64::new(1);

/// Correlates a write with the form modal that issued it (close on
/// success, stay open with data intact on failure).
pub fn next_form_id() -> u64 {
    FORM_ID.fetch_add(1, Ordering::Relaxed)
}

/// Commands the UI sends to the worker. Debug is test surface —
/// secrets ride `writes::Arg::Secret`, which redacts structurally.
#[derive(Clone, Debug)]
pub enum Cmd {
    /// Re-read + re-fold the config file.
    LoadConfig,
    /// `abstractcore config defaults --json` → routes.
    LoadRoutes,
    /// `abstractcore config providers --probe --json` → the provider
    /// INVENTORY (every provider the registry knows, keyless ones
    /// included) plus the endpoint profiles. One payload, two tables.
    LoadProfiles,
    /// Per-provider model list for pickers (`config models P --json`).
    LoadModels { provider: String },
    /// `abstractcore models status --json` → local weight availability.
    LoadAvailability,
    /// `abstractcore models download <provider> <artifact>` — the ONLY
    /// command in this console that spends network bytes, and it only
    /// ever runs from an explicit `d` on a route the operator selected.
    DownloadModel { provider: String, artifact: String },
    /// One verified write action.
    Write(Box<WriteSpec>),
    /// One test verb (M3): live model discovery, route membership, or
    /// a cheap generation. Evidence lands in `store.tests`.
    Probe(crate::probes::ProbeSpec),
    /// `abstractcore email status --json` → the Email screen.
    LoadEmail,
    /// One `abstractcore email …` verb (connect / test / disconnect /
    /// policy / limits / enable / disable), then a fresh status read.
    Email(Box<EmailAction>),
    /// `abstractcore email discover <address> --json`: find the mail
    /// servers of an address (the Mailbox card's Other tab summary).
    /// Changes nothing; the answer lands in `store.email_discovery`.
    EmailDiscover { address: String },
}

/// One email verb. `args` follow `abstractcore email`; `--json` is
/// appended by the worker. A password or client secret never rides argv
/// (readable by every local user via `ps` while the command runs): the
/// args carry `--password-stdin` / `--client-secret-stdin` and the
/// secret rides `stdin_secret`, written to the command's stdin (redacted
/// in Debug, in the journal and in every error label).
#[derive(Clone, Debug)]
pub struct EmailAction {
    /// What the journal and the busy strip say ("email test").
    pub label: String,
    pub args: Vec<Arg>,
    /// The form to close on success (None for key verbs).
    pub form_id: Option<u64>,
    /// The one secret line written to the command's stdin, if any.
    pub stdin_secret: Option<StdinSecret>,
    /// An OAuth2 sign-in (`connect --oauth …`): the command waits for a
    /// person, streams its `oauth_prompt` into `store.email_oauth_prompt`
    /// and can be cancelled (`cancel_email_oauth`).
    pub oauth: bool,
    /// The notice on success, describing the NEW state ("Agent email
    /// tools are on."); None says "<label>: done".
    pub ok_notice: Option<String>,
}

/// Set by `cancel_email_oauth`; the running OAuth sign-in is killed.
static EMAIL_OAUTH_CANCEL: AtomicBool = AtomicBool::new(false);

/// Cancel the OAuth2 sign-in in flight (the UI thread calls this; the
/// worker kills the command within 25 ms and nothing is stored).
pub fn cancel_email_oauth() {
    EMAIL_OAUTH_CANCEL.store(true, Ordering::SeqCst);
}

/// Reads are Python-startup-bound (~1.5s observed); 30s is a hung
/// interpreter, not a slow one.
const READ_TIMEOUT: Duration = Duration::from_secs(30);
/// Model listing may do live discovery against a slow local server.
const MODELS_TIMEOUT: Duration = Duration::from_secs(60);
/// Setters are one Python startup + one file write.
const WRITE_TIMEOUT: Duration = Duration::from_secs(60);
/// A generation may LOAD a local model first (21s observed for a 4B);
/// the busy strip shows elapsed the whole way.
const GENERATE_TIMEOUT: Duration = Duration::from_secs(120);
/// A model download is the one operation here measured in gigabytes.
/// 2 hours is "the provider tool is wedged", not "this file is large" —
/// a 9B 4-bit build over a domestic line is comfortably inside it.
const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(7200);
/// TCP reachability disambiguation — local endpoints answer instantly.
const REACH_TIMEOUT: Duration = Duration::from_millis(1500);
/// An email verb may sign in to IMAP and SMTP (30 s connect timeout
/// each) before it answers.
const EMAIL_TIMEOUT: Duration = Duration::from_secs(150);
/// An OAuth2 sign-in waits for a person to approve it (a device code
/// lives 15 minutes), then tests both legs.
const EMAIL_OAUTH_TIMEOUT: Duration = Duration::from_secs(20 * 60);

/// Form-completion sink (constructed in lib.rs over the UI signal).
pub type DoneSink = Box<dyn Fn(u64, Result<String, String>) + Send>;

pub fn spawn(
    store: Store,
    wake: WakeHandle,
    rx: Receiver<Cmd>,
    config_path: ConfigPath,
    cli: Option<CoreCli>,
    done: DoneSink,
) -> std::thread::JoinHandle<()> {
    std::thread::spawn(move || {
        while let Ok(cmd) = rx.recv() {
            // A panic in one command must not silently kill the lane:
            // catch, report loudly, keep serving.
            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                handle(&store, &wake, &config_path, cli.as_ref(), &cmd, &done);
            }));
            if let Err(p) = result {
                let msg = panic_text(&p);
                let cmd_dbg = format!("{cmd:?}");
                wake.post(move || {
                    // The worker is SERIAL: at most the panicked
                    // command's own ops are in flight — clearing all
                    // busy entries cannot cancel anyone else's, and a
                    // leaked ghost op would keep the 500ms ticker
                    // alive forever (review P3-13). The probe flag
                    // rides the same lifecycle: stuck true would
                    // refuse every future test verb.
                    store.busy.update(|ops| ops.clear());
                    store.probe_busy.set(false);
                    store.notice.set(Some(format!(
                        "internal error while handling {cmd_dbg}: {msg}"
                    )));
                });
            }
        }
    })
}

fn handle(
    store: &Store,
    wake: &WakeHandle,
    config_path: &ConfigPath,
    cli: Option<&CoreCli>,
    cmd: &Cmd,
    done: &DoneSink,
) {
    match cmd {
        Cmd::LoadConfig => {
            let op = next_op();
            begin(store, wake, op, "reading config file");
            let state = config::load(&config_path.path);
            let mirror = ConfigMirror {
                path: config_path.clone(),
                state,
                loaded_at: crate::store::now_hms(),
            };
            let store = *store;
            wake.post(move || {
                store.end_busy(op);
                store.cfg.set(Loadable::Ready(mirror.clone()));
            });
        }
        Cmd::LoadRoutes => {
            load_derived(
                store,
                wake,
                cli,
                "loading routes (config defaults --json)",
                &["config", "defaults", "--json"],
                |store, outcome| match outcome {
                    Ok(v) => store
                        .routes
                        .set(Loadable::Ready(RoutesData::from_value(&v))),
                    Err(e) => store.routes.set(Loadable::Failed(e)),
                },
            );
        }
        Cmd::LoadProfiles => {
            load_derived(
                store,
                wake,
                cli,
                // `--probe` is what turns "lmstudio exists" into "lmstudio is
                // answering on :1234": one cheap GET per local server, on the
                // worker thread, never on a render path.
                "loading providers (config providers --probe --json)",
                &["config", "providers", "--probe", "--json"],
                |store, outcome| match outcome {
                    Ok(v) => store
                        .profiles
                        .set(Loadable::Ready(ProfilesData::from_value(&v))),
                    Err(e) => store.profiles.set(Loadable::Failed(e)),
                },
            );
        }
        Cmd::LoadModels { provider } => {
            let provider = provider.clone();
            let outcome = match cli {
                None => Err(no_cli_error()),
                Some(cli) => {
                    let op = next_op();
                    begin(store, wake, op, &format!("listing models for {provider}"));
                    let r = cli
                        .run_json(&["config", "models", &provider, "--json"], MODELS_TIMEOUT)
                        .map(|o| models_from_payload(&o.value));
                    let store = *store;
                    wake.post(move || store.end_busy(op));
                    r
                }
            };
            let store = *store;
            wake.post(move || {
                store.models.update(|m| {
                    m.insert(
                        provider.clone(),
                        match &outcome {
                            Ok(models) => Loadable::Ready(models.clone()),
                            Err(e) => Loadable::Failed(e.clone()),
                        },
                    );
                });
            });
        }
        Cmd::LoadAvailability => {
            load_derived(
                store,
                wake,
                cli,
                "probing model weights (models status --json)",
                &["models", "status", "--all", "--json"],
                |store, outcome| match outcome {
                    Ok(v) => store
                        .availability
                        .set(Loadable::Ready(AvailabilityData::from_value(&v))),
                    Err(e) => store.availability.set(Loadable::Failed(e)),
                },
            );
        }
        Cmd::DownloadModel { provider, artifact } => {
            handle_download(store, wake, cli, provider, artifact)
        }
        Cmd::Write(spec) => handle_write(store, wake, config_path, cli, spec, done),
        Cmd::Probe(spec) => handle_probe(store, wake, config_path, cli, spec),
        Cmd::LoadEmail => {
            load_derived(
                store,
                wake,
                cli,
                "loading email (email status --json)",
                &["email", "status", "--json"],
                |store, outcome| match outcome {
                    Ok(v) => store.email.set(Loadable::Ready(v)),
                    Err(e) => store.email.set(Loadable::Failed(e)),
                },
            );
        }
        Cmd::Email(action) => handle_email(store, wake, cli, action, done),
        Cmd::EmailDiscover { address } => handle_email_discover(store, wake, cli, address),
    }
}

/// A server lookup may try autoconfig, the ISPDB, SRV and MX records
/// (each bounded by the CLI's own per-step timeout).
const DISCOVER_TIMEOUT: Duration = Duration::from_secs(45);

/// Find the mail servers of `address` (`abstractcore email discover
/// <address> --json`); the document, or the refusal's words, lands in
/// `store.email_discovery` tagged with the address, so a stale answer
/// never describes a newer entry. Changes nothing on disk.
fn handle_email_discover(store: &Store, wake: &WakeHandle, cli: Option<&CoreCli>, address: &str) {
    let answer = match cli {
        None => json!({"address": address, "error": no_cli_error().to_string()}),
        Some(cli) => {
            let op = next_op();
            begin(store, wake, op, "finding the mail servers");
            let out = cli.run_email_discover(address, DISCOVER_TIMEOUT);
            let store_b = *store;
            wake.post(move || store_b.end_busy(op));
            match out {
                Ok(v) => json!({"address": address, "result": v}),
                Err(e) => json!({"address": address, "error": e.message}),
            }
        }
    };
    let store = *store;
    wake.post(move || store.email_discovery.set(Some(answer)));
}

/// The argv of one email verb: `email <args…> --json`.
pub(crate) fn email_argv(action: &EmailAction) -> Vec<&str> {
    let mut argv: Vec<&str> = vec!["email"];
    argv.extend(action.args.iter().map(Arg::value));
    argv.push("--json");
    argv
}

/// What the journal and error labels name: the args, secrets redacted.
fn email_redacted_label(action: &EmailAction) -> String {
    format!(
        "abstractcore email {}",
        action
            .args
            .iter()
            .map(|a| match a {
                Arg::Plain(s) => s.clone(),
                Arg::Secret(_) => "«redacted»".to_string(),
            })
            .collect::<Vec<_>>()
            .join(" ")
    )
}

/// Run one email verb: `abstractcore email <args…> --json`, its secret
/// (if any) written to the command's stdin, never on its command line.
/// An OAuth2 sign-in streams its prompt to `on_prompt` and stops when
/// `cancel` turns true; other verbs ignore both. `timeout` bounds the
/// command (`EMAIL_TIMEOUT`, or `EMAIL_OAUTH_TIMEOUT` for a sign-in).
pub(crate) fn run_email_action(
    cli: &CoreCli,
    action: &EmailAction,
    timeout: Duration,
    on_prompt: Box<dyn Fn(Value) + Send>,
    cancel: &AtomicBool,
) -> Result<crate::cli::CliOutput, crate::cli::CliError> {
    let argv = email_argv(action);
    let stdin_line = action.stdin_secret.as_ref().map(StdinSecret::line);
    let stdin = stdin_line.as_deref();
    let redacted = email_redacted_label(action);
    if action.oauth {
        cli.run_email_streaming(&argv, stdin, &redacted, timeout, on_prompt, cancel)
    } else {
        cli.run_email(&argv, stdin, &redacted, timeout)
    }
}

/// One email verb: run it, journal it (redacted), route the outcome to
/// its form, then re-read the status so the screen shows the truth.
fn handle_email(
    store: &Store,
    wake: &WakeHandle,
    cli: Option<&CoreCli>,
    action: &EmailAction,
    done: &DoneSink,
) {
    let Some(cli) = cli else {
        let err = no_cli_error().to_string();
        if let Some(fid) = action.form_id {
            done(fid, Err(err.clone()));
        }
        let store = *store;
        wake.post(move || store.notice.set(Some(err)));
        return;
    };
    let op = next_op();
    begin(store, wake, op, &action.label);
    let redacted = email_redacted_label(action);
    let outcome = if action.oauth {
        EMAIL_OAUTH_CANCEL.store(false, Ordering::SeqCst);
        let (store_p, wake_p) = (*store, wake.clone());
        let on_prompt: Box<dyn Fn(Value) + Send> = Box::new(move |p: Value| {
            wake_p.post(move || store_p.email_oauth_prompt.set(Some(p)));
        });
        let out = run_email_action(
            cli,
            action,
            EMAIL_OAUTH_TIMEOUT,
            on_prompt,
            &EMAIL_OAUTH_CANCEL,
        );
        let store_c = *store;
        wake.post(move || store_c.email_oauth_prompt.set(None));
        out
    } else {
        run_email_action(
            cli,
            action,
            EMAIL_TIMEOUT,
            Box::new(|_| {}),
            &EMAIL_OAUTH_CANCEL,
        )
    };
    let (notice, journal) = match &outcome {
        Ok(_) => (
            action
                .ok_notice
                .clone()
                .unwrap_or_else(|| format!("{}: done", action.label)),
            Ok("ok".to_string()),
        ),
        Err(e) => (
            format!("{}: {}", action.label, e.message),
            Err(e.message.clone()),
        ),
    };
    let error_code = outcome.as_ref().err().and_then(|e| e.reason_code.clone());
    if let Some(fid) = action.form_id {
        done(fid, journal.clone());
    }
    let status = cli.run_json(&["email", "status", "--json"], READ_TIMEOUT);
    let store = *store;
    wake.post(move || {
        store.end_busy(op);
        store.push_journal(JournalEntry {
            when: crate::store::now_hms(),
            action: redacted,
            outcome: journal,
        });
        store.email_error_code.set(error_code);
        match status {
            Ok(out) => store.email.set(Loadable::Ready(out.value)),
            Err(e) => store.email.set(Loadable::Failed(e)),
        }
        store.notice.set(Some(notice));
    });
}

/// THE ONLY COMMAND HERE THAT SPENDS NETWORK BYTES. It runs the shipped
/// `abstractcore models download` (which runs the PROVIDER's own tool),
/// so the console and the CLI cannot disagree about what a download is.
///
/// Read once at the end: the CLI streams `host_job_v1` progress lines,
/// and this lane keeps only the final one (the busy strip already shows
/// elapsed; the Models screen, 9, is the lane with a progress bar).
/// The outcome lands in the journal and the notice, and availability is
/// re-probed so the grid tells the truth immediately afterwards.
fn handle_download(
    store: &Store,
    wake: &WakeHandle,
    cli: Option<&CoreCli>,
    provider: &str,
    artifact: &str,
) {
    let Some(cli) = cli else {
        let store = *store;
        let err = no_cli_error().to_string();
        wake.post(move || store.notice.set(Some(err)));
        return;
    };
    let op = next_op();
    let label = format!("downloading {provider} {artifact}");
    begin(store, wake, op, &label);
    let action = format!("abstractcore models download {provider} {artifact}");
    // `models download --json` streams `host_job_v1` lines and ends with
    // the final job, so only the LAST line is the answer.
    let outcome = cli.run_json_last(
        &["models", "download", provider, artifact, "--json"],
        DOWNLOAD_TIMEOUT,
    );
    // A failed download exits non-zero, so `run_json` reports the CLI's
    // own error line — the provider tool's words, which is the only
    // useful half of a download failure.
    let (notice, journal) = match &outcome {
        Ok(out) => {
            let (status, message) = download_outcome(&out.value);
            (
                format!(
                    "{provider} {artifact}: {status}{}",
                    if message.is_empty() {
                        String::new()
                    } else {
                        format!(" — {message}")
                    }
                ),
                Ok(status.to_string()),
            )
        }
        Err(e) => (format!("{provider} {artifact}: {e}"), Err(e.to_string())),
    };
    let store = *store;
    wake.post(move || {
        store.end_busy(op);
        store.push_journal(JournalEntry {
            when: crate::store::now_hms(),
            action,
            outcome: journal,
        });
        store.notice.set(Some(notice));
    });
}

/// Status and message of a finished download, read from the final
/// document: the legacy `results[0]`, else the job's `result`, else the
/// job itself (`status`/`message`).
pub(crate) fn download_outcome(v: &serde_json::Value) -> (String, String) {
    let result = v
        .get("results")
        .and_then(|r| r.as_array())
        .and_then(|a| a.first())
        .or_else(|| v.get("result").filter(|r| r.is_object()));
    let pick = |key: &str| {
        result
            .and_then(|r| r.get(key))
            .and_then(|s| s.as_str())
            .or_else(|| v.get(key).and_then(|s| s.as_str()))
            .map(str::to_string)
    };
    (
        pick("status").unwrap_or_else(|| "completed".into()),
        pick("message").unwrap_or_default(),
    )
}

// ---------------------------------------------------------------------
// The probe lane (M3 test verbs).
// ---------------------------------------------------------------------

fn handle_probe(
    store: &Store,
    wake: &WakeHandle,
    config_path: &ConfigPath,
    cli: Option<&CoreCli>,
    spec: &crate::probes::ProbeSpec,
) {
    use crate::probes::{self, ProbeKind, Verdict};

    let op = next_op();
    begin(store, wake, op, &spec.label);
    {
        let store = *store;
        wake.post(move || store.probe_busy.set(true));
    }

    let (verdict, detail) = match (&spec.kind, cli) {
        (_, None) => (Verdict::Failed, no_cli_error().to_string()),
        (ProbeKind::ListModels { target, reach }, Some(cli)) => {
            match cli.run_json(
                &["config", "test-provider", target, "--json"],
                MODELS_TIMEOUT,
            ) {
                Err(e) => (Verdict::Failed, e.to_string()),
                Ok(out) => {
                    // TCP evidence only on the ambiguous branch.
                    let count = out.value.get("count").and_then(Value::as_u64).unwrap_or(0);
                    let evidence = if count == 0 {
                        reach.as_ref().map(|hp| (hp, tcp_probe(hp)))
                    } else {
                        None
                    };
                    let (v, mut d) = probes::fold_list_models(
                        &out.value,
                        evidence.as_ref().map(|(hp, r)| (*hp, r)),
                    );
                    // For keyed cloud providers the empty listing is
                    // ALSO the silent no-API-key answer (openai's
                    // list_available_models returns [] keyless) — name
                    // the likely cause where no endpoint exists to
                    // check (M3 review P3-6).
                    if v == Verdict::NotProven
                        && reach.is_none()
                        && crate::probes::KEYED_CLOUD_PROVIDERS.contains(&target.as_str())
                    {
                        d.push_str(
                            "; for this keyed cloud provider it is also the answer when \
                                    no API key resolves (config or env)",
                        );
                    }
                    (v, d)
                }
            }
        }
        (
            ProbeKind::RouteCheck {
                provider,
                model,
                reach,
                ..
            },
            Some(cli),
        ) => {
            match cli.run_json(
                &["config", "test-provider", provider, "--json"],
                MODELS_TIMEOUT,
            ) {
                Err(e) => (Verdict::Failed, e.to_string()),
                Ok(out) => {
                    let count = out.value.get("count").and_then(Value::as_u64).unwrap_or(0);
                    let evidence = if count == 0 {
                        reach.as_ref().map(|hp| (hp, tcp_probe(hp)))
                    } else {
                        None
                    };
                    let (v, d) = probes::fold_route_check(
                        &out.value,
                        model,
                        evidence.as_ref().map(|(hp, r)| (*hp, r)),
                    );
                    // The label names only the route (evidence replaces
                    // per target); the tested pair rides the detail
                    // AFTER the cause — notices truncate from the
                    // right and endpoint+HF-style pairs are long (M3
                    // review P3-11).
                    (v, format!("{d} — {provider}/{model}"))
                }
            }
        }
        (ProbeKind::Generate { provider, model }, Some(cli)) => {
            probe_generation(config_path, cli, provider.as_deref(), model.as_deref())
        }
    };

    let store = *store;
    let label = spec.label.clone();
    let result = crate::probes::TestResult {
        when: crate::store::now_hms(),
        label: label.clone(),
        verdict,
        detail: detail.clone(),
    };
    wake.post(move || {
        store.end_busy(op);
        store.probe_busy.set(false);
        store.record_test(result.clone());
        store.push_journal(JournalEntry {
            when: result.when.clone(),
            action: label.clone(),
            // "NOT PROVEN — " is a rendering contract with the journal
            // view: review.rs renders Err rows starting with it under
            // the ? glyph, not ✗ (M3 review P3-5). Change both or
            // neither.
            outcome: match verdict {
                Verdict::Proven => Ok(detail.clone()),
                Verdict::NotProven => Err(format!("NOT PROVEN — {detail}")),
                Verdict::Failed => Err(detail.clone()),
            },
        });
        // No cap here: the notice line fits itself to the terminal
        // (ui::mod's `ellipsize(&n, viewport.w - 6)`), so a second blind
        // 90-char cut only hid evidence a wide terminal had room for.
        store
            .notice
            .set(Some(format!("{} {}: {detail}", verdict.glyph(), label,)));
    });
}

/// The generation probe. For the DEFAULT route (`provider/model` both
/// None) the config file must actually name one — probed 2026-07-25:
/// `abstractcore-chat` on an empty config silently invents a
/// huggingface default, so without this pre-check the test would pass
/// while the operator's own route is unconfigured.
fn probe_generation(
    config_path: &ConfigPath,
    cli: &CoreCli,
    provider: Option<&str>,
    model: Option<&str>,
) -> (crate::probes::Verdict, String) {
    use crate::probes::{fold_generation, Verdict};

    // Every branch may need the fresh raw file: the default resolution
    // AND the endpoint-profile expansion below.
    let raw = match config::load_with_raw(&config_path.path) {
        (FileState::Ready(_), Some(raw)) => raw,
        (FileState::Missing, _) => Value::Object(Default::default()),
        _ => {
            return (
                Verdict::Failed,
                "the config file is corrupt/unreadable — fix it before testing".into(),
            )
        }
    };
    let (provider, model) = match (provider, model) {
        (Some(p), Some(m)) => (p.to_string(), m.to_string()),
        _ => {
            let get = |k: &str| {
                raw.get("default_models")
                    .and_then(|d| d.get(k))
                    .and_then(Value::as_str)
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .map(String::from)
            };
            match (get("global_provider"), get("global_model")) {
                (Some(p), Some(m)) => (p, m),
                _ => {
                    return (
                        Verdict::Failed,
                        "no default route configured (default_models.global_provider/model) — \
                         set one first (wizard step 2); testing without it would exercise a \
                         built-in fallback, not YOUR route"
                            .into(),
                    )
                }
            }
        }
    };

    // `endpoint:<id>` routes: the chat CLI's --provider argparse knows
    // only the 10 static names (utils/cli.py:2558 — M3 review P1-1), so
    // naming the endpoint verbatim dies on a usage error and a WORKING
    // route reads ✗ FAILED. Expand keyless profiles to their family +
    // base_url (both flags exist); keyed profiles are refused honestly
    // — the chat CLI cannot receive their key (argv never carries
    // secrets), and a guessed key lane would mint fresh 401 lies.
    let mut argv_provider = provider.clone();
    let mut base_url: Option<String> = None;
    if let Some(id) = provider.strip_prefix("endpoint:") {
        let row = raw
            .get("provider_profiles")
            .and_then(|p| p.get("profiles"))
            .and_then(|p| p.get(id));
        let Some(row) = row else {
            return (
                Verdict::Failed,
                format!(
                    "the route names endpoint:{id}, but no such profile exists in the file — \
                     a on Providers adds one"
                ),
            );
        };
        let s = |k: &str| {
            row.get(k)
                .and_then(Value::as_str)
                .map(str::trim)
                .unwrap_or("")
                .to_string()
        };
        if row.get("enabled").and_then(Value::as_bool) == Some(false) {
            return (
                Verdict::NotProven,
                format!("profile {id} is not enabled — open it (e on Providers) and check [x] enabled before testing"),
            );
        }
        if !s("api_key").is_empty() || !s("api_key_env_var").is_empty() {
            return (
                Verdict::NotProven,
                format!(
                    "profile {id} carries an API key the chat CLI cannot receive \
                     (abstractcore-chat knows no endpoint: providers, and argv must never \
                     carry secrets) — t on Providers proves its models; generation over \
                     keyed endpoint profiles needs chat-CLI endpoint support"
                ),
            );
        }
        let family = s("provider_family");
        let url = s("base_url");
        if family.is_empty() || url.is_empty() {
            return (
                Verdict::NotProven,
                format!("profile {id} lacks a family/base_url — e on Providers completes it"),
            );
        }
        argv_provider = family;
        base_url = Some(url);
    }

    let started = std::time::Instant::now();
    let mut args = vec![
        "--provider",
        argv_provider.as_str(),
        "--model",
        model.as_str(),
        "--prompt",
        "Reply with exactly: PONG",
        "--max-output-tokens",
        "24",
    ];
    if let Some(u) = &base_url {
        args.push("--base-url");
        args.push(u.as_str());
    }
    let out = cli.run_chat(&args, GENERATE_TIMEOUT);
    // A PATH-resolved chat binary may belong to a DIFFERENT install
    // than the abstractcore serving discovery — say so in the
    // evidence rather than silently mixing installs (M3 review P3-2).
    let provenance = if cli.chat_from_path {
        " [chat binary from PATH, not beside abstractcore]"
    } else {
        ""
    };
    match out {
        Err(e) => (Verdict::Failed, format!("{e}{provenance}")),
        Ok((stdout, _warnings)) => {
            let (v, d) = fold_generation(&stdout, started.elapsed().as_secs());
            let via = base_url
                .as_ref()
                .map(|u| format!(" (via {argv_provider} @ {u})"))
                .unwrap_or_default();
            (v, format!("{provider}/{model} — {d}{via}{provenance}"))
        }
    }
}

/// The worker's one socket lane: connect against a KNOWN http endpoint
/// (profile base_url or a documented local default — the spec builder
/// enforces which; see probes::endpoint_for).
fn tcp_probe(hp: &crate::probes::HostPort) -> crate::probes::Reach {
    use std::net::ToSocketAddrs;
    let addrs = match (hp.host.as_str(), hp.port).to_socket_addrs() {
        Ok(a) => a.collect::<Vec<_>>(),
        Err(e) => return crate::probes::Reach::Unresolvable(e.to_string()),
    };
    probe_addr_list(&addrs, REACH_TIMEOUT)
}

/// One reachability verdict over ALL resolved addresses: Connected if
/// ANY accepts; Refused only when every one refuses. `localhost`
/// resolves `::1` FIRST on this class of machine while local servers
/// (LM Studio, ollama) often bind IPv4 only — probing just the first
/// address reported "the server looks DOWN" for an UP server, the
/// exact evidence the count==0 branch exists to give (M3 review P1-2).
/// The error text prefers the IPv4 attempt (the family local servers
/// actually serve).
fn probe_addr_list(addrs: &[std::net::SocketAddr], timeout: Duration) -> crate::probes::Reach {
    use crate::probes::Reach;
    if addrs.is_empty() {
        return Reach::Unresolvable("no addresses".into());
    }
    let mut v4_err: Option<String> = None;
    let mut last_err: Option<String> = None;
    for addr in addrs {
        match std::net::TcpStream::connect_timeout(addr, timeout) {
            Ok(_) => return Reach::Connected,
            Err(e) => {
                if addr.is_ipv4() && v4_err.is_none() {
                    v4_err = Some(e.to_string());
                }
                last_err = Some(e.to_string());
            }
        }
    }
    Reach::Refused(v4_err.or(last_err).unwrap_or_else(|| "refused".into()))
}

fn no_cli_error() -> CliError {
    CliError::core(
        CliErrorKind::NotFound,
        "no $ABSTRACTCORE_CLI, nothing on PATH, ~/.local/bin or ./.venv".into(),
    )
}

// ---------------------------------------------------------------------
// The write lane.
// ---------------------------------------------------------------------

fn handle_write(
    store: &Store,
    wake: &WakeHandle,
    config_path: &ConfigPath,
    cli: Option<&CoreCli>,
    spec: &WriteSpec,
    done: &DoneSink,
) {
    let op = next_op();
    begin(store, wake, op, &spec.label);

    let outcome = execute_write(config_path, cli, spec);

    // Post-write state refresh: the mirror ALWAYS re-reads (even after
    // failure — the operator must see what the file holds now), and
    // the derived views refresh when the write touched them.
    let mirror = ConfigMirror {
        path: config_path.clone(),
        state: config::load(&config_path.path),
        loaded_at: crate::store::now_hms(),
    };
    let mut routes_new: Option<Loadable<RoutesData>> = None;
    let mut profiles_new: Option<Loadable<ProfilesData>> = None;
    let mut fallback_new: Option<Option<String>> = None;
    if let Some(cli) = cli {
        if spec.needs_routes() || outcome.is_ok() {
            match cli.run_json(&["config", "defaults", "--json"], READ_TIMEOUT) {
                Ok(out) => {
                    fallback_new = Some(out.fallback_warnings.first().cloned());
                    routes_new = Some(Loadable::Ready(RoutesData::from_value(&out.value)));
                }
                Err(e) => routes_new = Some(Loadable::Failed(e)),
            }
        }
        // Profiles refresh only when the write can touch them (key/profile
        // specs declare profile expects) — an unconditional refresh added
        // ~5-15s of CLI tail to EVERY write for views it cannot change.
        if spec.needs_profiles() {
            // `--probe` HERE TOO, exactly as `Cmd::LoadProfiles` reads
            // it. The post-write refresh REPLACES the screen's whole
            // providers view, so a probe-less re-read silently downgrades
            // every probed row: the live model counts vanish and the
            // `origin` column flips `auto` → `registry` — a WRONG word
            // about a server that is still answering (caught live by the
            // parity pty run, 2026-08-01). The probe is one cheap
            // localhost GET per local server, the same cost the screen
            // already pays on every reload.
            match cli.run_json(&["config", "providers", "--probe", "--json"], READ_TIMEOUT) {
                Ok(out) => {
                    if fallback_new.is_none() {
                        fallback_new = Some(out.fallback_warnings.first().cloned());
                    }
                    profiles_new = Some(Loadable::Ready(ProfilesData::from_value(&out.value)));
                }
                Err(e) => profiles_new = Some(Loadable::Failed(e)),
            }
        }
    }

    // Derived-view expectations get their verdict from the fresh
    // payloads; a failed file verify already decided the outcome.
    let routes_data = routes_new.as_ref().and_then(|l| match l {
        Loadable::Ready(d) => Some(d),
        _ => None,
    });
    let profiles_data = profiles_new.as_ref().and_then(|l| match l {
        Loadable::Ready(d) => Some(d),
        _ => None,
    });
    let outcome = outcome.and_then(|mut proofs| {
        for ex in &spec.expects {
            if ex.needs_routes() || ex.needs_profiles() {
                proofs.push(eval_derived_expect(ex, routes_data, profiles_data)?);
            }
        }
        Ok(proofs)
    });

    let store = *store;
    let label = spec.label.clone();
    let form_id = spec.form_id;
    let done_outcome = match &outcome {
        Ok(proofs) => Ok(format!("verified: {}", proofs.join("; "))),
        Err(e) => Err(e.clone()),
    };
    let journal_outcome = done_outcome.clone();
    wake.post(move || {
        store.end_busy(op);
        store.cfg.set(Loadable::Ready(mirror.clone()));
        if let Some(r) = routes_new.clone() {
            store.routes.set(r);
        }
        if let Some(p) = profiles_new.clone() {
            store.profiles.set(p);
        }
        if let Some(fb) = fallback_new.clone() {
            store.python_fallback.set(fb);
        }
        store.push_journal(JournalEntry {
            when: crate::store::now_hms(),
            action: label.clone(),
            outcome: journal_outcome.clone(),
        });
        match &journal_outcome {
            Ok(v) => store.notice.set(Some(format!("✓ {label} — {v}"))),
            Err(e) => store.notice.set(Some(format!("✗ {label} — {e}"))),
        }
    });
    // The sink marshals to the UI thread itself (lib.rs builds it over
    // wake.post) — calling it here on the worker is the contract.
    if let Some(fid) = form_id {
        done(fid, done_outcome);
    }
}

/// The confirmed stored row, in the ONE sentence both consoles print
/// after a route write: what the store now holds and where it applies.
fn route_proof(row: &crate::store::RouteRow) -> String {
    let mut out = row.pair_text();
    if let Some(r) = row.reasoning.as_deref() {
        out.push_str(&format!(" · reasoning {r}"));
    }
    if !row.source.is_empty() {
        out.push_str(&format!(" (source: {})", row.source));
    }
    out
}

/// One derived-view expectation over the FRESH payloads — pure, so the
/// verification the routes/profiles writes rely on is unit-testable
/// (M2 review: this lane had zero coverage).
pub(crate) fn eval_derived_expect(
    ex: &Expect,
    routes: Option<&RoutesData>,
    profiles: Option<&ProfilesData>,
) -> Result<String, String> {
    match ex {
        Expect::RouteEq {
            key,
            provider,
            model,
            reasoning,
        } => {
            let row = routes
                .and_then(|d| d.rows.iter().find(|r| &r.key == key))
                .ok_or_else(|| {
                    format!("route {key} not found in the fresh view (CLI reload failed?)")
                })?;
            // A partial update verifies EXACTLY what it named. A field
            // the write left to the store is not evidence either way,
            // and an emptied field ("" was sent) must read as absent.
            let sent = |want: &Option<String>, got: &Option<String>| -> bool {
                match want.as_deref() {
                    None => true,
                    Some("") => got.is_none(),
                    Some(v) => got.as_deref() == Some(v),
                }
            };
            let cleared_all = [provider, model, reasoning]
                .iter()
                .all(|f| matches!(f.as_deref(), None | Some("")));
            if (!row.configured && !cleared_all)
                || !sent(provider, &row.provider)
                || !sent(model, &row.model)
                || !sent(reasoning, &row.reasoning)
            {
                return Err(format!(
                    "route {key} verifies as {} (configured: {})",
                    route_proof(row),
                    row.configured
                ));
            }
            Ok(format!("{key} = {}", route_proof(row)))
        }
        Expect::RouteCleared { key } => {
            match routes.and_then(|d| d.rows.iter().find(|r| &r.key == key)) {
                Some(r) if !r.configured => Ok(format!("route {key} cleared")),
                Some(_) => Err(format!("route {key} is still configured")),
                None => Err(format!(
                    "route {key} not found in the fresh view (CLI reload failed?)"
                )),
            }
        }
        Expect::ProfileExists { id } => {
            if profiles.is_some_and(|d| d.profiles.iter().any(|p| &p.id == id)) {
                Ok(format!("profile {id} present"))
            } else {
                Err(format!("profile {id} not present in the fresh view"))
            }
        }
        Expect::ProfileAbsent { id } => {
            if profiles.is_some_and(|d| d.profiles.iter().any(|p| &p.id == id)) {
                Err(format!("profile {id} still present"))
            } else {
                Ok(format!("profile {id} gone"))
            }
        }
        other => Err(format!("not a derived expectation: {other:?}")),
    }
}

/// Pre-checks + verbs + FILE verification. Route/profile verification
/// happens in the caller over the fresh derived views.
fn execute_write(
    config_path: &ConfigPath,
    cli: Option<&CoreCli>,
    spec: &WriteSpec,
) -> Result<Vec<String>, String> {
    // A spec with CLI verbs and no CLI refuses UP FRONT — before ANY
    // verb applies. The alternative (failing at the CLI verb's turn)
    // half-applies multi-verb specs and reports an error that implies
    // nothing happened (M2 review P2-2).
    let has_cli_verb = spec
        .verbs
        .iter()
        .any(|v| matches!(v, WriteVerb::Cli(_) | WriteVerb::ApplyRecommended(_)));
    if has_cli_verb && cli.is_none() {
        return Err(
            "abstractcore CLI not found — this write needs it ($ABSTRACTCORE_CLI); \
             nothing was changed"
                .into(),
        );
    }
    // 1. Refuse-unless-writable, on a FRESH read (risk-map fact #4:
    // never write over corrupt; plus the drift guard — no lock exists,
    // whole-file rewrites are last-writer-wins).
    let (state, _) = config::load_with_raw(&config_path.path);
    match &state {
        FileState::Corrupt { .. } => {
            return Err(
                "the config file is CORRUPT — writes are disabled until it is fixed \
                 (see the Overview for backups)"
                    .into(),
            )
        }
        FileState::Unreadable { error } => {
            return Err(format!("the config file is unreadable: {error}"))
        }
        FileState::Ready(snap) => {
            if has_cli_verb && !snap.python_refusals.is_empty() {
                // A CLI setter against a Python-refused file LOADS
                // DEFAULTS then SAVES — the historical data-loss
                // incident, executed by us. Structurally refused.
                return Err(format!(
                    "Python refuses this file ({}) — a CLI write would RESET it to defaults; \
                     fix the named rows first (Overview)",
                    snap.python_refusals.first().cloned().unwrap_or_default()
                ));
            }
            if spec.base_stamp != snap.stamp {
                return Err(
                    "the file changed since you loaded it — press r to reload, review, \
                     then retry"
                        .into(),
                );
            }
        }
        FileState::Missing => {
            if spec.base_stamp.is_some() {
                return Err(
                    "the config file DISAPPEARED since you loaded it — press r to reload".into(),
                );
            }
        }
    }

    // 2. Verbs, in order. A reporting verb's lines lead the proofs.
    let mut reports: Vec<String> = Vec::new();
    for verb in &spec.verbs {
        match verb {
            WriteVerb::Cli(args) => {
                let cli = cli.expect("pre-checked above");
                let argv: Vec<&str> = args.iter().map(Arg::value).collect();
                let warnings = cli
                    .run_setter(&argv, &spec.label, WRITE_TIMEOUT)
                    .map_err(|e| e.to_string())?;
                if let Some(w) = warnings.first() {
                    // The pre-check makes this unreachable in theory;
                    // if Python still fell back mid-write, the file
                    // may now be defaults+this-change — say so loudly.
                    return Err(format!(
                        "Python reported #FALLBACK during the write — the file may have been \
                         RESET; press r and inspect immediately ({w})"
                    ));
                }
            }
            WriteVerb::ApplyRecommended(args) => {
                let cli = cli.expect("pre-checked above");
                let argv: Vec<&str> = args.iter().map(Arg::value).collect();
                let out = cli
                    .run_json(&argv, WRITE_TIMEOUT)
                    .map_err(|e| e.to_string())?;
                if let Some(w) = out.fallback_warnings.first() {
                    return Err(format!(
                        "Python reported #FALLBACK during the write — the file may have been \
                         RESET; press r and inspect immediately ({w})"
                    ));
                }
                reports.extend(crate::writes::apply_report_lines(&out.value)?);
            }
            WriteVerb::Rmw(op) => rmw_write(config_path, op)?,
        }
    }

    // 3. Verify every FILE expectation against a fresh re-read.
    let (_, raw) = config::load_with_raw(&config_path.path);
    let raw = raw.ok_or("post-write re-read failed — the file is missing or corrupt now?!")?;
    let mut proofs = reports;
    for ex in &spec.expects {
        if ex.needs_routes() || ex.needs_profiles() {
            continue;
        }
        proofs.push(eval_file_expect(&raw, ex)?);
    }
    Ok(proofs)
}

/// Direct read-modify-write: fresh read (unknown keys ride along in
/// the raw value), mutate, write via a UNIQUE tmp name + rename, 0600.
/// (Python uses a fixed `<file>.tmp` — sharing it would interleave
/// writers.)
fn rmw_write(config_path: &ConfigPath, op: &crate::writes::RmwOp) -> Result<(), String> {
    let path = &config_path.path;
    let (state, raw) = config::load_with_raw(path);
    let mut raw = match (&state, raw) {
        (FileState::Ready(_), Some(raw)) => raw,
        (FileState::Missing, _) => Value::Object(Default::default()),
        _ => return Err("the file is not writable in its current state".into()),
    };
    op.apply(&mut raw)?;

    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
    }
    let mut bytes = serde_json::to_vec_pretty(&raw).map_err(|e| e.to_string())?;
    bytes.push(b'\n'); // Python writes a trailing newline
    let tmp = path.with_file_name(format!(
        "{}.tmp-console-{}",
        path.file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("abstractcore.json"),
        std::process::id()
    ));
    std::fs::write(&tmp, &bytes).map_err(|e| format!("write {} failed: {e}", tmp.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600))
            .map_err(|e| format!("chmod failed: {e}"))?;
    }
    std::fs::rename(&tmp, path).map_err(|e| {
        let _ = std::fs::remove_file(&tmp);
        format!("rename into place failed: {e}")
    })?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
    }
    Ok(())
}

fn load_derived(
    store: &Store,
    wake: &WakeHandle,
    cli: Option<&CoreCli>,
    label: &str,
    args: &[&str],
    apply: impl FnOnce(&Store, Result<serde_json::Value, CliError>) + Send + 'static,
) {
    let Some(cli) = cli else {
        let store = *store;
        wake.post(move || {
            apply(&store, Err(no_cli_error()));
        });
        return;
    };
    let op = next_op();
    begin(store, wake, op, label);
    let action = format!("abstractcore {}", args.join(" "));
    let outcome = cli.run_json(args, READ_TIMEOUT);
    let journal = match &outcome {
        Ok(_) => Ok("ok".to_string()),
        Err(e) => Err(e.to_string()),
    };
    let store = *store;
    wake.post(move || {
        store.end_busy(op);
        // Reads journal only on failure — a green load is not an event
        // worth a journal row, a red one is.
        if journal.is_err() {
            store.push_journal(JournalEntry {
                when: crate::store::now_hms(),
                action,
                outcome: journal,
            });
        }
        // The P1-1 lane: an exit-0 run that printed `#FALLBACK` means
        // Python REFUSED the config file and answered from defaults —
        // record it (both loads hit the same file, so last-write-wins
        // is one consistent truth), or clear it on a clean run.
        if let Ok(out) = &outcome {
            store
                .python_fallback
                .set(out.fallback_warnings.first().cloned());
        }
        apply(&store, outcome.map(|o| o.value));
    });
}

fn begin(store: &Store, wake: &WakeHandle, op: u64, label: &str) {
    let store = *store;
    let label = label.to_string();
    wake.post(move || store.begin_busy(op, &label));
}

fn panic_text(p: &Box<dyn std::any::Any + Send>) -> String {
    p.downcast_ref::<&str>()
        .map(|s| s.to_string())
        .or_else(|| p.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "panic".into())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{resolve_config_path, PathSource};
    use crate::writes::{Expect, RmwOp};
    use serde_json::json;
    use std::path::PathBuf;

    /// The final `host_job_v1` line of a streamed download carries the
    /// legacy `results`; a job without them still yields its own status.
    #[test]
    fn download_outcome_reads_the_final_job_line() {
        let legacy = json!({"schema": "host_job_v1", "status": "completed", "ok": true,
            "results": [{"status": "downloaded", "message": "qwen3:8b ready"}]});
        assert_eq!(
            download_outcome(&legacy),
            ("downloaded".to_string(), "qwen3:8b ready".to_string())
        );
        let job_only = json!({"schema": "host_job_v1", "status": "cancelled",
            "message": "cancelled by operator", "results": []});
        assert_eq!(
            download_outcome(&job_only),
            ("cancelled".to_string(), "cancelled by operator".to_string())
        );
        let with_result = json!({"status": "completed", "result": {"status": "present"}});
        assert_eq!(download_outcome(&with_result).0, "present");
    }

    struct Scratch {
        dir: PathBuf,
    }

    impl Scratch {
        fn new(tag: &str) -> Scratch {
            let dir = std::env::temp_dir().join(format!(
                "acc-worker-{tag}-{}-{}",
                std::process::id(),
                OP_ID.fetch_add(1, Ordering::Relaxed)
            ));
            std::fs::create_dir_all(&dir).unwrap();
            Scratch { dir }
        }
        fn cfg_path(&self) -> ConfigPath {
            ConfigPath {
                path: self.dir.join("abstractcore.json"),
                source: PathSource::Default,
            }
        }
        fn write(&self, v: &serde_json::Value) {
            std::fs::write(self.cfg_path().path, serde_json::to_vec_pretty(v).unwrap()).unwrap();
        }
        fn read(&self) -> serde_json::Value {
            serde_json::from_slice(&std::fs::read(self.cfg_path().path).unwrap()).unwrap()
        }
        fn stamp(&self) -> Option<crate::config::FileStamp> {
            crate::config::FileStamp::of(&self.cfg_path().path)
        }
        /// A fake abstractcore: a shell script so the CLI verb lane is
        /// testable without Python. `body` sees the argv.
        fn fake_cli(&self, body: &str) -> CoreCli {
            let p = self.dir.join("fake-abstractcore");
            std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
            }
            CoreCli::new(p)
        }
    }

    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.dir);
        }
    }

    fn spec_rmw(
        op: RmwOp,
        expects: Vec<Expect>,
        base: Option<crate::config::FileStamp>,
    ) -> WriteSpec {
        WriteSpec {
            label: "test rmw".into(),
            verbs: vec![WriteVerb::Rmw(op)],
            expects,
            base_stamp: base,
            form_id: None,
        }
    }

    #[test]
    fn rmw_write_preserves_unknown_keys_and_verifies() {
        let s = Scratch::new("rmw");
        s.write(&json!({
            "future_section": {"keep": 1},
            "logging": {"verbatim_enabled": true, "unknown_knob": "x"},
        }));
        let base = s.stamp();
        let spec = spec_rmw(
            RmwOp::SetField {
                section: "logging".into(),
                key: "verbatim_enabled".into(),
                value: json!(false),
            },
            vec![Expect::Eq {
                path: vec!["logging".into(), "verbatim_enabled".into()],
                value: json!(false),
            }],
            base,
        );
        let proofs = execute_write(&s.cfg_path(), None, &spec).expect("write ok");
        assert!(proofs[0].contains("verbatim_enabled = false"), "{proofs:?}");
        let after = s.read();
        assert_eq!(
            after["future_section"]["keep"],
            json!(1),
            "unknown section kept"
        );
        assert_eq!(
            after["logging"]["unknown_knob"],
            json!("x"),
            "unknown key kept"
        );
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(s.cfg_path().path)
                .unwrap()
                .permissions()
                .mode()
                & 0o777;
            assert_eq!(mode, 0o600, "write keeps the file private");
        }
    }

    #[test]
    fn drift_guard_refuses_and_leaves_the_file_alone() {
        let s = Scratch::new("drift");
        s.write(&json!({"video": {"max_frames": 3}}));
        // A stale base identity (someone else wrote since the UI loaded).
        let stale = Some(crate::config::FileStamp {
            mtime: Some(std::time::SystemTime::UNIX_EPOCH),
            ino: 1,
            size: 1,
        });
        let spec = spec_rmw(
            RmwOp::SetField {
                section: "video".into(),
                key: "max_frames".into(),
                value: json!(9),
            },
            vec![],
            stale,
        );
        let err = execute_write(&s.cfg_path(), None, &spec).unwrap_err();
        assert!(err.contains("changed since you loaded"), "{err}");
        assert_eq!(s.read()["video"]["max_frames"], json!(3), "untouched");
    }

    #[test]
    fn corrupt_file_refuses_all_writes() {
        let s = Scratch::new("corrupt");
        std::fs::write(s.cfg_path().path, b"{ not json").unwrap();
        let spec = spec_rmw(
            RmwOp::SetField {
                section: "video".into(),
                key: "max_frames".into(),
                value: json!(9),
            },
            vec![],
            None,
        );
        let err = execute_write(&s.cfg_path(), None, &spec).unwrap_err();
        assert!(err.contains("CORRUPT"), "{err}");
        assert_eq!(std::fs::read(s.cfg_path().path).unwrap(), b"{ not json");
    }

    #[test]
    fn python_refused_file_blocks_cli_verbs_but_not_rmw() {
        let s = Scratch::new("refused");
        s.write(&json!({
            "provider_profiles": {"profiles": {"p": {"id": "p", "future_field": true}}},
            "logging": {"verbatim_enabled": true},
        }));
        let base = s.stamp();
        // A CLI verb would make Python load defaults + save = the
        // incident. Refused.
        let cli_spec = WriteSpec {
            label: "cli write".into(),
            verbs: vec![WriteVerb::Cli(vec![
                Arg::p("--set-video-strategy"),
                Arg::p("auto"),
            ])],
            expects: vec![],
            base_stamp: base,
            form_id: None,
        };
        let fake = s.fake_cli("echo should-not-run; exit 0");
        let err = execute_write(&s.cfg_path(), Some(&fake), &cli_spec).unwrap_err();
        assert!(err.contains("RESET it to defaults"), "{err}");

        // RMW preserves everything — allowed even on a refused file.
        let rmw = spec_rmw(
            RmwOp::SetField {
                section: "logging".into(),
                key: "verbatim_enabled".into(),
                value: json!(false),
            },
            vec![Expect::Eq {
                path: vec!["logging".into(), "verbatim_enabled".into()],
                value: json!(false),
            }],
            base,
        );
        execute_write(&s.cfg_path(), None, &rmw).expect("rmw allowed");
        let after = s.read();
        assert_eq!(
            after["provider_profiles"]["profiles"]["p"]["future_field"],
            json!(true),
            "the refused row is preserved, not dropped"
        );
    }

    #[test]
    fn cli_verb_runs_and_verify_catches_lies() {
        let s = Scratch::new("cli");
        s.write(&json!({"video": {"max_frames": 3}}));
        let base = s.stamp();
        let cfg = s.cfg_path();

        // An honest fake setter: mutates the file like Python would.
        let honest = s.fake_cli(&format!(
            "python3 -c \"import json; p='{}'; v=json.load(open(p)); \
             v['video']['max_frames']=9; json.dump(v, open(p,'w'))\"",
            cfg.path.display()
        ));
        let spec = WriteSpec {
            label: "set video.max_frames = 9".into(),
            verbs: vec![WriteVerb::Cli(vec![
                Arg::p("--set-video-max-frames"),
                Arg::p("9"),
            ])],
            expects: vec![Expect::Eq {
                path: vec!["video".into(), "max_frames".into()],
                value: json!(9),
            }],
            base_stamp: base,
            form_id: None,
        };
        let proofs = execute_write(&cfg, Some(&honest), &spec).expect("verified");
        assert!(proofs[0].contains("max_frames = 9"));

        // A LYING setter (exit 0, ❌ line, no write) — the probed
        // --set-server-port class. Caught before verify.
        s.write(&json!({"video": {"max_frames": 3}}));
        let liar = s.fake_cli("echo '❌ Error: Invalid value'; exit 0");
        let spec2 = WriteSpec {
            base_stamp: s.stamp(),
            ..spec.clone()
        };
        let err = execute_write(&cfg, Some(&liar), &spec2).unwrap_err();
        assert!(err.contains("Invalid value"), "{err}");

        // A SILENT liar (✅, exit 0, writes nothing) — the probed
        // --set-app-default class. Caught by verify-by-re-read.
        let silent = s.fake_cli("echo '✅ Set'; exit 0");
        let spec3 = WriteSpec {
            base_stamp: s.stamp(),
            ..spec
        };
        let err = execute_write(&cfg, Some(&silent), &spec3).unwrap_err();
        assert!(err.contains("is 3 (expected 9)"), "{err}");
    }

    /// `a` on Routes: the CLI's apply report IS the outcome the journal
    /// carries — every route, the `unavailable` one with its reason. The
    /// lane used to run the verb as a plain setter and throw the report
    /// away ("verified: " and nothing else).
    #[test]
    fn apply_recommended_journals_the_cli_report() {
        let s = Scratch::new("apply");
        s.write(&json!({}));
        let cfg = s.cfg_path();
        let report = json!({"ok": true, "dry_run": false, "force": false, "routes": [
            {"key": "input.text", "action": "already",
             "after": {"provider": "lmstudio", "model": "qwen/qwen3.5-9b"}},
            {"key": "output.image", "action": "unavailable", "before": {},
             "reason": "MLX-Gen needs Apple silicon"}
        ]});
        let cli = s.fake_cli(&format!(
            "echo \"$*\" > '{}/argv'; cat <<'EOF'\n{}\nEOF",
            s.dir.display(),
            serde_json::to_string_pretty(&report).unwrap()
        ));
        let spec = crate::writes::apply_recommended(false, s.stamp(), None);
        let proofs = execute_write(&cfg, Some(&cli), &spec).expect("applied");
        assert_eq!(
            proofs,
            vec![
                "input.text: already lmstudio · qwen/qwen3.5-9b".to_string(),
                "output.image: nothing recommended runs on this computer — MLX-Gen needs \
                 Apple silicon; left unset"
                    .to_string(),
            ]
        );
        let argv = std::fs::read_to_string(s.dir.join("argv")).unwrap();
        assert_eq!(argv.trim(), "config apply-recommended --json");

        // A non-report answer is a FAILURE, never a silent "done".
        let prose = s.fake_cli("echo 'Applied the recommended capability defaults'");
        let spec = crate::writes::apply_recommended(true, s.stamp(), None);
        let err = execute_write(&cfg, Some(&prose), &spec).unwrap_err();
        assert!(err.contains("Applied the recommended"), "{err}");
    }

    #[test]
    fn missing_file_writes_create_it() {
        let s = Scratch::new("missing");
        let spec = spec_rmw(
            RmwOp::SetField {
                section: "offline".into(),
                key: "allow_network".into(),
                value: json!(true),
            },
            vec![Expect::Eq {
                path: vec!["offline".into(), "allow_network".into()],
                value: json!(true),
            }],
            None, // Missing file = no base mtime
        );
        execute_write(&s.cfg_path(), None, &spec).expect("created");
        assert_eq!(s.read()["offline"]["allow_network"], json!(true));
    }

    #[test]
    fn resolve_helpers_are_reachable() {
        // Anchor: the worker's path type matches the resolver's.
        let p = resolve_config_path(&|_| None, std::path::Path::new("/home/u"));
        assert_eq!(p.source, PathSource::Default);
    }

    /// The M2-review P1 pin: the fallback-chain builders' array-index
    /// expectations must evaluate against the REAL post-write file —
    /// the walker used to return None for every numeric segment
    /// (false-fail on add, vacuous-pass on remove).
    #[test]
    fn fallback_chain_writes_verify_with_array_paths() {
        let s = Scratch::new("chain");
        s.write(&json!({"vision": {"fallback_chain": [
            {"provider": "ollama", "model": "llava2"}
        ]}}));
        // Add: an honest fake that appends like Python does.
        let cfg = s.cfg_path();
        let honest = s.fake_cli(&format!(
            "python3 -c \"import json; p='{}'; v=json.load(open(p)); \
             v['vision']['fallback_chain'].append({{'provider':'lmstudio','model':'qwen-vl'}}); \
             json.dump(v, open(p,'w'))\"",
            cfg.path.display()
        ));
        let spec = crate::writes::add_vision_fallback("lmstudio", "qwen-vl", 2, s.stamp(), None);
        let proofs = execute_write(&cfg, Some(&honest), &spec)
            .expect("a landed add VERIFIES (was: false-fail on every add)");
        assert!(
            proofs[0].contains("fallback_chain.1.provider"),
            "{proofs:?}"
        );

        // Remove: the RMW op + a REAL check that the slot is gone —
        // and the inverse: a remove whose expectation is checked
        // against a file where the entry survived must FAIL.
        let spec = crate::writes::remove_vision_fallback(1, 2, s.stamp(), None);
        execute_write(&cfg, None, &spec).expect("remove verifies");
        let after = s.read();
        assert_eq!(
            after["vision"]["fallback_chain"].as_array().unwrap().len(),
            1
        );

        // Vacuous-pass guard: expecting slot 0 cleared while it still
        // exists must error.
        let bogus = spec_rmw(
            RmwOp::SetField {
                section: "audio".into(),
                key: "stt_language".into(),
                value: json!("fr"),
            },
            vec![Expect::Cleared {
                path: vec![
                    "vision".into(),
                    "fallback_chain".into(),
                    "0".into(),
                    "provider".into(),
                ],
            }],
            s.stamp(),
        );
        let err = execute_write(&cfg, None, &bogus).unwrap_err();
        assert!(err.contains("still holds"), "{err}");
    }

    /// #FALLBACK printed to stderr DURING a write = Python refused the
    /// file mid-write (the reset case) — the last line of defense for
    /// the historical incident must fire loudly (was: zero coverage).
    #[test]
    fn fallback_stderr_during_a_write_fails_loudly() {
        let s = Scratch::new("fbwrite");
        s.write(&json!({"video": {"max_frames": 3}}));
        let fake = s.fake_cli(
            "echo '#FALLBACK abstractcore config could not be parsed; falling back to \
             DEFAULTS' >&2; echo '✅ Set'; exit 0",
        );
        let spec = WriteSpec {
            label: "set video.max_frames = 9".into(),
            verbs: vec![WriteVerb::Cli(vec![
                Arg::p("--set-video-max-frames"),
                Arg::p("9"),
            ])],
            expects: vec![],
            base_stamp: s.stamp(),
            form_id: None,
        };
        let err = execute_write(&s.cfg_path(), Some(&fake), &spec).unwrap_err();
        assert!(err.contains("may have been RESET"), "{err}");
        assert!(err.contains("press r and inspect"), "{err}");
    }

    /// A nonzero-exit setter (argparse refusals: the leading-dash
    /// class) surfaces its error through execute_write.
    #[test]
    fn nonzero_exit_setter_fails_through_the_lane() {
        let s = Scratch::new("exit2");
        s.write(&json!({"video": {"max_frames": 3}}));
        let fake = s.fake_cli("echo 'error: expected one argument' >&2; exit 2");
        let spec = WriteSpec {
            label: "set something".into(),
            verbs: vec![WriteVerb::Cli(vec![Arg::p("--set-video-max-frames")])],
            expects: vec![],
            base_stamp: s.stamp(),
            form_id: None,
        };
        let err = execute_write(&s.cfg_path(), Some(&fake), &spec).unwrap_err();
        assert!(err.contains("expected one argument"), "{err}");
    }

    /// Multi-verb order (M2 review P2-2): the fallible CLI half of
    /// clear_global_default runs FIRST; with no CLI available the spec
    /// refuses UP FRONT and the RMW half never applies.
    #[test]
    fn clear_global_default_is_cli_first_and_refuses_without_cli() {
        let spec = crate::writes::clear_global_default(None, None);
        assert!(
            matches!(spec.verbs[0], WriteVerb::Cli(_)),
            "CLI verb first: {:?}",
            spec.verbs
        );
        assert!(matches!(spec.verbs[1], WriteVerb::Rmw(_)));

        let s = Scratch::new("noclip");
        s.write(&json!({"default_models": {"global_provider": "lmstudio",
                                             "global_model": "m"}}));
        let spec = crate::writes::clear_global_default(s.stamp(), None);
        let err = execute_write(&s.cfg_path(), None, &spec).unwrap_err();
        assert!(err.contains("nothing was changed"), "{err}");
        assert_eq!(
            s.read()["default_models"]["global_provider"],
            json!("lmstudio"),
            "the RMW half must NOT have applied"
        );
    }

    /// The derived-view verification fold, unit-tested (M2 review:
    /// this lane had zero coverage).
    #[test]
    fn derived_expects_evaluate_against_fresh_views() {
        let routes = RoutesData::from_value(&json!({
            "ok": true, "routes": [
                {"key": "input.text", "provider": "lmstudio", "model": "m",
                 "configured": true, "kind": "input", "modality": "text",
                 "label": "Text Input", "source": "x"},
                {"key": "input.voice", "configured": false, "kind": "input",
                 "modality": "voice", "label": "Voice", "source": "not_configured"}
            ]
        }));
        let profiles = ProfilesData::from_value(&json!({
            "ok": true, "profiles": [{"id": "acme"}]
        }));

        let ok = eval_derived_expect(
            &Expect::RouteEq {
                key: "input.text".into(),
                provider: Some("lmstudio".into()),
                model: Some("m".into()),
                reasoning: None,
            },
            Some(&routes),
            None,
        )
        .unwrap();
        assert!(
            ok.contains("input.text = lmstudio / m") && ok.contains("(source: x)"),
            "the proof shows the confirmed row AND where it applies: {ok}"
        );

        let err = eval_derived_expect(
            &Expect::RouteEq {
                key: "input.text".into(),
                provider: Some("ollama".into()),
                model: None,
                reasoning: None,
            },
            Some(&routes),
            None,
        )
        .unwrap_err();
        assert!(err.contains("verifies as lmstudio / m"), "{err}");

        // A PARTIAL update verifies only what it named: naming just the
        // reasoning must not fail because provider/model went unsent.
        let routes_reasoned = RoutesData::from_value(&json!({
            "ok": true, "routes": [
                {"key": "input.text", "provider": "lmstudio", "model": "m",
                 "reasoning": "high", "configured": true, "kind": "input",
                 "modality": "text", "label": "Text Input", "source": "x"}
            ]
        }));
        let only_reasoning = |want: &str| Expect::RouteEq {
            key: "input.text".into(),
            provider: None,
            model: None,
            reasoning: Some(want.into()),
        };
        let ok =
            eval_derived_expect(&only_reasoning("high"), Some(&routes_reasoned), None).unwrap();
        assert!(ok.contains("reasoning high"), "{ok}");
        assert!(
            eval_derived_expect(&only_reasoning("low"), Some(&routes_reasoned), None).is_err(),
            "a reasoning the store did not take must fail the write"
        );
        // "" was sent = clear it: the row must carry NO reasoning.
        assert!(
            eval_derived_expect(&only_reasoning(""), Some(&routes_reasoned), None).is_err(),
            "a cleared field that survived is a failed write"
        );
        assert!(
            eval_derived_expect(&only_reasoning(""), Some(&routes), None).is_ok(),
            "a cleared field that is gone verifies"
        );

        assert!(eval_derived_expect(
            &Expect::RouteCleared {
                key: "input.voice".into()
            },
            Some(&routes),
            None
        )
        .is_ok());
        assert!(eval_derived_expect(
            &Expect::RouteCleared {
                key: "input.text".into()
            },
            Some(&routes),
            None
        )
        .is_err());
        // A missing fresh view is an honest failure, not a pass.
        assert!(eval_derived_expect(
            &Expect::RouteCleared {
                key: "input.text".into()
            },
            None,
            None
        )
        .is_err());

        assert!(eval_derived_expect(
            &Expect::ProfileExists { id: "acme".into() },
            None,
            Some(&profiles)
        )
        .is_ok());
        assert!(eval_derived_expect(
            &Expect::ProfileAbsent { id: "acme".into() },
            None,
            Some(&profiles)
        )
        .is_err());
        assert!(eval_derived_expect(
            &Expect::ProfileAbsent { id: "gone".into() },
            None,
            Some(&profiles)
        )
        .is_ok());
    }

    // -----------------------------------------------------------------
    // The probe lane (M3).
    // -----------------------------------------------------------------

    impl Scratch {
        /// A CoreCli whose CHAT binary is a controlled script — the
        /// generation probe's mechanics without any real model.
        fn fake_chat(&self, body: &str) -> CoreCli {
            let p = self.dir.join("fake-abstractcore-chat");
            std::fs::write(&p, format!("#!/bin/sh\n{body}\n")).unwrap();
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
            }
            CoreCli {
                bin: self.dir.join("unused-abstractcore"),
                chat_bin: Some(p),
                chat_from_path: false,
            }
        }
    }

    /// The default-route probe must test the OPERATOR'S route, never
    /// the chat CLI's silent built-in fallback (live-probed: an empty
    /// config generates via an invented huggingface default).
    #[test]
    fn generation_probe_refuses_without_a_default_route() {
        let s = Scratch::new("probe-nodefault");
        s.write(&json!({"version": "1.0"}));
        let cli = s.fake_chat("echo SHOULD-NEVER-RUN");
        let (v, d) = probe_generation(&s.cfg_path(), &cli, None, None);
        assert_eq!(v, crate::probes::Verdict::Failed);
        assert!(d.contains("no default route configured"), "{d}");
        assert!(d.contains("wizard"), "teaches the fix: {d}");

        // A MISSING file is the same honest refusal (fresh machine).
        let s2 = Scratch::new("probe-missing");
        let (v, d) = probe_generation(&s2.cfg_path(), &cli, None, None);
        assert_eq!(v, crate::probes::Verdict::Failed);
        assert!(d.contains("no default route configured"), "{d}");
    }

    /// The chat CLI's liar class (exit 0 + ❌ on stdout) fails the
    /// probe; a real reply proves it; the configured default resolves
    /// from the FILE into the argv and the detail label.
    #[test]
    fn generation_probe_folds_reply_and_exit0_error() {
        let s = Scratch::new("probe-gen");
        s.write(&json!({"default_models": {
            "global_provider": "lmstudio", "global_model": "m1"}}));

        let lying = s.fake_chat("echo '❌ Error: API error: Connection refused'");
        let (v, d) = probe_generation(&s.cfg_path(), &lying, None, None);
        assert_eq!(v, crate::probes::Verdict::Failed);
        assert!(d.contains("Connection refused"), "{d}");

        // The happy fake echoes its argv tail so the assert can prove
        // the FILE's default reached the command line.
        let honest = s.fake_chat("echo \"PONG from $2/$4\"");
        let (v, d) = probe_generation(&s.cfg_path(), &honest, None, None);
        assert_eq!(v, crate::probes::Verdict::Proven, "{d}");
        assert!(
            d.starts_with("lmstudio/m1 — "),
            "label carries the route: {d}"
        );
        assert!(d.contains("PONG from lmstudio/m1"), "{d}");

        // Explicit pair overrides the file.
        let (v, d) = probe_generation(&s.cfg_path(), &honest, Some("ollama"), Some("x"));
        assert_eq!(v, crate::probes::Verdict::Proven);
        assert!(d.starts_with("ollama/x — "), "{d}");

        // No chat binary: honest teaching refusal.
        let bare = CoreCli::bare(s.dir.join("unused"));
        let (v, d) = probe_generation(&s.cfg_path(), &bare, None, None);
        assert_eq!(v, crate::probes::Verdict::Failed);
        assert!(d.contains("abstractcore-chat not found"), "{d}");
    }

    /// The endpoint-default lane (M3 review P1-1): the chat CLI's
    /// argparse knows no `endpoint:` providers, so a keyless profile
    /// expands to `--provider <family> --base-url <url>`; keyed,
    /// disabled and missing profiles resolve without running the
    /// binary — a Failed verdict on a working route is a lie.
    #[test]
    fn generation_probe_expands_keyless_endpoint_profiles() {
        let s = Scratch::new("probe-endpoint");
        let profile = |api_key: &str, env_var: &str, enabled: bool| {
            json!({
                "default_models": {"global_provider": "endpoint:lab", "global_model": "m9"},
                "provider_profiles": {"profiles": {"lab": {
                    "id": "lab", "provider_family": "lmstudio",
                    "base_url": "http://localhost:9999/v1",
                    "api_key": api_key, "api_key_env_var": env_var,
                    "enabled": enabled}}}
            })
        };

        // Keyless + enabled: expands — the fake echoes argv so the
        // assert proves family + base_url REACHED THE COMMAND LINE
        // (the "via …" note alone is worker-constructed).
        s.write(&profile("", "", true));
        let honest = s.fake_chat("echo \"GEN $2 $4 $9 ${10}\"");
        let (v, d) = probe_generation(&s.cfg_path(), &honest, None, None);
        assert_eq!(v, crate::probes::Verdict::Proven, "{d}");
        assert!(
            d.starts_with("endpoint:lab/m9 — "),
            "the ROUTE stays the label: {d}"
        );
        assert!(
            d.contains("GEN lmstudio m9 --base-url"),
            "argv carried the expansion: {d}"
        );
        assert!(
            d.contains("via lmstudio @ http://localhost:9999/v1"),
            "expansion disclosed: {d}"
        );

        // Keyed profile: refused as NOT PROVEN (argv must never carry
        // secrets; a guessed key lane would mint 401 lies).
        s.write(&profile("sk-secret", "", true));
        let never = s.fake_chat("echo SHOULD-NEVER-RUN");
        let (v, d) = probe_generation(&s.cfg_path(), &never, None, None);
        assert_eq!(v, crate::probes::Verdict::NotProven);
        assert!(d.contains("cannot receive"), "{d}");
        assert!(!d.contains("sk-secret"), "the key never echoes: {d}");

        // $VAR-referenced keys refuse the same way.
        s.write(&profile("", "LAB_KEY", true));
        let (v, _) = probe_generation(&s.cfg_path(), &never, None, None);
        assert_eq!(v, crate::probes::Verdict::NotProven);

        // A profile that is not enabled: NotProven, naming the switch.
        s.write(&profile("", "", false));
        let (v, d) = probe_generation(&s.cfg_path(), &never, None, None);
        assert_eq!(v, crate::probes::Verdict::NotProven);
        assert!(
            d.contains("is not enabled") && d.contains("[x] enabled"),
            "{d}"
        );

        // A default naming a MISSING profile is a broken route: Failed.
        s.write(&json!({"default_models": {
            "global_provider": "endpoint:ghost", "global_model": "m"}}));
        let (v, d) = probe_generation(&s.cfg_path(), &never, None, None);
        assert_eq!(v, crate::probes::Verdict::Failed);
        assert!(d.contains("no such profile"), "{d}");
    }

    /// Reachability is judged over ALL resolved addresses (M3 review
    /// P1-2): `localhost` resolves `::1` first while local servers
    /// often bind IPv4 only — first-address-only probing reported
    /// "looks DOWN" for an UP server.
    #[test]
    fn reachability_connects_if_any_address_accepts() {
        use std::net::{SocketAddr, TcpListener};
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let live = listener.local_addr().unwrap();
        // A port with no listener on either family: bind + drop.
        let dead_port = {
            let l = TcpListener::bind("127.0.0.1:0").unwrap();
            l.local_addr().unwrap().port()
        };
        let dead_v6: SocketAddr = format!("[::1]:{dead_port}").parse().unwrap();
        let dead_v4: SocketAddr = format!("127.0.0.1:{dead_port}").parse().unwrap();

        // The P1-2 shape: v6 refuses FIRST, v4 accepts → Connected.
        let r = probe_addr_list(&[dead_v6, live], Duration::from_millis(800));
        assert_eq!(r, crate::probes::Reach::Connected);

        // Every address refuses → Refused, preferring the IPv4 error.
        let r = probe_addr_list(&[dead_v6, dead_v4], Duration::from_millis(800));
        assert!(matches!(r, crate::probes::Reach::Refused(_)), "{r:?}");

        // No addresses at all → honest Unresolvable.
        let r = probe_addr_list(&[], Duration::from_millis(100));
        assert!(matches!(r, crate::probes::Reach::Unresolvable(_)), "{r:?}");
    }
}