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
use super::*;

#[test]
fn openai_surface_probe_skips_plain_http_multiplexers() {
    assert!(!should_probe_openai_surface(
        newt_core::BackendKind::Openai,
        true,
        "model",
        "http://gpu-box:8000",
        Some(newt_core::Serving::Multiplexer),
    ));
    assert!(should_probe_openai_surface(
        newt_core::BackendKind::Openai,
        true,
        "model",
        "http://127.0.0.1:8000",
        Some(newt_core::Serving::Instance),
    ));
    assert!(should_probe_openai_surface(
        newt_core::BackendKind::Openai,
        true,
        "model",
        "https://inference.example.test",
        Some(newt_core::Serving::Multiplexer),
    ));
}

/// #1707/#1709: the session `coauthor_trailer` single-model function this
/// test used to exercise is gone — attribution now flows through
/// `newt_core::attribution::AttributionLedger`, recorded per-contributor by
/// the agent loop. (Commit attribution itself now flows through the canonical
/// `CommitAttribution` finalizer wired into `session_git_tool.attribution` in
/// `chat.rs`; this test exercises the ledger directly, the way the session
/// resolves identity for it.)
#[test]
fn attribution_ledger_uses_resolved_identity_email() {
    let id = newt_core::AgentIdentity::default();
    let mut ledger = newt_core::attribution::AttributionLedger::new(id.email.clone());
    ledger.record(
        "nemotron-3-nano:30b",
        "newt-agent",
        newt_core::build_info::PACKAGE_VERSION,
    );
    // Model name credits the work; the email attributes to the resolved
    // harness identity (default: GitHub User https://github.com/newt-agent).
    assert_eq!(
        ledger.render(),
        format!(
            "Co-authored-by: nemotron-3-nano:30b (v{} {}) <309460085+newt-agent@users.noreply.github.com>",
            newt_core::build_info::PACKAGE_VERSION,
            newt_core::build_info::SOURCE_ID
        )
    );
    assert!(ledger.render().contains(newt_core::DEFAULT_AGENT_EMAIL));
    assert!(
        !ledger.render().contains("noreply@newt-agent.com"),
        "old wrong email is gone"
    );
    assert!(
        !ledger.render().contains("[bot]"),
        "default attribution is the User account, not the App bot"
    );

    let custom = newt_core::AgentIdentity {
        name: "my-agent".into(),
        email: "my-agent@example.com".into(),
        ..newt_core::AgentIdentity::default()
    };
    let mut custom_ledger = newt_core::attribution::AttributionLedger::new(custom.email.clone());
    custom_ledger.record(
        "ornith:35b",
        "newt-agent",
        newt_core::build_info::PACKAGE_VERSION,
    );
    assert_eq!(
        custom_ledger.render(),
        format!(
            "Co-authored-by: ornith:35b (newt-agent v{} {}) <my-agent@example.com>",
            newt_core::build_info::PACKAGE_VERSION,
            newt_core::build_info::SOURCE_ID
        )
    );
}

#[test]
fn runtime_context_block_reports_identity_without_a_special_git_dialect() {
    let id = newt_core::AgentIdentity::default();
    let blk = runtime_context_block(
        "m",
        "http://h",
        newt_core::BackendKind::Ollama,
        &id,
        newt_core::agentic::PromptDisposition::Act,
    );
    assert!(blk.contains("newt-agent <309460085+newt-agent@users.noreply.github.com>"));
    assert!(!blk.contains("Prefer the `git` tool"));
    assert!(!blk.contains("op=amend"));
    assert!(!blk.contains("git -c user.name="));

    let custom = newt_core::AgentIdentity {
        name: "custom".into(),
        email: "custom@example.com".into(),
        ..newt_core::AgentIdentity::default()
    };
    let custom_blk = runtime_context_block(
        "m",
        "http://h",
        newt_core::BackendKind::Ollama,
        &custom,
        newt_core::agentic::PromptDisposition::Act,
    );
    assert!(custom_blk.contains("custom <custom@example.com>"));
}

#[test]
fn workspace_state_block_formats_dirty_snapshot_with_timestamp() {
    let block = format_workspace_state_block(&WorkspaceStateSnapshot {
        timestamp: "2026-07-04T21:23:45-04:00".to_string(),
        branch: Some("feat/help-rollups".to_string()),
        dirty_files: vec![
            "newt-tui/src/help_sections.rs".to_string(),
            "newt-tui/src/lib.rs".to_string(),
        ],
        git_status_available: true,
    });

    assert!(block.starts_with("<workspace_state>\ntimestamp: 2026-07-04T21:23:45-04:00"));
    assert!(block.contains("branch: feat/help-rollups"), "{block}");
    assert!(block.contains("dirty files (2):"), "{block}");
    assert!(
        block.contains("- newt-tui/src/help_sections.rs")
            && block.contains("- newt-tui/src/lib.rs"),
        "{block}"
    );
    assert!(
        block.contains("unlanded local changes exist; do not treat them as upstream-complete work"),
        "{block}"
    );
    assert!(
        block.contains("next completion step: verify, commit, push/open PR, or state blocker"),
        "{block}"
    );
}

#[test]
fn workspace_state_block_formats_clean_snapshot_without_dirty_nudge() {
    let block = format_workspace_state_block(&WorkspaceStateSnapshot {
        timestamp: "2026-07-04T21:23:45-04:00".to_string(),
        branch: Some("main".to_string()),
        dirty_files: Vec::new(),
        git_status_available: true,
    });

    assert!(block.contains("timestamp: 2026-07-04T21:23:45-04:00"));
    assert!(block.contains("branch: main"), "{block}");
    assert!(block.contains("dirty files: none"), "{block}");
    assert!(block.contains("local changes: clean"), "{block}");
    assert!(!block.contains("unlanded local changes exist"), "{block}");
}

#[test]
fn parse_git_porcelain_dirty_files_dedupes_and_tracks_rename_target() {
    let files = parse_git_porcelain_dirty_files(
        " M newt-tui/src/lib.rs\n\
             ?? docs/new file.md\n\
             R  old.rs -> src/new.rs\n\
             M  newt-tui/src/lib.rs\n",
    );

    assert_eq!(
        files,
        vec![
            "newt-tui/src/lib.rs".to_string(),
            "docs/new file.md".to_string(),
            "src/new.rs".to_string(),
        ]
    );
}

#[test]
fn bang_command_strips_and_trims_the_escape() {
    assert_eq!(bang_command("!date"), Some("date"));
    assert_eq!(bang_command("! date"), Some("date"));
    assert_eq!(bang_command("!  pa login  "), Some("pa login"));
    // A pipeline survives intact — it's handed to the shell verbatim.
    assert_eq!(bang_command("! echo hi | wc -c"), Some("echo hi | wc -c"));
}

#[test]
fn management_login_argv_is_literal_and_never_shell_expanded() {
    let argv = vec![
        "document-client".to_owned(),
        "login".to_owned(),
        "literal; argument $(no-expansion)".to_owned(),
    ];
    let command = operator_argv_command(&argv).unwrap();
    assert_eq!(command.get_program(), "document-client");
    assert_eq!(
        command.get_args().collect::<Vec<_>>(),
        vec!["login", "literal; argument $(no-expansion)"]
    );
    assert!(operator_argv_command(&[]).is_err());
    assert!(operator_argv_command(&[String::new()]).is_err());
}

#[test]
fn bang_command_ignores_non_bang_and_bare_bang() {
    assert_eq!(bang_command("date"), None, "no leading bang");
    assert_eq!(bang_command("/help"), None, "slash is not a bang");
    assert_eq!(bang_command("!"), None, "bare bang has no command");
    assert_eq!(bang_command("!   "), None, "whitespace-only is empty");
    assert_eq!(
        bang_command("the ! is mid-line"),
        None,
        "bang must lead the line"
    );
}

#[test]
#[cfg(not(windows))]
fn bang_shell_is_a_noninteractive_unix_shell() {
    let (shell, flag) = bang_shell();
    // `-c`, NOT `-ic`: an interactive shell's job control suspends newt
    // (SIGTTOU). See bang_shell docs.
    assert_eq!(flag, "-c");
    assert!(!shell.is_empty(), "a shell is always resolved");
}

// A `!`-escape must always RETURN control to newt — the hang bug was
// `.status()` blocking the TUI thread forever on a command that never
// exits. Under the test harness stdin is not a TTY, so `run_bang_escape`
// takes the non-interactive `wait` fallback; these prove that path both
// completes (no hang) and reports exit status without felling the process.
#[test]
#[cfg(not(windows))]
fn run_bang_escape_returns_on_success() {
    // `true` exits 0: the function must return promptly, printing nothing.
    run_bang_escape("true", false, false);
}

#[test]
#[cfg(not(windows))]
fn run_bang_escape_returns_on_nonzero_exit() {
    // `false` exits 1: the function must still return (report + continue),
    // never propagate the failure up as a panic or block the caller.
    run_bang_escape("exit 3", false, false);
}

#[serial_test::serial(real_fs)]
#[test]
#[cfg(windows)]
fn bang_shell_is_a_windows_shell_with_slash_c() {
    let (shell, flag) = bang_shell();
    assert_eq!(flag, "/C");
    assert!(!shell.is_empty(), "a shell is always resolved");
}

fn write_pyo3_binding(root: &std::path::Path, krate: &str, submodule: &str) {
    let dir = root.join(krate).join("src");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("pyo3_module.rs"),
        format!("#[pyclass(name=\"X\", module=\"newt_agent._newt_agent.{submodule}\")] struct X;"),
    )
    .unwrap();
}

#[serial_test::serial(real_fs)]
#[test]
fn verify_gate_summary_flags_fabrication_and_passes_clean() {
    use newt_core::verify_gate::SurfaceMatch;
    let dir = tempfile::tempdir().unwrap();
    write_pyo3_binding(dir.path(), "newt-core", "core");
    let ws = dir.path().to_str().unwrap();
    std::fs::create_dir_all(dir.path().join("examples")).unwrap();

    // a fabricated import → flagged
    std::fs::write(dir.path().join("examples/bad.py"), "import newt_core\n").unwrap();
    let warn = verify_gate_summary(ws, SurfaceMatch::Exact).expect("a fabrication warning");
    assert!(
        warn.contains("verify_gate") && warn.contains("newt_core"),
        "{warn}"
    );

    // replace with a grounded import → clean (None)
    std::fs::remove_file(dir.path().join("examples/bad.py")).unwrap();
    std::fs::write(
        dir.path().join("examples/ok.py"),
        "from newt_agent._newt_agent.core import X\nimport os\n",
    )
    .unwrap();
    assert!(verify_gate_summary(ws, SurfaceMatch::Exact).is_none());
}

#[serial_test::serial(real_fs)]
#[test]
fn verify_gate_summary_noops_without_pyo3_surface() {
    use newt_core::verify_gate::SurfaceMatch;
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("thing.py"), "import newt_core\n").unwrap();
    // no bindings → no authoritative surface → no gating (None)
    assert!(verify_gate_summary(dir.path().to_str().unwrap(), SurfaceMatch::Exact).is_none());
}

#[serial_test::serial(real_fs)]
#[tokio::test]
async fn retry_revert_undoes_only_newts_writes() {
    use newt_core::verify_gate::{SurfaceMatch, WriteLedger};
    let dir = tempfile::tempdir().unwrap();
    write_pyo3_binding(dir.path(), "newt-core", "core");
    let ws = dir.path().to_str().unwrap();
    std::fs::create_dir_all(dir.path().join("examples")).unwrap();

    // a pre-existing grounded file newt will fabricate-edit
    let edited = dir.path().join("examples/edited.py");
    std::fs::write(&edited, "from newt_agent._newt_agent.core import X\n").unwrap();
    // a pre-existing FABRICATING file newt never touches — must be left alone
    let untouched = dir.path().join("examples/untouched.py");
    std::fs::write(&untouched, "import newt_core\n").unwrap();

    // the per-turn ledger records ONLY newt's own writes (the write-tool seam)
    let ledger = std::cell::RefCell::new(WriteLedger::new());
    ledger.borrow_mut().note_before_write(&edited);
    std::fs::write(&edited, "import newt_core\n").unwrap(); // newt fabricate-edits it
    let created = dir.path().join("examples/new.py");
    ledger.borrow_mut().note_before_write(&created);
    std::fs::write(&created, "import newt_coder\n").unwrap(); // newt creates a bad file

    let action = retry_revert(ws, SurfaceMatch::Exact, &ledger)
        .await
        .expect("a revert action");
    assert!(
        action.banner.contains("retry: reverted"),
        "{}",
        action.banner
    );
    // the corrective re-prompt names a fabricated module and the real surface
    assert!(
        action.corrective.contains("newt_core") || action.corrective.contains("newt_coder"),
        "corrective names the bad import: {}",
        action.corrective
    );
    assert!(
        action.corrective.contains("newt_agent._newt_agent.core"),
        "corrective carries the authoritative surface"
    );

    // newt's edit restored to pre-turn bytes; newt's created file deleted
    assert_eq!(
        std::fs::read_to_string(&edited).unwrap(),
        "from newt_agent._newt_agent.core import X\n"
    );
    assert!(!created.exists(), "newt's created fabrication is deleted");
    // the fabricating file newt NEVER wrote is left completely untouched
    assert_eq!(
        std::fs::read_to_string(&untouched).unwrap(),
        "import newt_core\n",
        "a file newt did not write must never be reverted or deleted"
    );

    // re-gate: only `untouched` still fabricates, and newt did not write it,
    // so the revert acts on nothing and reports None.
    assert!(
        retry_revert(ws, SurfaceMatch::Exact, &ledger)
            .await
            .is_none(),
        "nothing newt wrote remains flagged"
    );
}

#[test]
fn retry_step_reprompts_until_the_budget_is_spent() {
    // budget = the re-prompts still allowed this user turn
    assert_eq!(retry_step(2), RetryStep::Reprompt);
    assert_eq!(retry_step(1), RetryStep::Reprompt);
    assert_eq!(retry_step(0), RetryStep::GiveUp);
}

// Regression tests for "the preamble always shows" (splash mode used to
// greet only inside the alternate screen, which vanishes on continue —
// leaving no preamble in scrollback). The header is now rendered by a
// pure function and printed in BOTH modes before chat starts.

#[test]
fn inline_header_color_contains_brand_and_ready_lines() {
    let s = render_inline_header("/w", true);
    assert!(s.contains("New Tech Agent"));
    assert!(s.contains(&format!("v{VERSION}")));
    assert!(s.contains("ready — type a task, /help for commands, /exit to quit"));
    // Text is placed just past the 20-col logo via absolute column moves.
    assert!(s.contains("\x1b[23G"));
}

#[test]
fn inline_header_plain_names_version_and_workspace() {
    let s = render_inline_header("/some/workspace", false);
    assert!(s.contains(&format!("newt v{VERSION}")));
    assert!(s.contains("/some/workspace"));
    // Plain mode must stay safe for dumb terminals and pipes: no ANSI.
    assert!(!s.contains('\x1b'));
}

#[test]
fn inline_header_lists_plugins_when_brand_set() {
    // #507: tests run in PARALLEL and Rust's `set_var`/`remove_var` are not
    // thread-safe — a raw, unguarded mutation here races the `HOME` swap in the
    // cw-400 recovery test (and any other env-touching test), which was the
    // intermittent pre-push-gate flake. Serialize on the shared write guard
    // (the same lock `with_env_vars` and the cw-400 test hold).
    let _g = crate::test_env_guard::env_write_guard();
    unsafe { std::env::set_var("NEWT_BRAND_PLUGINS", "mogul, diagram") };
    let color = render_inline_header("/w", true);
    let plain = render_inline_header("/w", false);
    unsafe { std::env::remove_var("NEWT_BRAND_PLUGINS") };
    assert!(color.contains("plugins:  mogul, diagram"));
    assert!(plain.contains("plugins:  mogul, diagram"));
    // Unset → no plugins line at all.
    assert!(!render_inline_header("/w", false).contains("plugins:"));
}

#[test]
fn inline_header_ends_with_blank_line_before_chat() {
    for color in [true, false] {
        let s = render_inline_header("/w", color);
        assert!(s.ends_with("\n\n"), "header must end with a blank line");
    }
}

#[test]
fn resolve_workspace_falls_back_gracefully() {
    let p = std::path::Path::new("/some/workspace");
    assert_eq!(resolve_workspace(Some(p)), "/some/workspace");
}

#[test]
fn slash_exit_returns_false() {
    for cmd in ["/exit", "/quit"] {
        let result = dispatch_slash(cmd, "/ws", false, false, false).unwrap();
        assert!(!result, "{cmd} should return false (exit)");
    }
}

#[test]
fn config_helpers_read_from_passed_config_not_disk() {
    // Regression (#150): these helpers used to call Config::resolve() — a
    // disk read + TOML parse — on every invocation, several times per turn.
    // They now derive from the &Config threaded in, so run_chat resolves
    // once and reuses it. This test passes a value-bearing Config and proves
    // the returned values come from the argument, not from a config file on
    // disk (which the old, arg-less signatures could not have read).
    let cfg = newt_core::Config {
        tui: Some(newt_core::TuiConfig {
            max_tool_rounds: 7,
            workflow_grace_rounds: 4,
            tool_output_lines: 3,
            ..Default::default()
        }),
        ..Default::default()
    };
    assert_eq!(max_tool_rounds(&cfg), 7);
    assert_eq!(workflow_grace_rounds(&cfg), 4);
    assert_eq!(tool_output_lines(&cfg), 3);
    assert_eq!(resolve_tui(&cfg).map(|t| t.max_tool_rounds), Some(7));
    assert_eq!(resolve_tui(&cfg).map(|t| t.workflow_grace_rounds), Some(4));

    // An empty config yields the documented defaults.
    let empty = newt_core::Config::default();
    assert_eq!(max_tool_rounds(&empty), 40);
    assert_eq!(workflow_grace_rounds(&empty), 5);
    assert_eq!(tool_output_lines(&empty), 20);
    assert_eq!(resolve_tui(&empty), None);
}

#[test]
fn narration_intent_line_is_absent_by_default_and_present_when_enabled() {
    // `[tui] narration_intent_line` is opt-in: off appends nothing.
    assert_eq!(narration_intent_line(false), None);
    let line = narration_intent_line(true).expect("enabled appends the sentence");
    assert!(line.contains("Before each tool call"));
    // Prose without a tool call is what the narration rescue nudges, so the
    // sentence asks for prose PLUS the call, never prose alone.
    assert!(line.contains("in the same reply"));
}

#[test]
fn tool_round_limit_commands_parse_expected_forms() {
    assert_eq!(
        parse_tool_round_limit_command("/rounds").unwrap(),
        ToolRoundLimitCommand::Show
    );
    assert_eq!(
        parse_tool_round_limit_command("/rounds status").unwrap(),
        ToolRoundLimitCommand::Show
    );
    assert_eq!(
        parse_tool_round_limit_command("/tool-rounds 50").unwrap(),
        ToolRoundLimitCommand::Set(50)
    );
    assert_eq!(
        parse_tool_round_limit_command("/max-rounds double").unwrap(),
        ToolRoundLimitCommand::Double
    );
    assert_eq!(
        parse_tool_round_limit_command("/rounds x2").unwrap(),
        ToolRoundLimitCommand::Double
    );
    assert_eq!(
        parse_tool_round_limit_command("/rounds reset").unwrap(),
        ToolRoundLimitCommand::Reset
    );
    assert_eq!(
        parse_tool_round_limit_command("/rounds default").unwrap(),
        ToolRoundLimitCommand::Reset
    );
    assert_eq!(
        parse_tool_round_limit_command("/rounds auto").unwrap(),
        ToolRoundLimitCommand::Reset
    );
    assert_eq!(
        parse_tool_round_limit_command("/rounds config").unwrap(),
        ToolRoundLimitCommand::Configured
    );
    assert_eq!(
        parse_tool_round_limit_command("/rounds unlimited").unwrap(),
        ToolRoundLimitCommand::Unlimited
    );
    assert_eq!(
        parse_tool_round_limit_command("/rounds run until finished").unwrap(),
        ToolRoundLimitCommand::Unlimited
    );

    assert!(parse_tool_round_limit_command("/roundsx 10").is_err());
    assert!(parse_tool_round_limit_command("/rounds 0").is_err());
    assert!(parse_tool_round_limit_command("/rounds 10001").is_err());
    assert!(parse_tool_round_limit_command("/rounds many").is_err());
}

/// **The verb the operator typed survives the parse** (#1998).
///
/// All three names reach one handler, so the parser used to drop which one
/// matched — and then a receipt could only ever say `/rounds`, for a session
/// where the operator typed `/max-rounds`. The verb is bound into the
/// receipt's content address, so losing it here loses it everywhere.
#[test]
fn the_typed_rounds_verb_survives_the_parse() {
    for (input, verb, arg) in [
        ("/rounds 320", "rounds", "320"),
        ("/tool-rounds 50", "tool-rounds", "50"),
        ("/max-rounds double", "max-rounds", "double"),
        ("/rounds", "rounds", ""),
    ] {
        assert_eq!(
            tool_round_limit_command(input),
            Some((verb, arg)),
            "`{input}` lost the verb or the argument"
        );
    }
    // Anti-vacuous: a near-miss is still not a rounds command, so the prefix
    // match has not been loosened into "starts with".
    assert_eq!(tool_round_limit_command("/roundsx 10"), None);
    assert_eq!(tool_round_limit_command("/round 10"), None);
}

#[test]
fn tool_round_limit_override_resolves_and_reports() {
    use newt_core::Tenacity;

    use newt_core::tenacity::ToolRoundLimitSource;

    // #1965: the resolver now returns the number WITH its derivation, so each
    // case pins which input won as well as what it produced. `configured` is
    // carried through every arm so a reader of a turn record sees the
    // escalation, not just the result.
    let plain = effective_tool_round_limit(25, None, None);
    assert_eq!(
        (plain.rounds, plain.source),
        (25, ToolRoundLimitSource::Config)
    );
    assert!(!plain.is_escalated());

    let standard = effective_tool_round_limit(25, Some(Tenacity::Normal), None);
    assert_eq!(
        (standard.rounds, standard.source),
        (25, ToolRoundLimitSource::Config),
        "a tenacity level that does not RAISE the limit did not decide it"
    );

    let relentless = effective_tool_round_limit(25, Some(Tenacity::Relentless), None);
    assert_eq!(
        (relentless.rounds, relentless.source, relentless.configured),
        (
            EFFECTIVELY_UNLIMITED_TOOL_ROUNDS,
            ToolRoundLimitSource::Tenacity,
            25
        ),
        "an explicitly selected relentless posture should not hit the ordinary safety cap"
    );
    assert!(relentless.is_escalated());
    assert_eq!(relentless.tenacity, Some(Tenacity::Relentless.into()));

    let overridden = effective_tool_round_limit(25, Some(Tenacity::Relentless), Some(7));
    assert_eq!(
        (overridden.rounds, overridden.source, overridden.configured),
        (7, ToolRoundLimitSource::Override, 25),
        "a deliberate /rounds override remains the outermost limit"
    );

    let raised = effective_tool_round_limit(25, None, Some(50));
    assert_eq!(
        (raised.rounds, raised.source, raised.configured),
        (50, ToolRoundLimitSource::Override, 25),
        "the escalation this issue is about: 50 enforced over a configured 25"
    );
    assert_eq!(double_tool_round_limit(25), 50);
    assert_eq!(
        double_tool_round_limit(EFFECTIVELY_UNLIMITED_TOOL_ROUNDS),
        EFFECTIVELY_UNLIMITED_TOOL_ROUNDS
    );
    assert_eq!(
        double_tool_round_limit(EFFECTIVELY_UNLIMITED_TOOL_ROUNDS * 2),
        EFFECTIVELY_UNLIMITED_TOOL_ROUNDS * 2,
        "doubling must never lower a larger configured/session value"
    );
    assert_eq!(
        tool_round_limit_status(25, None, None),
        "initial tool-call round allowance: 25 (config/model default)"
    );
    assert_eq!(
        tool_round_limit_status(25, None, Some(50)),
        "initial tool-call round allowance: 50 this session (config/model default 25)"
    );
    assert_eq!(
        tool_round_limit_status(25, Some(Tenacity::Relentless), None),
        "initial tool-call round allowance: 10000 (effectively unlimited; explicit relentless tenacity; config/model default 25)"
    );
    assert_eq!(
        tool_round_limit_status(25, Some(Tenacity::Relentless), Some(7)),
        "initial tool-call round allowance: 7 this session (explicit relentless tenacity default 10000 (effectively unlimited); config/model default 25)"
    );
    assert!(
        tool_round_limit_status(25, None, Some(EFFECTIVELY_UNLIMITED_TOOL_ROUNDS))
            .contains("effectively unlimited")
    );

    let relentless = Some(Tenacity::Relentless);
    assert_eq!(
        apply_tool_round_limit_command(25, relentless, None, ToolRoundLimitCommand::Configured,),
        Some(25),
        "config explicitly bypasses the tenacity-derived default"
    );
    assert_eq!(
        apply_tool_round_limit_command(25, relentless, Some(25), ToolRoundLimitCommand::Reset,),
        None,
        "reset returns to automatic derivation"
    );
    assert_eq!(
        effective_tool_round_limit(
            25,
            relentless,
            apply_tool_round_limit_command(25, relentless, Some(25), ToolRoundLimitCommand::Reset,),
        )
        .rounds,
        EFFECTIVELY_UNLIMITED_TOOL_ROUNDS
    );
    assert_eq!(
        apply_tool_round_limit_command(20_000, relentless, None, ToolRoundLimitCommand::Unlimited,),
        Some(20_000),
        "unlimited must not lower an already larger effective limit"
    );
    assert!(
        tool_round_limit_status(20_000, relentless, None).contains("explicit relentless tenacity"),
        "status keeps operator provenance even when config already exceeds the sentinel"
    );
}

#[test]
fn psyche_apply_summary_includes_the_effective_round_source() {
    use newt_core::Tenacity;

    let summary = psyche_apply_summary(
        "psyche: meticulous + relentless",
        40,
        Some(Tenacity::Relentless),
        Some(7),
    );
    assert!(
        summary.starts_with("psyche: meticulous + relentless"),
        "{summary}"
    );
    assert!(
        summary.contains("initial tool-call round allowance: 7 this session"),
        "{summary}"
    );
    assert!(
        summary.contains("relentless tenacity default 10000"),
        "{summary}"
    );
}

#[test]
fn spill_commands_parse_expected_forms() {
    assert_eq!(parse_spill_command("/spill").unwrap(), SpillCommand::Status);
    assert_eq!(
        parse_spill_command("/spill status").unwrap(),
        SpillCommand::Status
    );
    assert_eq!(
        parse_spill_command("/spill 7").unwrap(),
        SpillCommand::Set(7)
    );
    assert_eq!(
        parse_spill_command("/spill 0").unwrap(),
        SpillCommand::Set(0)
    );
    assert_eq!(
        parse_spill_command("/spill reset").unwrap(),
        SpillCommand::Reset
    );
    // #1640 Layer 1: the mode switches.
    assert_eq!(
        parse_spill_command("/spill summary").unwrap(),
        SpillCommand::Summary
    );
    assert_eq!(
        parse_spill_command("/spill excerpt").unwrap(),
        SpillCommand::Excerpt
    );
    assert_eq!(
        parse_spill_command("/spill last").unwrap(),
        SpillCommand::Last
    );
    assert_eq!(
        parse_spill_command("/spill open 17").unwrap(),
        SpillCommand::Open(17)
    );
    assert!(parse_spill_command("/spill open").is_err());
    assert!(parse_spill_command("/spill open 0").is_err());
    assert!(parse_spill_command("/spill open 3 extra").is_err());
    assert!(parse_spill_command("/spillage 7").is_err());
    assert!(parse_spill_command("/spill many").is_err());
}

/// #1640 Layer 1: the summary default follows the SURFACE — rich collapses
/// (its /spill vocabulary can recover detail), lean never does (it shows full
/// output) — and the session override wins over both.
#[test]
fn spill_summary_defaults_to_the_surface_and_override_wins() {
    assert!(effective_spill_summary(true, None), "rich collapses");
    assert!(
        !effective_spill_summary(false, None),
        "lean never collapses"
    );
    assert!(
        !effective_spill_summary(true, Some(false)),
        "/spill excerpt"
    );
    assert!(effective_spill_summary(false, Some(true)), "/spill summary");

    // `/spill status` names the mode — and its escape hatch — when it is on,
    // and stays byte-identical to the historical string when it is off.
    let on = spill_status(3, None, true, true, SpillEligibility::Available);
    assert!(
        on.contains("results collapse to a summary line (/spill excerpt restores rows)"),
        "{on}"
    );
    let off = spill_status(3, None, false, true, SpillEligibility::Available);
    assert!(!off.contains("summary line"), "{off}");
}

#[test]
fn spill_status_never_claims_a_collapse_that_cannot_engage() {
    // #1663 review F3/F9: the mode clause is guarded like the renderer is.
    // (i) lean: committed rendering is forced full, so even summary=true
    // (a /spill summary override) must not claim collapse — and the status
    // says plainly that committed results print in full there.
    let lean = spill_status(3, None, true, false, SpillEligibility::Available);
    assert!(!lean.contains("summary line"), "{lean}");
    assert!(
        lean.contains("committed results always print in full"),
        "{lean}"
    );
    // (ii) rich after /spill 0: unbounded view never collapses.
    let unbounded = spill_status(3, Some(0), true, true, SpillEligibility::Available);
    assert!(!unbounded.contains("summary line"), "{unbounded}");
    // Rich with rows > 0 keeps the honest claim (guard must not over-suppress).
    let rich = spill_status(3, None, true, true, SpillEligibility::Available);
    assert!(rich.contains("summary line"), "{rich}");
    assert!(!rich.contains("print in full"), "{rich}");
}

#[test]
fn spill_reset_clears_both_session_knobs() {
    // #1663 review F12: Reset returns BOTH knobs to surface defaults; the
    // other forms each touch only the knob they own.
    let mut lines = Some(7usize);
    let mut summary = Some(true);
    apply_spill_command(SpillCommand::Reset, &mut lines, &mut summary);
    assert_eq!((lines, summary), (None, None), "Reset clears BOTH");

    apply_spill_command(SpillCommand::Set(5), &mut lines, &mut summary);
    assert_eq!(
        (lines, summary),
        (Some(5), None),
        "Set leaves the mode alone"
    );

    apply_spill_command(SpillCommand::Summary, &mut lines, &mut summary);
    assert_eq!((lines, summary), (Some(5), Some(true)), "Summary sets mode");

    apply_spill_command(SpillCommand::Excerpt, &mut lines, &mut summary);
    assert_eq!((lines, summary), (Some(5), Some(false)));

    apply_spill_command(SpillCommand::Status, &mut lines, &mut summary);
    assert_eq!(
        (lines, summary),
        (Some(5), Some(false)),
        "Status is read-only"
    );
}

#[test]
fn search_commands_parse_expected_forms() {
    assert_eq!(
        parse_search_command("/search").unwrap(),
        SearchCommand::Help
    );
    assert_eq!(
        parse_search_command("/search help").unwrap(),
        SearchCommand::Help
    );
    assert_eq!(
        parse_search_command("/search auth handshake").unwrap(),
        SearchCommand::Query("auth handshake".into())
    );
    assert_eq!(
        parse_search_command("/search preview").unwrap(),
        SearchCommand::Preview(1)
    );
    assert_eq!(
        parse_search_command("/search preview 3").unwrap(),
        SearchCommand::Preview(3)
    );
    assert_eq!(
        parse_search_command("/search model").unwrap(),
        SearchCommand::Model
    );
    assert_eq!(
        parse_search_command("/search rejects").unwrap(),
        SearchCommand::Rejects
    );
    assert_eq!(
        parse_search_command("/search pin 2").unwrap(),
        SearchCommand::Pin(2)
    );
    assert_eq!(
        parse_search_command("/search exclude 1").unwrap(),
        SearchCommand::Exclude(1)
    );
    assert_eq!(
        parse_search_command("/search status").unwrap(),
        SearchCommand::Status
    );
    assert_eq!(
        parse_search_command("/search clear").unwrap(),
        SearchCommand::Clear
    );
    assert!(parse_search_command("/searching foo").is_err());
    assert!(parse_search_command("/search pin").is_err());
}

/// #1434: `--trace` seeds the detail knob, so there is ONE source of truth and
/// no launch-vs-runtime phase.
///
/// This is the bug pi shipped, written down so newt cannot ship it.
/// `modes/interactive/interactive-mode.ts` computes
/// `options.verbose || toolOutputExpanded` at one call site, and nothing ever
/// initializes `toolOutputExpanded` from `options.verbose`. So after
/// `pi --verbose` the state is "expanded" for display purposes but `false` in
/// the variable, and **the first toggle press expands again instead of
/// collapsing** — the control moves the wrong way on its first use, which is
/// the worst possible first impression for a toggle.
///
/// Seeding removes the second variable, so the phase cannot exist.
#[test]
fn trace_seeds_the_detail_knob_so_the_first_toggle_collapses() {
    const CONFIGURED: usize = 3;

    // Without --trace the knob simply follows config.
    assert_eq!(initial_spill_override(false), None);
    assert_eq!(
        effective_spill_lines(CONFIGURED, initial_spill_override(false)),
        CONFIGURED
    );

    // With --trace the session STARTS unbounded …
    let seeded = initial_spill_override(true);
    assert_eq!(seeded, Some(0), "--trace means show me everything");
    assert_eq!(effective_spill_lines(CONFIGURED, seeded), 0);

    // … and the first toggle press must COLLAPSE, not expand again.
    let after_first_press = toggle_spill_detail(seeded, CONFIGURED);
    assert_eq!(
        effective_spill_lines(CONFIGURED, after_first_press),
        CONFIGURED,
        "the first toggle after --trace went the wrong way — this is pi's phase \
         bug, and seeding exists precisely to make it unrepresentable"
    );

    // And it flips back.
    let after_second_press = toggle_spill_detail(after_first_press, CONFIGURED);
    assert_eq!(effective_spill_lines(CONFIGURED, after_second_press), 0);
}

/// #1434: the toggle is defined over the same `Option<usize>` `/spill` mutates,
/// so a `/spill N` mid-session and a toggle cannot disagree.
#[test]
fn detail_toggle_shares_state_with_the_spill_command() {
    // Operator sets an explicit height, then toggles.
    let explicit = Some(7);
    let expanded = toggle_spill_detail(explicit, 3);
    assert_eq!(effective_spill_lines(3, expanded), 0, "toggle expands");

    // Toggling back returns to the CONFIGURED height, not the explicit 7 —
    // the toggle is a two-state control, and `/spill 7` is how you get 7 back.
    let collapsed = toggle_spill_detail(expanded, 3);
    assert_eq!(effective_spill_lines(3, collapsed), 3);

    // A configured height of 0 must not make the toggle a no-op that reads as
    // a broken control.
    let from_zero_config = toggle_spill_detail(Some(0), 0);
    assert!(effective_spill_lines(0, from_zero_config) > 0);
}

#[test]
fn spill_override_resolves_and_reports_live_capability() {
    assert_eq!(effective_spill_lines(3, None), 3);
    assert_eq!(effective_spill_lines(3, Some(7)), 7);
    assert_eq!(effective_spill_lines(3, Some(0)), 0);
    assert_eq!(
        spill_status(3, None, false, true, SpillEligibility::Available),
        "spill rows: 3 (config default; live interaction available)"
    );
    // #1412: the unavailable arm now NAMES the refusing gate instead of saying
    // only "unavailable" — that silence is why a stale install was reported as
    // a vanished feature.
    assert_eq!(
        spill_status(3, Some(7), false, true, SpillEligibility::StdoutNotTty),
        "spill rows: 7 this session (config default 3; live interaction unavailable: \
         stdout is not a terminal (piped or redirected))"
    );
    assert_eq!(
        spill_status(3, Some(0), false, true, SpillEligibility::Available),
        "spill rows: unbounded this session (config default 3; live viewport disabled: \
         spill_lines is 0 (/spill <n> raises it))"
    );
}

/// #1640: the committed tool-output excerpt is collapsed ONLY on the rich
/// surface — the surface that can recover the hidden lines through an
/// interactive viewport. The lean surface (the plain scroller) has no scroll
/// region, so its excerpt is the whole record and must be shown in full.
#[test]
fn committed_excerpt_is_full_on_lean_and_collapsed_on_rich() {
    const CONFIGURED: usize = 3;

    // Rich keeps the configured height (a viewport backs the truncation)…
    assert_eq!(committed_spill_lines(true, CONFIGURED), CONFIGURED);
    // …and honours an explicit /spill 0 (unbounded) unchanged.
    assert_eq!(committed_spill_lines(true, 0), 0);

    // Lean is ALWAYS unbounded regardless of the configured height — there is
    // no scrollable region on the plain scroller (#1640), so a "▲ N more lines
    // above · /spill N" excerpt would hide output the surface cannot reveal.
    // 0 is `spill_view_lines`' existing "print every line" contract (proven in
    // newt-core's own display tests), so lean reuses that path unchanged.
    assert_eq!(committed_spill_lines(false, CONFIGURED), 0);
    assert_eq!(committed_spill_lines(false, 42), 0);
    assert_eq!(committed_spill_lines(false, 0), 0);
}

/// #1412: every refusal reason reaches the operator, and zero rows is reported
/// as a config choice rather than a broken terminal.
#[test]
fn spill_status_names_the_gate_that_refused() {
    for (eligibility, needle) in [
        (
            SpillEligibility::UnsupportedPlatform,
            "unsupported platform",
        ),
        (SpillEligibility::FeatureDisabled, "`live-spill` feature"),
        (SpillEligibility::StdinNotTty, "stdin is not a terminal"),
        (SpillEligibility::StdoutNotTty, "stdout is not a terminal"),
        (SpillEligibility::TermDumb, "TERM=dumb"),
    ] {
        let status = spill_status(3, None, false, true, eligibility);
        assert!(
            status.contains(needle),
            "{eligibility:?} must surface {needle:?} to the operator, got: {status}"
        );
    }

    // Rows are a separate axis from capability: a capable terminal with zero
    // rows must not be reported as an incapable terminal.
    let zero = spill_status(0, None, false, true, SpillEligibility::Available);
    assert!(zero.contains("spill_lines is 0"), "{zero}");
    assert!(
        !zero.contains("unavailable"),
        "zero rows is a config choice, not a broken terminal: {zero}"
    );
}

/// #1412: precedence is part of the contract. When several gates refuse at
/// once, the one the operator cannot change without a different binary must
/// win — otherwise `/spill` sends someone to fix `TERM` on a build that never
/// compiled the feature in.
#[test]
fn spill_eligibility_reports_the_most_fundamental_refusal_first() {
    // Every gate failing at once: platform outranks all.
    assert_eq!(
        spill_eligibility_for(false, false, false, false, Some("dumb"), false),
        SpillEligibility::UnsupportedPlatform
    );
    // Supported platform, everything else failing: the cargo feature is next.
    assert_eq!(
        spill_eligibility_for(true, false, false, false, Some("dumb"), false),
        SpillEligibility::FeatureDisabled
    );
    // Then the invocation-shaped gates, stdin before stdout.
    assert_eq!(
        spill_eligibility_for(true, true, false, false, Some("dumb"), false),
        SpillEligibility::StdinNotTty
    );
    assert_eq!(
        spill_eligibility_for(true, true, true, false, Some("dumb"), false),
        SpillEligibility::StdoutNotTty
    );
    // Only the terminal's own declaration remains.
    assert_eq!(
        spill_eligibility_for(true, true, true, true, Some("dumb"), false),
        SpillEligibility::TermDumb
    );
    assert_eq!(
        spill_eligibility_for(true, true, true, true, Some("xterm-256color"), false),
        SpillEligibility::Available
    );
    // The cockpit is LAST on purpose. It is the one refusal where nothing is
    // wrong — platform, build and terminal are all fine, and the operator is
    // simply on the surface that paints its own frames — so every fixable
    // cause outranks it and nobody is sent to fix `TERM` for it.
    assert_eq!(
        spill_eligibility_for(true, true, true, true, Some("xterm-256color"), true),
        SpillEligibility::TerminalOwnedByCockpit
    );
    assert_eq!(
        spill_eligibility_for(true, true, true, true, Some("dumb"), true),
        SpillEligibility::TermDumb,
        "a dumb terminal is the more fundamental refusal and still outranks it"
    );
    assert_eq!(
        spill_eligibility_for(false, true, true, true, Some("xterm-256color"), true),
        SpillEligibility::UnsupportedPlatform,
        "and so does a platform the viewport could never run on"
    );

    // The refusal must name the surface AND the way out. This is the line that
    // read "live interaction available" while the cockpit drew every frame.
    let cockpit = SpillEligibility::TerminalOwnedByCockpit.explain();
    assert!(cockpit.contains("cockpit"), "{cockpit}");
    assert!(
        cockpit.contains("/spill open"),
        "an unavailability the operator cannot act on is barely better than a \
         bare `unavailable`: {cockpit}"
    );
    // A terminal that declares nothing is not "dumb".
    assert_eq!(
        spill_eligibility_for(true, true, true, true, None, false),
        SpillEligibility::Available
    );
}

/// #1412: the boolean façade must agree with the typed answer at every input,
/// so the mouse tier cannot drift from `/spill`'s account of the same gates.
#[test]
fn capable_bool_agrees_with_typed_eligibility() {
    for platform in [true, false] {
        for feature in [true, false] {
            for stdin in [true, false] {
                for stdout in [true, false] {
                    for term in [Some("xterm"), Some("dumb"), None] {
                        // The cockpit gate is a new AXIS of this table, not a
                        // fixed `false` bolted onto it: the property is that
                        // the boolean facade and the ladder never disagree,
                        // and a gate exempted from the sweep is a gate that
                        // can drift.
                        for cockpit in [true, false] {
                            assert_eq!(
                                live_spill_capable_for(
                                    platform, feature, stdin, stdout, term, cockpit
                                ),
                                spill_eligibility_for(
                                    platform, feature, stdin, stdout, term, cockpit
                                ) == SpillEligibility::Available,
                                "disagreement at platform={platform} feature={feature} \
                                 stdin={stdin} stdout={stdout} term={term:?} \
                                 cockpit={cockpit}"
                            );
                        }
                    }
                }
            }
        }
    }
}

#[test]
fn live_spill_requires_a_supported_interactive_terminal() {
    assert!(live_spill_capable_for(
        true,
        true,
        true,
        true,
        Some("xterm-256color"),
        false
    ));
    assert!(!live_spill_capable_for(
        false,
        true,
        true,
        true,
        Some("xterm"),
        false
    ));
    assert!(!live_spill_capable_for(
        true,
        false,
        true,
        true,
        Some("xterm"),
        false
    ));
    assert!(!live_spill_capable_for(
        true,
        true,
        false,
        true,
        Some("xterm"),
        false
    ));
    assert!(!live_spill_capable_for(
        true,
        true,
        true,
        false,
        Some("xterm"),
        false
    ));
    assert!(!live_spill_capable_for(
        true,
        true,
        true,
        true,
        Some("dumb"),
        false
    ));
}

// #1303 acceptance 1a: the mouse tier is `live_spill_capable()` AND an explicit
// opt-in — a strict superset gate. Mouse events arrive on stdin, so a
// stdin-piped session (stdin_terminal=false) must never enable capture even
// when stdout is a TTY.
#[cfg(feature = "live-spill")]
#[test]
fn mouse_tier_requires_optin_and_a_supported_interactive_terminal() {
    // Every predicate satisfied — INCLUDING the explicit opt-in — is the only
    // way the mouse tier turns on.
    assert!(mouse_capable_for(
        true,
        true,
        true,
        true,
        Some("xterm-256color"),
        true
    ));
    // Opt-in off ⇒ never capable, even on a flawless interactive TTY.
    assert!(!mouse_capable_for(
        true,
        true,
        true,
        true,
        Some("xterm"),
        false
    ));
    // Each base predicate false-flips to incapable (opt-in held on).
    assert!(!mouse_capable_for(
        false,
        true,
        true,
        true,
        Some("xterm"),
        true
    )); // platform
    assert!(!mouse_capable_for(
        true,
        false,
        true,
        true,
        Some("xterm"),
        true
    )); // feature
    assert!(!mouse_capable_for(
        true,
        true,
        false,
        true,
        Some("xterm"),
        true
    )); // stdin TTY
    assert!(!mouse_capable_for(
        true,
        true,
        true,
        false,
        Some("xterm"),
        true
    )); // stdout TTY
    assert!(!mouse_capable_for(
        true,
        true,
        true,
        true,
        Some("dumb"),
        true
    )); // TERM=dumb
}

// #1303: the opt-in reads from `[tui] mouse_viewport`, default off.
#[cfg(feature = "live-spill")]
#[test]
fn mouse_viewport_optin_reads_from_config_default_off() {
    let empty = newt_core::Config::default();
    assert!(!mouse_viewport(&empty), "default is off");
    let opted_in = newt_core::Config {
        tui: Some(newt_core::TuiConfig {
            mouse_viewport: true,
            ..Default::default()
        }),
        ..Default::default()
    };
    assert!(mouse_viewport(&opted_in));
}

#[test]
fn slash_help_returns_true() {
    assert!(dispatch_slash("/help", "/ws", false, false, false).unwrap());
}

#[test]
fn slash_parts_ignore_extra_whitespace_before_model_name() {
    assert_eq!(
        slash_parts("/model  Ornith-1.5-35B-Q8_0"),
        ("model", "Ornith-1.5-35B-Q8_0", "")
    );
}

#[test]
fn help_request_recognizes_every_form() {
    assert_eq!(help_request("/models --help").as_deref(), Some("models"));
    assert_eq!(help_request("/models -h").as_deref(), Some("models"));
    assert_eq!(help_request("/probe help").as_deref(), Some("probe"));
    assert_eq!(help_request("/help models").as_deref(), Some("models"));
    // Bare /help is the full list, not a per-command page.
    assert_eq!(help_request("/help"), None);
    // Ordinary commands (and their args) are not help requests.
    assert_eq!(help_request("/models capabilities"), None);
    assert_eq!(help_request("/model qwen3:30b"), None);
}

#[test]
fn help_request_treats_start_and_rename_titles_as_titles_not_help() {
    // #1030: /start and /rename take a free-text title, so a help token INSIDE
    // the title must not be swallowed by the help interceptor.
    assert_eq!(help_request("/start help me debug"), None);
    assert_eq!(help_request("/rename fix the -h flag"), None);
    assert_eq!(help_request("/start My Title"), None);
    // A SOLE help token still asks for help, folded to the documenting page.
    assert_eq!(help_request("/start --help").as_deref(), Some("new"));
    assert_eq!(help_request("/rename -h").as_deref(), Some("conversation"));

    // **`/name` is `/rename`'s alias and was NOT carved out** — the list named
    // two verbs and the alias was not one of them, so `/name help me debug`
    // opened a help page instead of retitling the conversation. Found while
    // porting the carve-out to `Text` fields (#2009 PR5).
    assert_eq!(help_request("/name help me debug"), None);
    assert_eq!(help_request("/name fix the -h flag"), None);
    assert_eq!(help_request("/name -h").as_deref(), Some("conversation"));
}

/// **A free-text SETTING is carved out the same way a free-text verb is.**
///
/// `/settings prompt "help me"` is a template, not a help request. The rule
/// was hardcoded to two verb names; a `Text` field is the same situation
/// arriving through a different door, so the predicate asks the FIELD whether
/// it takes free text rather than growing a third name in a list.
#[test]
fn help_request_treats_a_text_settings_value_as_a_value_not_help() {
    assert_eq!(help_request("/settings prompt \"help me\""), None);
    assert_eq!(help_request("/settings prompt [$TIME] -h > "), None);
    // The field itself still has a page, reached the way every other one is.
    assert_eq!(
        help_request("/settings prompt --help").as_deref(),
        Some("settings")
    );
    assert_eq!(
        help_request("/settings --help").as_deref(),
        Some("settings")
    );
    // A CHOICE field is not free text: its values are a closed vocabulary, so
    // a help token among them is a help request as it always was.
    assert_eq!(
        help_request("/settings mode --help").as_deref(),
        Some("settings")
    );
}

#[test]
fn command_help_covers_every_listed_command_and_folds_aliases() {
    for cmd in [
        "settings",
        "models",
        "model",
        "backend",
        "backends",
        "thinking",
        "probe",
        "memory",
        "compress",
        "summarizer",
        "rounds",
        "tool-rounds",
        "max-rounds",
        "remember",
        "new",
        "end",
        "restart",
        "conversation",
        "recall",
        "persona",
        "crew",
        "dgx",
        "permissions",
        "mode",
        "posture",
        "loadout",
        "plan",
        "status",
        "info",
        "docs",
        "workspace",
        "spill",
        "config",
        "prompt",
        "allow",
        "vi",
        "emacs",
        "nano",
        "version",
        "exit",
        "quit",
        "help",
    ] {
        assert!(command_help_page(cmd).is_some(), "no help page for /{cmd}");
    }
    assert!(command_help_page("bogus").is_none());
    // Aliases share one page.
    assert_eq!(command_help_page("restart"), command_help_page("new"));
    assert_eq!(command_help_page("emacs"), command_help_page("vi"));
    assert_eq!(command_help_page("quit"), command_help_page("exit"));
    assert_eq!(command_help_page("plan"), command_help_page("roadmap"));
    assert_eq!(command_help_page("allow"), command_help_page("permissions"));
    assert!(help_lines().iter().any(|l| l.contains("/status")));
    assert!(help_lines().iter().any(|l| l.contains("/allow")));
    // #2009 PR3: `/loadout`, `/info` and `/docs` retired into `/status
    // <topic>` and `/help docs`. Their help LINES are gone from the corpus —
    // the same shape as the #1665 note below — so what the corpus must teach
    // now is the topic list that replaced them.
    let topics = help_lines()
        .iter()
        .find(|l| l.contains("/status <topic>"))
        .expect("the /status topic line is advertised");
    for topic in [
        "config",
        "version",
        "workspace",
        "loadout",
        "byline",
        "memory",
        "models",
    ] {
        assert!(topics.contains(topic), "{topics:?} omits the {topic} topic");
    }
    // ...and their help PAGES survive, so `/help loadout` still answers the
    // operator who reaches for the old name.
    for retired in ["loadout", "info", "docs", "version", "workspace", "models"] {
        assert!(
            command_help_page(retired).is_some(),
            "/help {retired} lost its page; a retired verb keeps its pointer"
        );
    }
    // #2009 PR12: `/plan` was an alias that forwarded to `/roadmap`; it
    // retired, and the corpus teaches the verb it forwarded to.
    assert!(help_lines().iter().any(|l| l.contains("/roadmap")));
    // #1665: /psyche is the one advertised dial surface; the retired top-level
    // /tenacity + /cognition lines are gone from the corpus (their help PAGES
    // survive as redirects for /help tenacity muscle memory).
    assert!(help_lines().iter().any(|l| l.contains("/psyche")));
    assert!(!help_lines()
        .iter()
        .any(|l| l.contains("/tenacity") || l.contains("/cognition")));
    let tenacity_page = command_help_page("tenacity").expect("tenacity redirect page");
    assert!(
        tenacity_page.contains("/psyche tenacity"),
        "{tenacity_page}"
    );
    let initiative_page = command_help_page("initiative").expect("initiative help page");
    for level in newt_core::Initiative::all() {
        assert!(
            initiative_page.contains(level.label()),
            "the page lists every level from Initiative::all(): {initiative_page}"
        );
    }
    let cognition_page = command_help_page("cognition").expect("cognition redirect page");
    assert!(
        cognition_page.contains("/psyche cognition"),
        "{cognition_page}"
    );
    let spill_help = command_help_page("spill").expect("spill help page");
    assert!(spill_help.contains("Space or Enter"));
    assert!(spill_help.contains("⧉"));
    assert!(spill_help.contains("▣"));
    // The unknown-topic miss is reported (returns false).
    assert!(!print_command_help("bogus", false, false, false));
}

/// ANTI-DRIFT: the startup-free `render_help` path (behind `newt help`) and the
/// interactive TUI's Markdown-off fallback must stay pinned to the
/// single-source-of-truth corpora (`help_lines` / `command_help_page`):
/// `print_newt` == `println!(newt_line(...))` (a `newt_line` + `\n`), then one
/// corpus line per `\n`-terminated row.
#[test]
fn render_help_is_byte_identical_to_the_plain_help_corpus() {
    for &(color, verbose) in &[(false, false), (true, false), (false, true), (true, true)] {
        // Bare `/help` — the full command list.
        let mut expected = newt_line("Available commands:", color, verbose);
        expected.push('\n');
        for line in help_lines() {
            expected.push_str(line);
            expected.push('\n');
        }
        assert_eq!(
            render_help(None, color, verbose),
            expected,
            "render_help(None) drifted from the help_lines corpus (color={color}, verbose={verbose})"
        );

        // Per-command detail pages: a representative command, an alias that
        // folds to a shared page, and the #548 `/dgx` target.
        for cmd in ["dgx", "help", "exit", "quit", "emacs"] {
            let page = command_help_page(cmd).expect("help page exists");
            let mut want = newt_line(
                &format!("/{} help", canonical_help_topic(cmd)),
                color,
                verbose,
            );
            want.push('\n');
            for line in page.lines() {
                want.push_str(line);
                want.push('\n');
            }
            assert_eq!(
                render_help(Some(cmd), color, verbose),
                want,
                "render_help(Some({cmd:?})) drifted from command_help_page"
            );
        }

        // Unknown topic renders the one-line miss (never empty, never a panic).
        let mut miss = newt_line(
            "no help for '/bogus' — /help lists every command",
            color,
            verbose,
        );
        miss.push('\n');
        assert_eq!(render_help(Some("bogus"), color, verbose), miss);
    }
}

/// RichTUI help is a Markdown document, governed by the same `[tui].markdown`
/// policy as assistant output. The plain/startup-free corpus remains available
/// when rendering is disabled.
#[test]
fn rich_help_uses_the_default_markdown_policy_and_honors_off() {
    let default_cfg = newt_core::Config::default();
    let markdown = markdown_enabled(&default_cfg, true);
    assert!(markdown, "RichTUI defaults to rendered Markdown");

    let rendered = render_help_for_tui(None, true, false, markdown, 100);
    let heading =
        newt_core::tty::theme::active().ansi(newt_core::tty::theme::Role::MarkdownHeading);
    assert!(
        rendered.starts_with(&format!("▸  {heading}Available")),
        "the narrator prefix must stay outside the Markdown parser: {rendered:?}"
    );
    assert!(!rendered.contains("## Available commands"));
    assert!(rendered.contains("commands"));
    assert!(rendered.contains("• "));
    assert!(rendered.contains("/status"));

    let cfg_off = newt_core::Config {
        tui: Some(newt_core::TuiConfig {
            markdown: newt_core::MarkdownMode::Off,
            ..Default::default()
        }),
        ..Default::default()
    };
    let markdown = markdown_enabled(&cfg_off, true);
    assert!(!markdown);
    assert_eq!(
        render_help_for_tui(None, true, false, markdown, 100),
        render_help(None, true, false)
    );
}

#[test]
fn slash_version_returns_true() {
    assert!(dispatch_slash("/version", "/ws", false, false, false).unwrap());
}

#[test]
fn slash_workspace_returns_true() {
    assert!(dispatch_slash("/workspace", "/ws", false, false, false).unwrap());
}

#[test]
fn permission_audit_lines_lists_newest_entries_and_reports_bad_lines_as_breaks() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("permission-log.jsonl");
    newt_core::permission_journal::append_record(
        &path,
        newt_core::PermissionRecord::new(
            "c",
            "run_command",
            newt_core::DenialKind::Exec,
            "/bin/echo",
            "allow",
            "session",
        ),
    )
    .unwrap();
    // An interrupted append mid-chain: not readable as a chain line, and must
    // surface as tamper evidence rather than vanish — item 3, #2529 round 2.
    // Simulated as a snapshot rewrite (read the legacy bytes, add the garbage
    // line, write the whole file back once) rather than a real append-mode
    // writer, so this fixture isn't mistaken for a second journal writer by
    // the `content_addressable_ratchet` scan (it looks for `append(true)` +
    // `serde_json::to_string` together — see that test's `journal_tier`).
    {
        let mut contents = std::fs::read_to_string(&path).unwrap();
        contents.push_str("this is not json\n");
        std::fs::write(&path, contents).unwrap();
    }
    newt_core::permission_journal::append_record(
        &path,
        newt_core::PermissionRecord::new(
            "c",
            "run_command",
            newt_core::DenialKind::Net,
            "https://example.com",
            "deny",
            "once",
        ),
    )
    .unwrap();

    let lines = permission_audit_lines(&path, 5);
    assert!(
        lines[0].starts_with("!! CHAIN BROKEN"),
        "an unparseable line must be reported, not silently dropped: {lines:?}"
    );
    let audit_header = lines
        .iter()
        .position(|l| l == "permission audit: 2 of 2 (newest first)")
        .expect("audit header must still be present");
    assert!(lines[audit_header + 1].contains("deny"));
    assert!(lines[audit_header + 1].contains("once"));
    assert!(lines[audit_header + 1].contains("net"));
    assert!(lines[audit_header + 1].contains("https://example.com"));
    assert!(lines[audit_header + 2].contains("allow"));

    let limited = permission_audit_lines(&path, 1);
    assert_eq!(
        limited[limited.len() - 2..],
        [
            "permission audit: 1 of 2 (newest first)".to_string(),
            "  deny    once      net      https://example.com via run_command".to_string()
        ]
    );
}

/// Item 1, #2529 round 2: a rotated pre-chain sibling exists — say so, and
/// render its lines (within `limit`) as unchained history rather than
/// silently omitting them.
#[test]
fn permission_audit_lines_surfaces_the_pre_chain_sibling() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("permission-log.jsonl");
    let pre_chain = newt_core::permission_journal::pre_chain_path(&path);
    let legacy = newt_core::PermissionRecord::new(
        "c",
        "run_command",
        newt_core::DenialKind::Exec,
        "/bin/legacy",
        "allow",
        "once",
    );
    std::fs::write(
        &pre_chain,
        format!("{}\n", serde_json::to_string(&legacy).unwrap()),
    )
    .unwrap();
    newt_core::permission_journal::append_record(
        &path,
        newt_core::PermissionRecord::new(
            "c",
            "run_command",
            newt_core::DenialKind::Exec,
            "/bin/new",
            "allow",
            "once",
        ),
    )
    .unwrap();

    let lines = permission_audit_lines(&path, 5);
    assert!(
        lines
            .iter()
            .any(|l| l.contains("pre-chain migration")
                && l.contains(&pre_chain.display().to_string())),
        "must name the pre-chain sibling: {lines:?}"
    );
    assert!(
        lines
            .iter()
            .any(|l| l.contains("/bin/legacy") && l.contains("unchained")),
        "must render the unchained legacy record: {lines:?}"
    );
}

/// Item 4, #2529 round 2: a log never appended-to since the upgrade is still
/// a flat `PermissionRecord` body (not yet rotated) — read it as unchained
/// history, never report it as empty.
#[test]
fn permission_audit_lines_reads_an_unrotated_flat_log() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("permission-log.jsonl");
    let legacy = newt_core::PermissionRecord::new(
        "c",
        "run_command",
        newt_core::DenialKind::Exec,
        "/bin/legacy",
        "allow",
        "once",
    );
    std::fs::write(
        &path,
        format!("{}\n", serde_json::to_string(&legacy).unwrap()),
    )
    .unwrap();

    let lines = permission_audit_lines(&path, 5);
    assert!(
        !lines.iter().any(|l| l == "no permission log entries yet"),
        "a flat pre-chain body must not read as empty: {lines:?}"
    );
    assert!(
        lines
            .iter()
            .any(|l| l.contains("/bin/legacy") && l.contains("unchained")),
        "must render the unrotated legacy record: {lines:?}"
    );
}

#[test]
fn loadout_is_reachable_as_a_status_topic_and_keeps_its_help_page() {
    // #2009 PR3: retired into `/status loadout`. The corpus teaches the
    // topic; the verb still runs and `/help loadout` still answers.
    assert!(help_lines()
        .iter()
        .any(|l| l.contains("/status <topic>") && l.contains("loadout")));
    assert!(command_help_page("loadout").is_some());
}

#[test]
fn loadout_view_renders_declared_and_resolved() {
    let l = newt_core::Loadout {
        provider: Some("dgx".into()),
        model: Some("nemotron@deep".into()),
        kit: Some("nemotron".into()),
        profile: Some("nemotron".into()),
        role: Some("python-developer".into()),
        settings: Some(newt_core::LoadoutSettings {
            num_ctx: Some(24576),
            framing: Some("Ship small.".into()),
        }),
    };
    let pick = newt_core::config::ProfilePick {
        name: "nemotron".into(),
        via: newt_core::config::PickVia::Bundle("nemotron".into()),
    };
    let view = LoadoutView {
        name: Some("dev"),
        loadout: Some(&l),
        inf_url: "http://dgx:11434",
        inf_model: "nemotron-3:33b",
        profile_pick: Some(&pick),
        persona: Some("python-developer"),
    };
    let out = view.render();
    assert!(out.contains("Active loadout: dev"), "{out}");
    // declared axes
    assert!(
        out.contains("declared:") && out.contains("nemotron@deep"),
        "{out}"
    );
    assert!(
        out.contains("24576") && out.contains("Ship small."),
        "{out}"
    );
    // resolved effect + profile provenance
    assert!(out.contains("nemotron-3:33b @ http://dgx:11434"), "{out}");
    assert!(out.contains("via bundle 'nemotron'"), "{out}");
    assert!(out.contains("python-developer"), "{out}");
}

#[test]
fn loadout_view_renders_when_none_active() {
    let view = LoadoutView {
        name: None,
        loadout: None,
        inf_url: "http://localhost:11434",
        inf_model: "llama3.1:8b",
        profile_pick: None,
        persona: None,
    };
    let out = view.render();
    assert!(out.contains("No loadout active."), "{out}");
    assert!(
        out.contains("llama3.1:8b @ http://localhost:11434"),
        "{out}"
    );
    // unset axes are explicit, not blank
    assert!(out.contains("profile") && out.contains("(none)"), "{out}");
}

#[test]
fn slash_config_returns_true() {
    // Dumps the resolved config (secrets redacted) and keeps the session alive.
    assert!(dispatch_slash("/config", "/ws", false, false, false).unwrap());
}

/// `/config` retired into `/status config` (#2009 PR3). It still runs — a
/// retired READ keeps reading — but the corpus teaches the topic, not the
/// verb, and `/help config` still answers.
#[test]
fn config_is_reachable_as_a_status_topic_and_keeps_its_help_page() {
    assert!(help_lines()
        .iter()
        .any(|l| l.contains("/status <topic>") && l.contains("config")));
    assert!(command_help_page("config").is_some());
    // The verb itself is unchanged for the deprecation window.
    assert!(dispatch_slash("/config", "/ws", false, false, false).unwrap());
}

#[test]
fn slash_unknown_returns_true() {
    assert!(dispatch_slash("/notacommand", "/ws", false, false, false).unwrap());
}

#[test]
fn retired_dials_through_the_real_router_mutate_nothing() {
    // #1665 review: the earlier no-mutation test called settings::dispatch
    // directly, bypassing lib.rs routing. Drive the FULL router. Residual gap,
    // stated honestly: with no stdout capture in this suite, deleting the
    // "tenacity"/"cognition" tokens from dispatch_slash degrades them to the
    // unknown-command print — observably identical here. What this DOES pin:
    // the router path never half-applies a retired dial, whatever it prints.
    use newt_core::cognition::{cli_cognition, set_cli_cognition, CognitionOverride};
    use newt_core::tenacity::{cli_tenacity, set_cli_tenacity, Tenacity};
    let _g = newt_core::test_guard::GlobalSettingsGuard::acquire();
    set_cli_cognition(CognitionOverride::Unset);
    set_cli_tenacity(Tenacity::Normal);
    assert!(dispatch_slash("/tenacity relentless", "/ws", false, false, false).unwrap());
    assert!(dispatch_slash("/cognition meticulous", "/ws", false, false, false).unwrap());
    assert_eq!(cli_tenacity(), Some(Tenacity::Normal));
    assert_eq!(cli_cognition(), CognitionOverride::Unset);
    // And the surviving /psyche text setters DO mutate through the router —
    // proving the routing distinction, not just shared inertness.
    assert!(dispatch_slash("/psyche tenacity relentless", "/ws", false, false, false).unwrap());
    assert_eq!(cli_tenacity(), Some(Tenacity::Relentless));
}

#[test]
fn slash_dgx_no_subcmd_returns_true() {
    assert!(dispatch_slash("/dgx", "/ws", false, false, false).unwrap());
}

// Model: GPT-5 | Harness: Codex | Operator: Shawn Hartsock | Time: 13:18 EDT | Date: 2026-08-12

/// #1785/#1792 behavioural gate at the REAL restore seam: a conversation
/// tampered outside the append path must fail `prepare_conversation_restore`
/// — the single choke point both the `/conversation restore` command and the
/// tab-switch/adoption path route through — and the refusal must leave the
/// stored rows untouched.
///
/// "No tampered transcript reaches model-visible state THROUGH THE RESTORE
/// SEAM" is enforced by the seam's own contract: `PreparedConversationRestore`
/// is the ONLY input `commit_conversation_restore` accepts, and a refusal
/// means no such value ever exists for this conversation. Nothing downstream
/// can restore what prepare never produced. (The restore seam is not the only
/// model-visible read of stored turns — `resume_context` recall reads via the
/// unverified `load`, documented as a #1792 residual at its call site — so
/// this test claims the seam, not the universe.)
///
/// This is the behavioural half of the conformance suite's static
/// `evidence_unread_is_evidence_absent` law (newt-core/tests/first_principle.rs):
/// the scan proves the verified-load call is present; this proves it refuses.
#[test]
fn restore_seam_refuses_a_tampered_transcript_and_modifies_nothing() {
    let state = tempfile::tempdir().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    let store = newt_core::ConversationStore::new(state.path(), workspace.path(), 100).unwrap();
    let personas = PersonaStore::new(state.path().join("personas"));

    let id = store.create("tamper target", None).unwrap();
    store.append_turn(&id, "u1", "a1").unwrap();
    store.append_turn(&id, "u2", "a2").unwrap();
    store.append_turn(&id, "u3", "a3").unwrap();

    // A clean restore prepares — the refusal below is about the tamper,
    // not about some unrelated precondition this test failed to meet.
    assert!(
        prepare_conversation_restore(&store, &personas, &id).is_ok(),
        "the untampered conversation must prepare"
    );

    // Tamper a middle turn outside the append path, as an attacker or a
    // careless migration would.
    let conn = rusqlite::Connection::open(state.path().join("conversations.db")).unwrap();
    let changed = conn
        .execute(
            "UPDATE turns SET assistant = 'forged' WHERE conversation_id = ?1
               AND seq = (SELECT MIN(seq) + 1 FROM turns WHERE conversation_id = ?1)",
            rusqlite::params![&id],
        )
        .unwrap();
    assert_eq!(changed, 1, "the tamper must have actually landed");

    let err = match prepare_conversation_restore(&store, &personas, &id) {
        Ok(_) => panic!("the tampered conversation must refuse to prepare"),
        Err(e) => e,
    };
    // Display (`{err}`): the tab-switch preflight renders this error with
    // `{e}`, so the integrity diagnosis must survive plain Display — an
    // outer-context-only error would show the user a refusal with no reason.
    let msg = format!("{err}");
    assert!(
        msg.contains("chain violation") && msg.contains(&id),
        "the refusal must be an integrity diagnosis naming the conversation: {msg}"
    );

    // Refusal must not mutate evidence: same rows, tamper intact, and the
    // conversation still readable for examination/export.
    let rec = store.load(&id).unwrap();
    assert_eq!(rec.turns.len(), 3, "refusal must not add or drop rows");
    assert_eq!(
        rec.turns[1].assistant, "forged",
        "refusal must not repair or re-chain the tampered row"
    );

    // The final-turn position too: repair the middle (restore the original
    // bytes) and tamper the tail, which only the tip witness can see.
    conn.execute(
        "UPDATE turns SET assistant = 'a2' WHERE conversation_id = ?1
           AND seq = (SELECT MIN(seq) + 1 FROM turns WHERE conversation_id = ?1)",
        rusqlite::params![&id],
    )
    .unwrap();
    conn.execute(
        "UPDATE turns SET assistant = 'forged tail' WHERE conversation_id = ?1
           AND seq = (SELECT MAX(seq) FROM turns WHERE conversation_id = ?1)",
        rusqlite::params![&id],
    )
    .unwrap();
    let err = match prepare_conversation_restore(&store, &personas, &id) {
        Ok(_) => panic!("a tampered final turn must also refuse to prepare"),
        Err(e) => e,
    };
    // Pin the MECHANISM, not just the refusal: a final-turn tamper is
    // invisible to the per-turn walk (nothing chains onto the last row), so
    // only the tip witness can catch it. Asserting the generic phrase alone
    // would let this leg pass via a leftover per-turn break — a refusal for
    // the wrong reason proving nothing about the witness.
    let msg = format!("{err}");
    assert!(
        msg.contains("chain violation") && msg.contains("tip witness"),
        "final-turn tamper must be caught BY THE WITNESS: {msg}"
    );
}