alix 0.5.0

A learning tool built for understanding, not just remembering.
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
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
//! End-to-end CLI integration tests: each runs the built `alix` binary as a
//! subprocess against temp decks and a temp progress store, asserting on exit
//! status and output. Unlike `tests/calibrate.rs` these are fully deterministic
//! (no real Claude) so they run in CI on every `make check`.
//!
//! A recurring property here is that a damaged progress store fails *safely*:
//! the command errors and the file on disk is left exactly as it was, never
//! silently overwritten with an empty store.

use std::{
    path::Path,
    process::{Command, Output},
};

use tempfile::TempDir;

/// Runs `alix <args...>` and returns its captured output. The child's `HOME` and
/// XDG dirs are pointed at a throwaway temp dir, so the suite never reads the
/// developer's real `~/.config/alix` or platform data dir — it's hermetic.
fn alix(args: &[&str]) -> Output {
    let home = TempDir::new().unwrap();
    Command::new(env!("CARGO_BIN_EXE_alix"))
        .args(args)
        .env("HOME", home.path())
        .env("XDG_CONFIG_HOME", home.path())
        .env("XDG_DATA_HOME", home.path())
        .output()
        .expect("failed to run the alix binary")
}

/// Like [`alix`], but with a caller-supplied (long-lived) home directory
/// instead of an ephemeral one — for a test that needs to inspect what landed
/// in the default decks/config dir, or re-invoke against the same state — plus
/// arbitrary extra env vars overlaid last. Used to make an external-binary
/// dependency (e.g. `wormhole`) deterministically absent via a stripped `PATH`,
/// without touching this test process's own environment.
fn alix_env(args: &[&str], home: &Path, extra_env: &[(&str, &str)]) -> Output {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_alix"));
    cmd.args(args)
        .env("HOME", home)
        .env("XDG_CONFIG_HOME", home)
        .env("XDG_DATA_HOME", home);
    for (k, v) in extra_env {
        cmd.env(k, v);
    }
    cmd.output().expect("failed to run the alix binary")
}

/// Writes `contents` to `dir/name` and returns its path as a string.
fn write(dir: &Path, name: &str, contents: &str) -> String {
    let path = dir.join(name);
    std::fs::write(&path, contents).unwrap();
    path.to_str().unwrap().to_string()
}

fn stdout(out: &Output) -> String {
    String::from_utf8_lossy(&out.stdout).into_owned()
}

fn stderr(out: &Output) -> String {
    String::from_utf8_lossy(&out.stderr).into_owned()
}

const VALID_DECK: &str = "# What is 2 + 2?\n    4\n";

#[test]
fn check_accepts_a_valid_deck() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "math.txt", VALID_DECK);
    let out = alix(&["doctor", &deck]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(stdout(&out).contains("1 cards"), "stdout: {}", stdout(&out));
}

#[test]
fn a_deck_file_argument_errors_with_a_picker_pointer() {
    // `alix <deck>` was removed — the picker is the one way into a review. The
    // guard fires before any server binds, so this is testable headless.
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "a.txt", VALID_DECK);
    let out = alix(&[&deck]);
    assert!(!out.status.success(), "a deck-file argument should error");
    assert!(
        stderr(&out).contains("was removed"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn the_review_subcommand_is_gone() {
    // `alix review x.txt` now parses as a launcher path plus an unexpected
    // extra positional — the subcommand no longer exists.
    let out = alix(&["review", "x.txt"]);
    assert!(
        !out.status.success(),
        "the review subcommand should be gone"
    );
}

#[test]
fn check_rejects_a_malformed_deck() {
    let dir = TempDir::new().unwrap();
    // A card front with no answer line is a parse error.
    let deck = write(dir.path(), "broken.txt", "# a front with no answer\n");
    let out = alix(&["doctor", &deck]);
    assert!(
        !out.status.success(),
        "a malformed deck should fail the check"
    );
    assert!(stderr(&out).contains("error:"), "stderr: {}", stderr(&out));
}

#[test]
fn doctor_warns_about_a_malformed_deadline_without_failing() {
    let dir = TempDir::new().unwrap();
    let ws = dir.path();
    std::fs::write(ws.join("alix.toml"), "").unwrap();
    std::fs::write(
        ws.join("alix.local.toml"),
        "[review]\ndeadline = \"soonish\"\n",
    )
    .unwrap();
    write(ws, "cards.txt", VALID_DECK);
    let out = alix(&["doctor", ws.to_str().unwrap()]);
    assert!(
        out.status.success(),
        "warnings should not fail the doctor check"
    );
    let err = stderr(&out);
    assert!(err.contains("deadline"), "stderr: {err}");
    assert!(err.contains("warning"), "stderr: {err}");
}

#[test]
fn workspace_init_writes_both_documented_manifests() {
    let dir = TempDir::new().unwrap();
    let ws = dir.path().join("fresh");
    let out = alix(&["workspace", "init", ws.to_str().unwrap(), "--title", "T"]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let manifest = std::fs::read_to_string(ws.join("alix.toml")).unwrap();
    assert!(manifest.contains("title = \"T\""), "{manifest}");
    assert!(manifest.contains("[defaults]"), "headers stay uncommented");
    let local = std::fs::read_to_string(ws.join("alix.local.toml")).unwrap();
    assert!(local.contains("[review]"), "headers stay uncommented");
    assert!(local.contains("never shared"), "{local}");
    assert!(ws.join("assets").is_dir());
}

#[test]
fn workspace_deadline_shows_sets_and_clears() {
    let dir = TempDir::new().unwrap();
    let ws = dir.path().join("ws");
    std::fs::create_dir(&ws).unwrap();
    std::fs::write(ws.join("alix.toml"), "title = \"Ws\"\n").unwrap();
    std::fs::write(ws.join("cards.txt"), "# Q?\n    A\n").unwrap();

    let out = alix(&["workspace", "deadline", ws.to_str().unwrap()]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("no deadline"),
        "stdout: {}",
        stdout(&out)
    );

    let out = alix(&["workspace", "deadline", ws.to_str().unwrap(), "2099-01-02"]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        std::fs::read_to_string(ws.join("alix.local.toml"))
            .unwrap()
            .contains("2099-01-02")
    );

    let out = alix(&["workspace", "deadline", ws.to_str().unwrap()]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let show_output = stdout(&out);
    assert!(show_output.contains("2099-01-02"), "stdout: {show_output}");
    assert!(show_output.contains("days"), "stdout: {show_output}");

    let out = alix(&["workspace", "deadline", ws.to_str().unwrap(), "clear"]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        !std::fs::read_to_string(ws.join("alix.local.toml"))
            .unwrap()
            .contains("deadline")
    );

    let out = alix(&["workspace", "deadline", ws.to_str().unwrap(), "not-a-date"]);
    assert!(!out.status.success(), "stderr: {}", stderr(&out));
}

#[test]
fn workspace_deadline_rejects_non_workspace_non_decks_dir() {
    let dir = TempDir::new().unwrap();
    let empty_dir = dir.path().join("empty");
    std::fs::create_dir(&empty_dir).unwrap();

    let out = alix(&["workspace", "deadline", empty_dir.to_str().unwrap()]);
    assert!(!out.status.success(), "stderr: {}", stderr(&out));
    let err = stderr(&out);
    assert!(
        err.contains("not a workspace")
            || err.contains("not a decks folder")
            || err.contains("not a workspace or decks folder"),
        "stderr should mention neither workspace nor decks folder: {err}"
    );
}

#[test]
fn workspace_deadline_rejects_a_decks_folder_without_a_manifest() {
    // DECISION 2026-07-15: deadline keys apply only inside a real workspace
    // (manifest present); a plain decks folder is rejected and pointed at the
    // upgrade path, rather than silently accepted like before.
    let dir = TempDir::new().unwrap();
    let plain = dir.path().join("plain");
    std::fs::create_dir(&plain).unwrap();
    write(&plain, "cards.txt", "# Q?\n    A\n");

    let out = alix(&["workspace", "deadline", plain.to_str().unwrap()]);
    assert!(!out.status.success(), "stderr: {}", stderr(&out));
    let err = stderr(&out);
    assert!(err.contains("workspace init"), "stderr: {err}");
}

#[test]
fn stats_on_a_folder_reports_every_deck_inside() {
    let dir = TempDir::new().unwrap();
    write(dir.path(), "alpha.txt", "# a?\n    a\n");
    write(dir.path(), "beta.txt", "# b?\n    b\n");
    let store = dir.path().join("elsewhere.json");
    let out = alix(&[
        "stats",
        dir.path().to_str().unwrap(),
        "--store",
        store.to_str().unwrap(),
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let text = stdout(&out);
    assert!(text.contains("alpha"), "stdout: {text}");
    assert!(text.contains("beta"), "stdout: {text}");
}

#[test]
fn reset_on_a_workspace_clears_every_member_in_its_own_store() {
    // A workspace target expands to its member decks and hits the workspace's
    // own progress.json — including the mastered flag.
    let dir = TempDir::new().unwrap();
    let ws = dir.path().join("eng");
    std::fs::create_dir(&ws).unwrap();
    std::fs::write(ws.join("alix.toml"), "title = \"Eng\"\n").unwrap();
    let a = write(&ws, "a.txt", "# qa\n    ans-a\n");
    let b = write(&ws, "b.txt", "# qb\n    ans-b\n");
    let store_path = ws.join("progress.json");
    let mut store = alix::store::Store::open(&store_path).unwrap();
    for deck in [&a, &b] {
        let cards = alix::parser::parse_str(
            Path::new(deck).file_name().unwrap().to_str().unwrap(),
            &std::fs::read_to_string(deck).unwrap(),
        )
        .unwrap();
        store.get_or_insert(cards[0].id(), 0);
    }
    store.set_deck_mastered("a.txt", 0);
    store.save().unwrap();

    let out = alix(&["reset", ws.to_str().unwrap(), "--yes"]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));

    let reloaded = alix::store::Store::open(&store_path).unwrap();
    assert_eq!(0, reloaded.len(), "member card progress should be gone");
    assert!(
        !reloaded.deck_mastered("a.txt"),
        "the mastered flag should be cleared"
    );
}

#[test]
fn stats_reports_a_fresh_deck_against_an_empty_store() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "math.txt", VALID_DECK);
    let store = dir.path().join("progress.json"); // does not exist yet
    let out = alix(&["stats", &deck, "--store", store.to_str().unwrap()]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("not started"),
        "stdout: {}",
        stdout(&out)
    );
}

#[test]
fn reset_all_clears_a_seeded_store() {
    let dir = TempDir::new().unwrap();
    let store = write(
        dir.path(),
        "progress.json",
        r#"{"version":1,"cards":{"123":{"acquired_ms":0}}}"#,
    );
    let out = alix(&["reset", "--all", "--yes", "--store", &store]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("Reset 1 card(s)."),
        "stdout: {}",
        stdout(&out)
    );
    // The card is gone from the rewritten file.
    let after = std::fs::read_to_string(&store).unwrap();
    assert!(!after.contains("123"), "store still has the card: {after}");
}

/// A minimal virtual card belonging to `parent`, for seeding a store directly
/// via the lib rather than hand-authoring its on-disk JSON shape. Its id is the
/// `Card::id` of the card `parse(parent, text)` yields — identical to a deck card.
fn sample_virtual_card(parent: &str) -> alix::store::VirtualCard {
    let text = "# front\n\tback\n";
    let id = alix::parser::parse_str(parent, text).unwrap()[0].id();
    alix::store::VirtualCard {
        id,
        kind: alix::store::VirtualKind::Remediation,
        parent: parent.to_string(),
        text: text.to_string(),
        created_ms: 0,
    }
}

#[test]
fn reset_all_clears_virtual_cards() {
    // A store holding ONLY virtual cards must still be reset by `--all`: the
    // count sees the virtual card's schedule in `store.cards` (seeded beside the
    // sidecar entry), and the clear must also drop its sidecar content.
    let dir = TempDir::new().unwrap();
    let store_path = dir.path().join("progress.json");
    let mut store = alix::store::Store::open(&store_path).unwrap();
    let vc = sample_virtual_card("math.txt");
    let id = vc.id;
    store.insert_virtual(vc);
    store.get_or_insert(id, 0); // the virtual card's schedule lives in store.cards
    store.save().unwrap();

    let out = alix(&[
        "reset",
        "--all",
        "--yes",
        "--store",
        store_path.to_str().unwrap(),
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        !stdout(&out).contains("No stored progress"),
        "a virtual-only store wrongly reported nothing to reset: {}",
        stdout(&out)
    );

    let reloaded = alix::store::Store::open(&store_path).unwrap();
    assert_eq!(0, reloaded.iter_virtual_cards().count());
}

#[test]
fn deck_reset_drops_that_decks_virtual_cards() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "math.txt", VALID_DECK);
    let store_path = dir.path().join("progress.json");

    let mut store = alix::store::Store::open(&store_path).unwrap();
    let math_vc = sample_virtual_card("math.txt");
    let math_id = math_vc.id;
    store.insert_virtual(math_vc);
    let other_vc = sample_virtual_card("other.txt");
    let other_id = other_vc.id;
    store.insert_virtual(other_vc);
    store.save().unwrap();

    let out = alix(&[
        "reset",
        &deck,
        "--yes",
        "--store",
        store_path.to_str().unwrap(),
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));

    let reloaded = alix::store::Store::open(&store_path).unwrap();
    assert!(
        reloaded.get_virtual(math_id).is_none(),
        "the reset deck's own virtual card should be dropped"
    );
    assert!(
        reloaded.get_virtual(other_id).is_some(),
        "another deck's virtual card should survive"
    );
}

#[test]
fn deck_reset_without_yes_leaves_store_unchanged() {
    // A declined/failed confirmation must not partially apply the reset: the
    // deck's mastered flag, its virtual card, and its authored progress must
    // all still be there afterwards, byte-for-byte.
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "math.txt", VALID_DECK);
    let store_path = dir.path().join("progress.json");

    let card_id = alix::deck::Deck::load(&deck).unwrap().cards[0].id();
    let mut store = alix::store::Store::open(&store_path).unwrap();
    store.get_or_insert(card_id, 0);
    store.set_deck_mastered("math.txt", 0);
    store.insert_virtual(sample_virtual_card("math.txt"));
    store.save().unwrap();
    let before = std::fs::read_to_string(&store_path).unwrap();

    // No `--yes` and no TTY in the test subprocess: the command must error.
    let out = alix(&["reset", &deck, "--store", store_path.to_str().unwrap()]);
    assert!(
        !out.status.success(),
        "a no-TTY reset without --yes should error"
    );

    let after = std::fs::read_to_string(&store_path).unwrap();
    assert_eq!(
        before, after,
        "the store on disk must be untouched by a declined/failed reset"
    );
    let reloaded = alix::store::Store::open(&store_path).unwrap();
    assert!(reloaded.deck_mastered("math.txt"), "mastered flag wiped");
    assert!(reloaded.get(card_id).is_some(), "authored progress wiped");
    assert_eq!(
        1,
        reloaded.virtual_cards_for("math.txt").len(),
        "virtual card wiped"
    );
}

#[test]
fn confirmed_virtual_only_deck_reset_clears_virtual() {
    // A deck with ONLY a virtual card (no authored progress, not mastered) must
    // still have that virtual card cleared and persisted on a confirmed reset.
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "math.txt", VALID_DECK);
    let store_path = dir.path().join("progress.json");

    let mut store = alix::store::Store::open(&store_path).unwrap();
    store.insert_virtual(sample_virtual_card("math.txt"));
    store.save().unwrap();

    let out = alix(&[
        "reset",
        &deck,
        "--yes",
        "--store",
        store_path.to_str().unwrap(),
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));

    let reloaded = alix::store::Store::open(&store_path).unwrap();
    assert_eq!(0, reloaded.virtual_cards_for("math.txt").len());
}

#[test]
fn a_progress_file_of_any_version_loads_pre_1_0() {
    // Pre-1.0 there is no store version fence: a store written by a "newer" alix
    // (higher version) loads best-effort rather than being refused — we break the
    // format freely and never bump or migrate the version.
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "math.txt", VALID_DECK);
    let store = write(dir.path(), "progress.json", r#"{"version":999,"cards":{}}"#);

    let out = alix(&["stats", &deck, "--store", &store]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
}

#[test]
fn a_corrupt_progress_file_fails_without_overwriting_it() {
    // A damaged store must not be silently replaced with an empty one — the
    // command fails and the bytes on disk are preserved for recovery.
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "math.txt", VALID_DECK);
    let garbage = "{ this is not valid json";
    let store = write(dir.path(), "progress.json", garbage);

    let out = alix(&["stats", &deck, "--store", &store]);
    assert!(
        !out.status.success(),
        "a corrupt store should fail the command"
    );
    assert_eq!(garbage, std::fs::read_to_string(&store).unwrap());
}

/// Writes an executable fake `claude` at `dir/fake-claude` that drains stdin
/// (so the prompt write never races into a broken pipe) then prints `reply`
/// verbatim, and returns its path. Mirrors `testutil::fake_reply`, but the CLI
/// suite drives the built binary as a subprocess so it can't reach that crate
/// helper — the fake is wired in via a `--config` TOML pointing `[ask] command`
/// at this script.
fn fake_claude(dir: &Path, reply: &str) -> String {
    use std::os::unix::fs::PermissionsExt;
    let reply_path = dir.join("fake-reply.txt");
    std::fs::write(&reply_path, reply).unwrap();
    let script = dir.join("fake-claude");
    std::fs::write(
        &script,
        format!(
            "#!/bin/sh\ncat >/dev/null; cat {}\n",
            reply_path.to_str().unwrap()
        ),
    )
    .unwrap();
    std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
    script.to_str().unwrap().to_string()
}

#[test]
fn augment_target_format_caches_a_reshape() {
    // `deck augment --target format` reshapes a badly-shaped plain card and
    // writes the result to the sidecar `augment.json` beside the store, without
    // touching the deck file. The Claude call is faked by a config-wired CLI.
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "parts.txt", "# List the parts\n    A, B, C\n");
    // The model returns a structured reshape for card index 0: a list body and a
    // line-by-line mode suggestion.
    let cli = fake_claude(
        dir.path(),
        r#"{"0": {"back": ["A", "B", "C"], "mode": "line"}}"#,
    );
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let store = dir.path().join("p.json");
    let out = alix(&[
        "deck",
        "augment",
        &deck,
        "--target",
        "format",
        "--store",
        store.to_str().unwrap(),
        "--config",
        &config,
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));

    // The reshape is cached beside the store, not written back into the deck.
    let cached = std::fs::read_to_string(dir.path().join("augment.json")).unwrap();
    assert!(cached.contains("\"A\""), "augment.json: {cached}");
    assert!(cached.contains("LineByLine"), "augment.json: {cached}");
    let deck_after = std::fs::read_to_string(&deck).unwrap();
    assert_eq!(
        deck_after, "# List the parts\n    A, B, C\n",
        "deck untouched"
    );
}

#[test]
fn augment_target_format_also_covers_a_decks_virtual_card() {
    // A deck's synthesized virtual (remediation) cards get the same format
    // treatment as its authored ones — `set_format` keys by the synth card's
    // real `Card::id`, so a re-drilled remediation card is reshaped too.
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "parts.txt", "# List the parts\n    A, B, C\n");

    let store_path = dir.path().join("p.json");
    let mut store = alix::store::Store::open(&store_path).unwrap();
    let vc = sample_virtual_card("parts.txt");
    let virtual_id = vc.id;
    store.insert_virtual(vc);
    store.save().unwrap();

    // The deck's one plain card is warmed at index 0; the deck's one virtual
    // card follows it at index 1.
    let cli = fake_claude(dir.path(), r#"{"1": {"back": ["X", "Y"], "mode": "line"}}"#);
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let out = alix(&[
        "deck",
        "augment",
        &deck,
        "--target",
        "format",
        "--store",
        store_path.to_str().unwrap(),
        "--config",
        &config,
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));

    let cached = std::fs::read_to_string(dir.path().join("augment.json")).unwrap();
    assert!(
        cached.contains(&virtual_id.to_string()),
        "augment.json should key a format entry by the virtual card's id: {cached}"
    );
    assert!(cached.contains("\"X\""), "augment.json: {cached}");
}

#[test]
fn augment_target_format_skips_an_orphaned_virtual_card_colliding_with_a_real_deck_card() {
    // A partial cloze promote can leave an orphaned sidecar `virtual_cards`
    // entry whose id collides with a real deck card (see `promote_virtual`).
    // `deck augment --target format` must filter those out exactly like
    // `assemble::select`'s injection does, or the same card gets warmed twice.
    let dir = TempDir::new().unwrap();
    let deck_text = "# List the parts\n    A, B, C\n";
    let deck = write(dir.path(), "parts.txt", deck_text);
    let real_id = alix::parser::parse_str("parts.txt", deck_text).unwrap()[0].id();

    let store_path = dir.path().join("p.json");
    let mut store = alix::store::Store::open(&store_path).unwrap();
    store.insert_virtual(alix::store::VirtualCard {
        id: real_id, // collides with the real deck card's id — simulates an orphan
        kind: alix::store::VirtualKind::Remediation,
        parent: "parts.txt".to_string(),
        // Must reproduce `real_id` when parsed (`synthesize_virtual` matches by
        // id), so an orphan left behind by a partial promote uses the same text
        // as the now-real deck card it collides with.
        text: deck_text.to_string(),
        created_ms: 0,
    });
    store.save().unwrap();

    // Only one item should ever be warmed (the real deck card) — if the orphan
    // isn't filtered, the fake reply's index 1 lookup would matter too, but
    // asserting "1 of 1" below is what actually pins the count down.
    let cli = fake_claude(
        dir.path(),
        r#"{"0": {"back": ["A", "B", "C"], "mode": "line"}}"#,
    );
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let out = alix(&[
        "deck",
        "augment",
        &deck,
        "--target",
        "format",
        "--store",
        store_path.to_str().unwrap(),
        "--config",
        &config,
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("augmented 1 of 1 cards"),
        "the colliding orphan must not be double-counted alongside the real card: {}",
        stdout(&out)
    );
}

#[test]
fn missing_backend_reports_install_hint() {
    // Pointing `[ask] command` at a nonexistent binary yields the install hint,
    // not a raw OS error. Uses `deck generate` (no TTY needed) to reach the runner.
    let dir = TempDir::new().unwrap();
    let config = write(
        dir.path(),
        "config.toml",
        "[ask]\ncommand = \"/nonexistent/claude-xyz\"\ntimeout_secs = 5\n",
    );
    let out = alix(&[
        "generate",
        "https://example.org/page",
        "--config",
        &config,
        "--print",
    ]);
    let err = stderr(&out);
    assert!(!out.status.success(), "a missing backend must fail: {err}");
    assert!(
        err.contains("is it installed"),
        "should hint at installation: {err}"
    );
}

/// Creates `n` small files in `dir`, each `bytes` bytes, to simulate a large
/// source tree.
fn make_large_tree(dir: &std::path::Path, n: usize, bytes: usize) {
    let content = vec![0u8; bytes];
    for i in 0..n {
        std::fs::write(dir.join(format!("f{i}.bin")), &content).unwrap();
    }
}

#[test]
fn oversized_local_source_without_yes_bails_with_guidance() {
    // An oversized source tree with no TTY and no --yes must bail.
    let dir = TempDir::new().unwrap();
    // Write enough bytes to exceed the 5 MB default threshold.
    make_large_tree(dir.path(), 10, 600_000); // 6 MB total
    let config = write(
        dir.path(),
        "config.toml",
        // A nonexistent backend: we never reach the model, but we need the guard to fire.
        "[ask]\ncommand = \"/nonexistent/claude-xyz\"\ntimeout_secs = 5\n",
    );
    let src = dir.path().to_str().unwrap();
    let out = alix(&["generate", src, "--config", &config, "--print"]);
    let err = stderr(&out);
    assert!(!out.status.success(), "should fail without --yes: {err}");
    // The error must name the guard condition and point at the fix.
    assert!(err.contains("--yes"), "error must mention --yes: {err}");
    assert!(
        err.contains("large source tree") || err.contains("files"),
        "error must describe the source size: {err}"
    );
}

#[test]
fn oversized_local_source_with_yes_proceeds_past_the_guard() {
    // With --yes the guard is bypassed and we reach the backend (which may fail
    // because the binary doesn't exist — that's fine; what matters is we got
    // past the size check).
    let dir = TempDir::new().unwrap();
    make_large_tree(dir.path(), 10, 600_000); // 6 MB total
    let config = write(
        dir.path(),
        "config.toml",
        "[ask]\ncommand = \"/nonexistent/claude-xyz\"\ntimeout_secs = 5\n",
    );
    let src = dir.path().to_str().unwrap();
    let out = alix(&["generate", src, "--yes", "--config", &config, "--print"]);
    let err = stderr(&out);
    // The error must NOT be the guard refusal — it should be the missing-binary
    // hint (or something from the model runner).
    assert!(
        !err.contains("pass --yes to proceed"),
        "guard must not fire with --yes: {err}"
    );
    // It should have reached the backend and failed there instead.
    assert!(
        err.contains("is it installed") || err.contains("nonexistent"),
        "should reach the backend: {err}"
    );
}

#[test]
fn undersized_local_source_proceeds_without_yes() {
    // A source tree under the threshold passes the guard silently without --yes.
    let dir = TempDir::new().unwrap();
    write(dir.path(), "small.txt", "hello world\n");
    let config = write(
        dir.path(),
        "config.toml",
        "[ask]\ncommand = \"/nonexistent/claude-xyz\"\ntimeout_secs = 5\n",
    );
    let out = alix(&[
        "generate",
        dir.path().to_str().unwrap(),
        "--config",
        &config,
        "--print",
    ]);
    let err = stderr(&out);
    // Must not hit the guard — passes through to the backend.
    assert!(
        !err.contains("pass --yes to proceed"),
        "guard must not fire for small trees: {err}"
    );
    // Guard against vacuous passes (this test once kept invoking a deleted
    // `deck generate` spelling): the run must get as far as the explore pass.
    assert!(
        err.contains("Exploring") || err.contains("is it installed"),
        "should reach the exploration/backend: {err}"
    );
}

#[test]
fn a_populated_workspace_no_longer_blocks_the_build() {
    // A populated `--workspace` used to bail before exploring (added, then
    // reverted the same day, once staging-then-merge landed): the build now
    // always stages and merges, so a populated destination must never stop
    // the run before it even reaches exploration/the backend.
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    std::fs::create_dir_all(&src).unwrap();
    write(&src, "notes.md", "# some source material\n");
    let ws = dir.path().join("ws");
    std::fs::create_dir_all(&ws).unwrap();
    write(&ws, "existing.txt", "# q\n  a\n");
    let config = write(
        dir.path(),
        "config.toml",
        "[ask]\ncommand = \"/nonexistent/claude-xyz\"\ntimeout_secs = 5\n",
    );
    let out = alix(&[
        "generate",
        src.to_str().unwrap(),
        "--workspace",
        ws.to_str().unwrap(),
        "--config",
        &config,
    ]);
    let err = stderr(&out);
    assert!(
        !err.contains("already has files"),
        "the populated-dest guard is gone: {err}"
    );
    assert!(
        err.contains("is it installed") || err.contains("nonexistent"),
        "should get past the destination check to the exploration/backend failure: {err}"
    );
}

#[test]
fn a_leftover_staging_dir_blocks_a_headless_rebuild_until_confirmed() {
    // A staging dir kept from a previous build's merge conflicts holds the
    // only copy of that content — a rebuild must ask before wiping it, and
    // ask before spending on exploration, not after.
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    std::fs::create_dir_all(&src).unwrap();
    write(&src, "notes.md", "# some source material\n");
    let ws = dir.path().join("ws");
    std::fs::create_dir_all(&ws).unwrap();
    let staging = dir.path().join(".ws.building");
    std::fs::create_dir_all(&staging).unwrap();
    write(&staging, "orphan.txt", "# q\n  a\n");
    let config = write(
        dir.path(),
        "config.toml",
        "[ask]\ncommand = \"/nonexistent/claude-xyz\"\ntimeout_secs = 5\n",
    );

    // Without --yes: headless (no TTY) — confirm bails before any exploration.
    let out = alix(&[
        "generate",
        src.to_str().unwrap(),
        "--workspace",
        ws.to_str().unwrap(),
        "--config",
        &config,
    ]);
    assert!(!out.status.success(), "should fail without confirmation");
    let err = stderr(&out);
    assert!(
        err.contains(staging.to_str().unwrap())
            || err.contains("holds files from a previous build"),
        "should mention the staging path or the confirm question: {err}"
    );
    assert!(
        !err.contains("Exploring"),
        "should bail before spending on exploration: {err}"
    );
    assert!(
        staging.is_dir(),
        "declining must leave the staging dir alone"
    );

    // With --yes: the staging confirm is skipped, so the run reaches the
    // (fake) backend failure.
    let out = alix(&[
        "generate",
        src.to_str().unwrap(),
        "--workspace",
        ws.to_str().unwrap(),
        "--config",
        &config,
        "--yes",
    ]);
    let err = stderr(&out);
    assert!(
        err.contains("is it installed") || err.contains("nonexistent"),
        "should get past the staging confirm to the exploration/backend failure: {err}"
    );
}

#[test]
fn deck_check_validates_like_the_old_check() {
    // `alix deck check <deck>` must parse and report cards exactly as the old
    // `alix check <deck>` did.
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "math.txt", VALID_DECK);
    let out = alix(&["doctor", &deck]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(stdout(&out).contains("1 cards"), "stdout: {}", stdout(&out));
}

#[test]
fn bare_check_is_gone() {
    // After the move, `alix check <deck>` is no longer a valid subcommand.
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "math.txt", VALID_DECK);
    let out = alix(&["check", &deck]);
    assert!(
        !out.status.success(),
        "the old `alix check` must be gone (clap should error)"
    );
}

#[test]
fn doctor_backends_reports_a_missing_backend() {
    // Pointing `[ask] command` at a nonexistent binary → the health probe
    // reports a not-installed message and the command exits with failure.
    let dir = TempDir::new().unwrap();
    let config = write(
        dir.path(),
        "config.toml",
        "[ask]\ncommand = \"/nonexistent/no-such-cli\"\ntimeout_secs = 5\n",
    );
    let out = alix(&["doctor", "--backends", "--config", &config]);
    assert!(
        !out.status.success(),
        "a missing backend must exit with failure"
    );
    let combined = format!("{}{}", stdout(&out), stderr(&out));
    assert!(
        combined.contains("installed") || combined.contains("not found") || combined.contains('✗'),
        "output should report the failure: {combined}"
    );
}

#[test]
fn doctor_backends_reports_a_working_backend() {
    // A fake CLI that drains stdin and prints a reply → the probe reports ✓.
    let dir = TempDir::new().unwrap();
    let cli = fake_claude(dir.path(), "OK");
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let out = alix(&["doctor", "--backends", "--config", &config]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let combined = format!("{}{}", stdout(&out), stderr(&out));
    assert!(
        combined.contains('✓') || combined.contains("ready") || combined.contains("ok"),
        "output should report success: {combined}"
    );
}

#[test]
fn doctor_all_backends_probes_each() {
    // `--all` probes all four backends and prints a line per backend.  All
    // will fail (none are installed in CI), but there must be output for each.
    let dir = TempDir::new().unwrap();
    let config = write(dir.path(), "config.toml", "[ask]\ntimeout_secs = 5\n");
    let out = alix(&["doctor", "--all-backends", "--config", &config]);
    // --all always exits with the overall status but must produce output for
    // each of the four backends.
    let combined = format!("{}{}", stdout(&out), stderr(&out));
    for name in ["claude", "gemini", "codex", "copilot"] {
        assert!(
            combined.contains(name),
            "output must mention '{name}': {combined}"
        );
    }
}

/// A store JSON fragment for one card: a Recall schedule in FSRS state 2
/// (`review`) due in the past, a Reconstruct schedule in state 1 (`learning`)
/// also past-due, and a set `recognized_ms`.
fn both_depths_due_card(card_id: u64) -> String {
    format!(
        r#""{card_id}":{{"acquired_ms":1000,"recall":{{"stability":10.0,"difficulty":5.0,"reps":5,"lapses":0,"state":2,"scheduled_days":20,"last_review_ms":1000,"due_ms":2000,"learning_goods":2}},"reconstruct":{{"stability":8.0,"difficulty":5.0,"reps":3,"lapses":0,"state":1,"scheduled_days":10,"last_review_ms":1000,"due_ms":2000,"learning_goods":1}},"recognized_ms":1000,"total_reviews":5,"total_passes":5}}"#
    )
}

#[test]
fn list_shows_per_depth_labels_and_recognized_mark() {
    let dir = TempDir::new().unwrap();
    // Card 1: recall=review (state 2), reconstruct=learning (state 1), recognized.
    // Card 2: recall=learning only — no reconstruct schedule, not recognized.
    let deck_text = "# Q1\n\tA1\n\n# Q2\n\tA2\n";
    let deck = write(dir.path(), "cards.txt", deck_text);
    let cards = alix::parser::parse_str("cards.txt", deck_text).unwrap();
    let (id1, id2) = (cards[0].id(), cards[1].id());
    let card1 = both_depths_due_card(id1);
    let card2 = format!(
        r#""{id2}":{{"acquired_ms":1000,"recall":{{"stability":1.0,"difficulty":5.0,"reps":1,"lapses":0,"state":1,"scheduled_days":0,"last_review_ms":1000,"due_ms":2000,"learning_goods":1}},"total_reviews":1,"total_passes":1}}"#
    );
    let store = write(
        dir.path(),
        "store.json",
        &format!(r#"{{"version":1,"cards":{{{card1},{card2}}}}}"#),
    );
    let out = alix(&["list", &deck, "--store", &store]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let result = stdout(&out);
    // Slot order is recall|reconstruct — a swap would print [  learning|    review].
    assert!(
        result.contains("[    review|  learning]✓"),
        "recall slot first, then reconstruct, then the recognized mark: {result}"
    );
    // An absent schedule shows `-` in its slot; no recognized mark → space.
    assert!(
        result.contains("[  learning|         -] "),
        "a depth without a schedule shows '-': {result}"
    );
}

#[test]
fn stats_shows_per_depth_due_counts() {
    let dir = TempDir::new().unwrap();
    let deck_text = "# Q1\n\tA1\n";
    let deck = write(dir.path(), "stats.txt", deck_text);
    let card_id = alix::parser::parse_str("stats.txt", deck_text).unwrap()[0].id();
    let card = both_depths_due_card(card_id);
    let store = write(
        dir.path(),
        "store.json",
        &format!(r#"{{"version":1,"cards":{{{card}}}}}"#),
    );
    let out = alix(&["stats", &deck, "--store", &store]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let result = stdout(&out);
    assert!(
        result.contains("due now (recall):      1"),
        "the past-due recall schedule must be counted: {result}"
    );
    assert!(
        result.contains("due now (reconstruct): 1"),
        "the past-due reconstruct schedule must be counted: {result}"
    );
}

// ── common.rs: target/workspace resolution errors ───────────────────────────

#[test]
fn a_nonexistent_target_errors_neither_deck_nor_folder() {
    let dir = TempDir::new().unwrap();
    let ghost = dir.path().join("ghost");
    let out = alix(&["stats", ghost.to_str().unwrap()]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("neither a deck file nor a folder"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn an_empty_folder_target_errors_no_decks() {
    let dir = TempDir::new().unwrap();
    let empty = dir.path().join("empty");
    std::fs::create_dir(&empty).unwrap();
    let out = alix(&["stats", empty.to_str().unwrap()]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("no decks in"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn importing_into_a_nonexistent_workspace_errors() {
    let dir = TempDir::new().unwrap();
    let tsv = write(dir.path(), "cards.tsv", "Q1\tA1\n");
    let ghost_ws = dir.path().join("ghost-ws");
    let out = alix(&[
        "deck",
        "import",
        &tsv,
        "--workspace",
        ghost_ws.to_str().unwrap(),
    ]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("no folder at"),
        "stderr: {}",
        stderr(&out)
    );
}

// ── the bare `alix [dir]` launcher: pre-flight error paths ──────────────────

#[test]
fn a_nonexistent_launch_dir_errors_not_a_folder() {
    let dir = TempDir::new().unwrap();
    let ghost = dir.path().join("ghost");
    let out = alix(&[ghost.to_str().unwrap()]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("is not a folder"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn the_launcher_reports_an_unreadable_config_path() {
    let dir = TempDir::new().unwrap();
    let bad_config = dir.path().join("nope.toml"); // deliberately never written
    let out = alix(&[
        dir.path().to_str().unwrap(),
        "--config",
        bad_config.to_str().unwrap(),
    ]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("cannot read config file"),
        "stderr: {}",
        stderr(&out)
    );
}

// ── `alix config` ────────────────────────────────────────────────────────────

#[test]
fn config_bare_shows_key_bindings_and_ask_settings() {
    let out = alix(&["config"]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let text = stdout(&out);
    assert!(text.contains("key bindings:"), "{text}");
    assert!(text.contains("ask:"), "{text}");
    assert!(text.contains("generate:"), "{text}");
}

#[test]
fn config_init_writes_a_file_then_refuses_to_clobber_it() {
    let home = TempDir::new().unwrap();
    let out = alix_env(&["config", "--init"], home.path(), &[]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(stdout(&out).contains("wrote "), "{}", stdout(&out));

    let out2 = alix_env(&["config", "--init"], home.path(), &[]);
    assert!(
        !out2.status.success(),
        "a second --init must refuse to clobber"
    );
    assert!(
        stderr(&out2).contains("already exists"),
        "stderr: {}",
        stderr(&out2)
    );
}

// ── `alix doctor` ────────────────────────────────────────────────────────────

#[test]
fn doctor_bare_reports_config_store_and_decks_sections() {
    let out = alix(&["doctor"]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let text = format!("{}{}", stdout(&out), stderr(&out));
    assert!(text.contains("config"), "{text}");
    assert!(text.contains("store"), "{text}");
    assert!(text.contains("decks"), "{text}");
}

#[test]
fn bare_and_rooted_doctor_share_the_in_folder_store() {
    let decks = tempfile::tempdir().unwrap();
    std::fs::write(decks.path().join("q.txt"), "# Q\n    A\n").unwrap();

    // A config pointing decks_dir at our temp folder.
    let cfg = decks.path().join("config.toml");
    std::fs::write(
        &cfg,
        format!("decks_dir = \"{}\"\n", decks.path().display()),
    )
    .unwrap();
    let cfg = cfg.to_str().unwrap();
    let dir = decks.path().to_str().unwrap();
    let in_folder = decks.path().join("progress.json");
    let in_folder = in_folder.display().to_string();

    // No DIR: the "configured setup" branch must use the in-folder store,
    // not the global platform store.
    let bare = String::from_utf8_lossy(&alix(&["doctor", "--config", cfg]).stdout).into_owned();
    assert!(bare.contains(&in_folder), "bare doctor store, got:\n{bare}");

    // Explicit root resolves to the SAME store (the gotcha is gone).
    let rooted =
        String::from_utf8_lossy(&alix(&["doctor", dir, "--config", cfg]).stdout).into_owned();
    assert!(
        rooted.contains(&in_folder),
        "rooted doctor store, got:\n{rooted}"
    );
}

#[test]
fn doctor_on_a_folder_target_scopes_to_its_own_store() {
    let dir = TempDir::new().unwrap();
    write(dir.path(), "a.txt", VALID_DECK);
    let out = alix(&["doctor", dir.path().to_str().unwrap()]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(stdout(&out).contains("1 decks"), "{}", stdout(&out));
}

#[test]
fn doctor_reports_a_broken_config_as_a_failing_finding() {
    let dir = TempDir::new().unwrap();
    let config = write(dir.path(), "config.toml", "[review]\nfrobnicate = 1\n");
    let out = alix(&["doctor", "--config", &config]);
    assert!(!out.status.success(), "a broken config should fail doctor");
    let text = format!("{}{}", stdout(&out), stderr(&out));
    assert!(text.contains("config"), "{text}");
}

// ── `stats`/`list`/`reset` agree with the served root's store ───────────────

#[test]
fn stats_on_a_loose_deck_resolves_the_decks_dir_root_store_like_review_does() {
    // Bare `alix` (and its picker) reads/writes a loose deck's progress at
    // `<decks_dir>/progress.json`. `alix stats` must resolve the SAME file —
    // proven with a corrupt-file discriminator: if `stats` instead fell back
    // to the global platform store (the pre-fix bug), the folder's corrupt
    // file would never be opened and the command would succeed instead of
    // failing.
    let decks = tempfile::tempdir().unwrap();
    let deck = write(decks.path(), "math.txt", VALID_DECK);

    let cfg = decks.path().join("config.toml");
    std::fs::write(
        &cfg,
        format!("decks_dir = \"{}\"\n", decks.path().display()),
    )
    .unwrap();
    let cfg = cfg.to_str().unwrap();

    let garbage = "{ this is not valid json";
    std::fs::write(decks.path().join("progress.json"), garbage).unwrap();

    let out = alix(&["stats", &deck, "--config", cfg]);
    assert!(
        !out.status.success(),
        "stats must read <decks_dir>/progress.json, not fall back to the \
         global store: stdout:\n{}",
        stdout(&out)
    );
}

#[test]
fn reset_all_clears_the_decks_dir_root_store_not_the_global_one() {
    // Same discriminator as above, against `reset --all`: it must resolve to
    // `<decks_dir>/progress.json` (mirroring bare `alix`), not the global
    // platform store.
    let decks = tempfile::tempdir().unwrap();
    write(decks.path(), "math.txt", VALID_DECK);

    let cfg = decks.path().join("config.toml");
    std::fs::write(
        &cfg,
        format!("decks_dir = \"{}\"\n", decks.path().display()),
    )
    .unwrap();
    let cfg = cfg.to_str().unwrap();

    let garbage = "{ this is not valid json";
    std::fs::write(decks.path().join("progress.json"), garbage).unwrap();

    let out = alix(&["reset", "--all", "--yes", "--config", cfg]);
    assert!(
        !out.status.success(),
        "reset --all must clear <decks_dir>/progress.json, not the global \
         store: stdout:\n{}",
        stdout(&out)
    );
}

// ── `alix share` / `alix receive` ────────────────────────────────────────────

#[test]
fn share_on_a_nonexistent_path_errors() {
    let dir = TempDir::new().unwrap();
    let ghost = dir.path().join("ghost.txt");
    let out = alix(&["share", ghost.to_str().unwrap()]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("neither a deck file nor a folder"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn share_on_a_folder_with_no_decks_errors() {
    let dir = TempDir::new().unwrap();
    let empty = dir.path().join("empty");
    std::fs::create_dir(&empty).unwrap();
    let out = alix(&["share", empty.to_str().unwrap()]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("nothing to share"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn share_zip_writes_an_archive_of_a_single_deck() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "math.txt", VALID_DECK);
    let out_dir = dir.path().join("out");
    std::fs::create_dir(&out_dir).unwrap();
    let out = alix(&[
        "share",
        &deck,
        "--zip",
        "--output",
        out_dir.to_str().unwrap(),
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(out_dir.join("math.zip").is_file());
    assert!(stdout(&out).contains("Wrote"), "{}", stdout(&out));
}

#[test]
fn share_zip_of_a_workspace_folder_strips_personal_state() {
    let dir = TempDir::new().unwrap();
    let ws = dir.path().join("eng");
    std::fs::create_dir(&ws).unwrap();
    std::fs::write(ws.join("alix.toml"), "title = \"Eng\"\n").unwrap();
    write(&ws, "a.txt", "# q\n\ta\n");
    write(&ws, "progress.json", "{}"); // must never travel
    let out_dir = dir.path().join("out");
    std::fs::create_dir(&out_dir).unwrap();
    let out = alix(&[
        "share",
        ws.to_str().unwrap(),
        "--zip",
        "--output",
        out_dir.to_str().unwrap(),
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let zip_path = out_dir.join("eng.zip");
    assert!(zip_path.is_file());

    let landed = dir.path().join("landed");
    alix::share::unzip_to(&zip_path, &landed).unwrap();
    assert!(landed.join("eng/a.txt").is_file());
    assert!(!landed.join("eng/progress.json").exists());
}

#[test]
fn share_without_wormhole_installed_reports_the_install_hint() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "math.txt", VALID_DECK);
    let out = alix_env(
        &["share", &deck],
        dir.path(),
        &[("PATH", "/nonexistent-empty-bin")],
    );
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("is magic-wormhole installed?"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn receive_without_wormhole_installed_reports_the_install_hint() {
    let dir = TempDir::new().unwrap();
    let out = alix_env(
        &["receive", "7-fake-code-xyz"],
        dir.path(),
        &[("PATH", "/nonexistent-empty-bin")],
    );
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("is magic-wormhole installed?"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn receive_a_zip_deck_lands_in_the_decks_dir() {
    let home = TempDir::new().unwrap();
    let src = TempDir::new().unwrap();
    let deck = write(src.path(), "math.txt", VALID_DECK);
    let zip_path = src.path().join("math.zip");
    alix::share::zip_to(Path::new(&deck), &zip_path).unwrap();

    let out = alix_env(&["receive", zip_path.to_str().unwrap()], home.path(), &[]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(home.path().join("decks/math.txt").is_file());
    assert!(
        stdout(&out).contains("shows up in the picker"),
        "{}",
        stdout(&out)
    );
}

#[test]
fn receive_an_existing_deck_without_force_errors_then_force_overwrites() {
    let home = TempDir::new().unwrap();
    let src = TempDir::new().unwrap();
    let deck = write(src.path(), "math.txt", VALID_DECK);
    let zip_path = src.path().join("math.zip");
    alix::share::zip_to(Path::new(&deck), &zip_path).unwrap();

    let first = alix_env(&["receive", zip_path.to_str().unwrap()], home.path(), &[]);
    assert!(first.status.success(), "stderr: {}", stderr(&first));

    // The same code, received again: the deck is already there.
    let second = alix_env(&["receive", zip_path.to_str().unwrap()], home.path(), &[]);
    assert!(
        !second.status.success(),
        "should refuse to clobber without --force"
    );
    assert!(
        stderr(&second).contains("pass --force to overwrite"),
        "stderr: {}",
        stderr(&second)
    );

    let third = alix_env(
        &["receive", zip_path.to_str().unwrap(), "--force"],
        home.path(),
        &[],
    );
    assert!(third.status.success(), "stderr: {}", stderr(&third));
}

#[test]
fn receive_a_zip_folder_strips_leaked_personal_files() {
    let home = TempDir::new().unwrap();
    let src = TempDir::new().unwrap();
    let ws = src.path().join("eng");
    std::fs::create_dir(&ws).unwrap();
    write(&ws, "a.txt", "# q\n\ta\n");
    write(&ws, "progress.json", "{}"); // simulates a leak — real `share` never zips this
    let zip_path = src.path().join("eng.zip");
    alix::share::zip_to(&ws, &zip_path).unwrap();

    let out = alix_env(&["receive", zip_path.to_str().unwrap()], home.path(), &[]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("stripped a leaked personal file: progress.json"),
        "{}",
        stdout(&out)
    );
    assert!(home.path().join("decks/eng/a.txt").is_file());
    assert!(!home.path().join("decks/eng/progress.json").exists());
}

#[test]
fn receive_a_zip_folder_rejects_the_workspace_flag() {
    let home = TempDir::new().unwrap();
    let src = TempDir::new().unwrap();
    let ws = src.path().join("eng");
    std::fs::create_dir(&ws).unwrap();
    write(&ws, "a.txt", "# q\n\ta\n");
    let zip_path = src.path().join("eng.zip");
    alix::share::zip_to(&ws, &zip_path).unwrap();

    let out = alix_env(
        &[
            "receive",
            zip_path.to_str().unwrap(),
            "--workspace",
            "/tmp/nonexistent-ws-for-alix-tests",
        ],
        home.path(),
        &[],
    );
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("--workspace places a received deck"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn receive_a_zip_folder_refuses_to_clobber_an_existing_dest() {
    let home = TempDir::new().unwrap();
    let src = TempDir::new().unwrap();
    let ws = src.path().join("eng");
    std::fs::create_dir(&ws).unwrap();
    write(&ws, "a.txt", "# q\n\ta\n");
    let zip_path = src.path().join("eng.zip");
    alix::share::zip_to(&ws, &zip_path).unwrap();

    let first = alix_env(&["receive", zip_path.to_str().unwrap()], home.path(), &[]);
    assert!(first.status.success(), "stderr: {}", stderr(&first));

    let second = alix_env(&["receive", zip_path.to_str().unwrap()], home.path(), &[]);
    assert!(!second.status.success());
    assert!(
        stderr(&second).contains("already exists — move it aside first"),
        "stderr: {}",
        stderr(&second)
    );
}

// ── `alix generate`: trace stub / suggest / walk with a fake backend ────────

#[test]
fn generate_builds_checkpoints_into_an_existing_trace_stub() {
    let dir = TempDir::new().unwrap();
    let stub = write(dir.path(), "t.txt", "% trace: how it works\n% source: .\n");
    let cli = fake_claude(dir.path(), "# checkpoint one\n\tsome point\n\t% at: 1\n");
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let out = alix(&["generate", &stub, "--config", &config, "--yes"]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("Wrote 1 checkpoints"),
        "{}",
        stdout(&out)
    );
    let rewritten = std::fs::read_to_string(&stub).unwrap();
    assert!(rewritten.contains("% trace: how it works"), "{rewritten}");
    assert!(rewritten.contains("checkpoint one"), "{rewritten}");
}

#[test]
fn generate_trace_plan_prints_the_suggestion_menu() {
    let dir = TempDir::new().unwrap();
    write(dir.path(), "notes.md", "some source material\n");
    let cli = fake_claude(dir.path(), "1. [trace] how X becomes Y\n   % source: .\n");
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let out = alix(&[
        "generate",
        dir.path().to_str().unwrap(),
        "--trace",
        "--plan",
        "--config",
        &config,
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(stdout(&out).contains("how X becomes Y"), "{}", stdout(&out));
    assert!(
        stdout(&out).contains("Paste a suggestion into a new deck"),
        "{}",
        stdout(&out)
    );
}

#[test]
fn generate_trace_walk_writes_an_explore_deck() {
    let dir = TempDir::new().unwrap();
    write(dir.path(), "notes.md", "some source material\n");
    let cli = fake_claude(dir.path(), "# what it is\n\tsome point\n\t% at: 1\n");
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let out_path = dir.path().join("walk.txt");
    let out = alix(&[
        "generate",
        dir.path().to_str().unwrap(),
        "--trace",
        "--config",
        &config,
        "--output",
        out_path.to_str().unwrap(),
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let text = std::fs::read_to_string(&out_path).unwrap();
    assert!(text.contains("% trace: exploring"), "{text}");
    assert!(text.contains("% source:"), "{text}");
    assert!(text.contains("what it is"), "{text}");
}

#[test]
fn generate_trace_walk_refuses_to_clobber_an_existing_output() {
    let dir = TempDir::new().unwrap();
    write(dir.path(), "notes.md", "some source material\n");
    let cli = fake_claude(dir.path(), "# what it is\n\tsome point\n\t% at: 1\n");
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let out_path = dir.path().join("walk.txt");
    write(dir.path(), "walk.txt", "already here\n");
    let out = alix(&[
        "generate",
        dir.path().to_str().unwrap(),
        "--trace",
        "--config",
        &config,
        "--output",
        out_path.to_str().unwrap(),
    ]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("already exists; pass --force to overwrite"),
        "stderr: {}",
        stderr(&out)
    );
}

// ── `alix generate`: a single deck from a URL/file source, fake backend ─────

#[test]
fn generate_single_deck_writes_a_deck_file() {
    let dir = TempDir::new().unwrap();
    let cli = fake_claude(dir.path(), "# Generated Q\n\tGenerated A\n");
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let ws = dir.path().join("ws");
    std::fs::create_dir(&ws).unwrap();
    let out = alix(&[
        "generate",
        "https://example.org/page",
        "--config",
        &config,
        "--workspace",
        ws.to_str().unwrap(),
        "--output",
        "gen",
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("Wrote 1 cards to"),
        "{}",
        stdout(&out)
    );
    assert!(ws.join("gen.txt").is_file());
}

#[test]
fn generate_single_deck_print_flag_prints_without_writing() {
    let dir = TempDir::new().unwrap();
    let cli = fake_claude(dir.path(), "# Generated Q\n\tGenerated A\n");
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let out = alix(&[
        "generate",
        "https://example.org/page",
        "--config",
        &config,
        "--print",
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(stdout(&out).contains("Generated Q"), "{}", stdout(&out));
    assert!(
        stderr(&out).contains("cards — not written; --print"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn generate_single_deck_refuses_to_clobber_without_force_then_force_overwrites() {
    let dir = TempDir::new().unwrap();
    let cli = fake_claude(dir.path(), "# Generated Q\n\tGenerated A\n");
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let ws = dir.path().join("ws");
    std::fs::create_dir(&ws).unwrap();
    let args = [
        "generate",
        "https://example.org/page",
        "--config",
        &config,
        "--workspace",
        ws.to_str().unwrap(),
        "--output",
        "gen",
    ];
    let first = alix(&args);
    assert!(first.status.success(), "stderr: {}", stderr(&first));

    let second = alix(&args);
    assert!(!second.status.success());
    assert!(
        stderr(&second).contains("already exists; pass --force to overwrite"),
        "stderr: {}",
        stderr(&second)
    );

    let mut forced = args.to_vec();
    forced.push("--force");
    let third = alix(&forced);
    assert!(third.status.success(), "stderr: {}", stderr(&third));
}

#[test]
fn generate_on_a_directory_source_explores_then_falls_back_to_a_single_deck() {
    // A one-item (unparseable-as-a-plan) exploration result routes to a single
    // deck rather than a multi-item workspace build.
    let dir = TempDir::new().unwrap();
    let src = dir.path().join("src");
    std::fs::create_dir(&src).unwrap();
    write(&src, "notes.md", "some source material\n");
    let cli = fake_claude(dir.path(), "# Generated Q\n\tGenerated A\n");
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let ws = dir.path().join("ws");
    std::fs::create_dir(&ws).unwrap();
    let out = alix(&[
        "generate",
        src.to_str().unwrap(),
        "--config",
        &config,
        "--workspace",
        ws.to_str().unwrap(),
        "--output",
        "gen",
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stderr(&out).contains("Exploring"),
        "stderr: {}",
        stderr(&out)
    );
    assert!(ws.join("gen.txt").is_file());
}

// ── `alix deck augment`: each target, fake backend ──────────────────────────

#[test]
fn augment_choices_caches_distractors_for_two_cards() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "quiz.txt", "# Q1\n\tA1\n\n# Q2\n\tA2\n");
    let cli = fake_claude(dir.path(), r#"{"0": ["W1", "W2"], "1": ["W3", "W4"]}"#);
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let store = dir.path().join("p.json");
    let out = alix(&[
        "deck",
        "augment",
        &deck,
        "--target",
        "choices",
        "--store",
        store.to_str().unwrap(),
        "--config",
        &config,
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("augmented 2 of 2 cards"),
        "{}",
        stdout(&out)
    );
    let cached = std::fs::read_to_string(dir.path().join("augment.json")).unwrap();
    assert!(cached.contains("W1"), "{cached}");
    assert!(cached.contains("W3"), "{cached}");
}

#[test]
fn augment_notes_caches_a_trivia_note() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "quiz.txt", "# Q1\n\tA1\n");
    let cli = fake_claude(dir.path(), r#"{"0": "a fun fact"}"#);
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let store = dir.path().join("p.json");
    let out = alix(&[
        "deck",
        "augment",
        &deck,
        "--target",
        "notes",
        "--store",
        store.to_str().unwrap(),
        "--config",
        &config,
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let cached = std::fs::read_to_string(dir.path().join("augment.json")).unwrap();
    assert!(cached.contains("a fun fact"), "{cached}");
}

#[test]
fn augment_without_a_store_flag_caches_beside_the_decks_dir_root_store() {
    // Mirrors `stats_on_a_loose_deck_resolves_the_decks_dir_root_store_like_review_does`:
    // with no `--store`, the cache must land at `<decks_dir>/augment.json` —
    // beside the `<decks_dir>/progress.json` review reads — not the global
    // platform store's sidecar (the pre-fix bug: `common::store_for` had no
    // decks-dir fallback, so a loose deck's augmentations went missing at
    // review time).
    let decks = tempfile::tempdir().unwrap();
    let deck = write(decks.path(), "quiz.txt", "# Q1\n\tA1\n");
    let cli = fake_claude(decks.path(), r#"{"0": "a fun fact"}"#);

    let cfg = decks.path().join("config.toml");
    std::fs::write(
        &cfg,
        format!(
            "decks_dir = \"{}\"\n[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n",
            decks.path().display()
        ),
    )
    .unwrap();
    let cfg = cfg.to_str().unwrap();

    let out = alix(&[
        "deck", "augment", &deck, "--target", "notes", "--config", cfg,
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));

    let cached = std::fs::read_to_string(decks.path().join("augment.json")).unwrap();
    assert!(cached.contains("a fun fact"), "{cached}");
}

#[test]
fn augment_questions_caches_a_reworded_variant() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "quiz.txt", "# Q1\n\tA1\n");
    let cli = fake_claude(dir.path(), r#"{"0": ["Rephrased Q1?"]}"#);
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let store = dir.path().join("p.json");
    let out = alix(&[
        "deck",
        "augment",
        &deck,
        "--target",
        "questions",
        "--store",
        store.to_str().unwrap(),
        "--config",
        &config,
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let cached = std::fs::read_to_string(dir.path().join("augment.json")).unwrap();
    assert!(cached.contains("Rephrased Q1?"), "{cached}");
}

#[test]
fn augment_questions_on_a_cloze_only_deck_errors() {
    let dir = TempDir::new().unwrap();
    let deck = write(
        dir.path(),
        "c.txt",
        "# Complete\n% reveal: cloze\n\tThe capital of France is {{Paris}}.\n",
    );
    let config = write(
        dir.path(),
        "config.toml",
        "[ask]\ncommand = \"/nonexistent/x\"\n",
    );
    let store = dir.path().join("p.json");
    let out = alix(&[
        "deck",
        "augment",
        &deck,
        "--target",
        "questions",
        "--store",
        store.to_str().unwrap(),
        "--config",
        &config,
    ]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("no plain (non-cloze) cards to add question variants to"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn augment_keypoints_caches_decomposed_claims() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "quiz.txt", "# Q1\n\tA1\n");
    let cli = fake_claude(dir.path(), r#"{"0": ["point one", "point two"]}"#);
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let store = dir.path().join("p.json");
    let out = alix(&[
        "deck",
        "augment",
        &deck,
        "--target",
        "keypoints",
        "--store",
        store.to_str().unwrap(),
        "--config",
        &config,
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let cached = std::fs::read_to_string(dir.path().join("augment.json")).unwrap();
    assert!(cached.contains("point one"), "{cached}");
    assert!(cached.contains("point two"), "{cached}");
}

#[test]
fn augment_topology_prints_and_caches_the_walk() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "quiz.txt", "# Q1\n\tA1\n\n# Q2\n\tA2\n");
    let cli = fake_claude(
        dir.path(),
        r#"{"principle": "by difficulty", "edges": [{"from": 0, "to": 1, "label": "builds on"}], "walk": [0, 1], "regions": []}"#,
    );
    let config = write(
        dir.path(),
        "config.toml",
        &format!("[ask]\ncommand = \"{cli}\"\ntimeout_secs = 10\n"),
    );
    let store = dir.path().join("p.json");
    let out = alix(&[
        "deck",
        "augment",
        &deck,
        "--target",
        "topology",
        "--store",
        store.to_str().unwrap(),
        "--config",
        &config,
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    let text = stdout(&out);
    assert!(text.contains("topology 'pedagogical order'"), "{text}");
    assert!(text.contains("by difficulty"), "{text}");
    assert!(text.contains("(1 topology stored for this deck)"), "{text}");
}

#[test]
fn augment_on_an_empty_deck_errors_without_calling_the_backend() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "empty.txt", "% title: Nothing\n");
    let config = write(
        dir.path(),
        "config.toml",
        "[ask]\ncommand = \"/nonexistent/x\"\n",
    );
    let store = dir.path().join("p.json");
    let out = alix(&[
        "deck",
        "augment",
        &deck,
        "--target",
        "choices",
        "--store",
        store.to_str().unwrap(),
        "--config",
        &config,
    ]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("the deck has no cards to augment"),
        "stderr: {}",
        stderr(&out)
    );
}

// ── `alix deck import` ───────────────────────────────────────────────────────

#[test]
fn deck_import_writes_a_deck_from_tsv() {
    let dir = TempDir::new().unwrap();
    let tsv = write(
        dir.path(),
        "cards.tsv",
        "Capital of Japan?\tTokyo\nCapital of Italy?\tRome\n",
    );
    let out = alix(&["deck", "import", &tsv, "--output", "geo"]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("Imported 2 cards into"),
        "{}",
        stdout(&out)
    );
}

#[test]
fn deck_import_print_flag_prints_without_writing() {
    let dir = TempDir::new().unwrap();
    let tsv = write(dir.path(), "cards.tsv", "Q1\tA1\n");
    let out = alix(&["deck", "import", &tsv, "--print"]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(stdout(&out).contains("# Q1"), "{}", stdout(&out));
    assert!(
        stderr(&out).contains("cards — not written; --print"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn deck_import_into_a_workspace_lands_there() {
    let dir = TempDir::new().unwrap();
    let tsv = write(dir.path(), "cards.tsv", "Q1\tA1\n");
    let ws = dir.path().join("ws");
    std::fs::create_dir(&ws).unwrap();
    let out = alix(&[
        "deck",
        "import",
        &tsv,
        "--workspace",
        ws.to_str().unwrap(),
        "--output",
        "geo",
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(ws.join("geo.txt").is_file());
}

#[test]
fn deck_import_refuses_to_clobber_without_force_then_force_overwrites() {
    let dir = TempDir::new().unwrap();
    let tsv = write(dir.path(), "cards.tsv", "Q1\tA1\n");
    let ws = dir.path().join("ws");
    std::fs::create_dir(&ws).unwrap();
    let args = [
        "deck",
        "import",
        &tsv,
        "--workspace",
        ws.to_str().unwrap(),
        "--output",
        "geo",
    ];
    let first = alix(&args);
    assert!(first.status.success(), "stderr: {}", stderr(&first));

    let second = alix(&args);
    assert!(!second.status.success());
    assert!(
        stderr(&second).contains("already exists; pass --force to overwrite"),
        "stderr: {}",
        stderr(&second)
    );

    let mut forced = args.to_vec();
    forced.push("--force");
    let third = alix(&forced);
    assert!(third.status.success(), "stderr: {}", stderr(&third));
}

// ── `alix workspace init` ────────────────────────────────────────────────────

#[test]
fn workspace_init_on_an_existing_workspace_errors() {
    let dir = TempDir::new().unwrap();
    let ws = dir.path().join("fresh");
    let first = alix(&["workspace", "init", ws.to_str().unwrap()]);
    assert!(first.status.success(), "stderr: {}", stderr(&first));
    // `is_workspace` requires a manifest AND at least one deck — a bare `init`
    // alone isn't "already a workspace" yet.
    write(&ws, "a.txt", "# q\n\ta\n");
    let second = alix(&["workspace", "init", ws.to_str().unwrap()]);
    assert!(!second.status.success());
    assert!(
        stderr(&second).contains("is already a workspace"),
        "stderr: {}",
        stderr(&second)
    );
}

// ── `alix reset`: remaining branches ─────────────────────────────────────────

#[test]
fn reset_without_target_or_flags_errors() {
    let out = alix(&["reset"]);
    assert!(!out.status.success());
    assert!(
        stderr(&out).contains("name a deck, folder, or workspace to reset"),
        "stderr: {}",
        stderr(&out)
    );
}

#[test]
fn reset_all_on_an_empty_store_reports_nothing_to_reset() {
    let dir = TempDir::new().unwrap();
    let store = dir.path().join("progress.json"); // never created
    let out = alix(&[
        "reset",
        "--all",
        "--yes",
        "--store",
        store.to_str().unwrap(),
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("No stored progress to reset."),
        "{}",
        stdout(&out)
    );
}

#[test]
fn reset_by_numeric_card_id_without_a_target() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "math.txt", VALID_DECK);
    let store_path = dir.path().join("progress.json");
    let card_id = alix::deck::Deck::load(&deck).unwrap().cards[0].id();
    let mut store = alix::store::Store::open(&store_path).unwrap();
    store.get_or_insert(card_id, 0);
    store.save().unwrap();

    let out = alix(&[
        "reset",
        "--card",
        &card_id.to_string(),
        "--yes",
        "--store",
        store_path.to_str().unwrap(),
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("Reset 1 card(s)."),
        "{}",
        stdout(&out)
    );
}

#[test]
fn reset_by_text_query_within_a_target_resets_only_matching_cards() {
    let dir = TempDir::new().unwrap();
    let deck_text = "# Capital of Japan?\n\tTokyo\n\n# Largest planet?\n\tJupiter\n";
    let deck = write(dir.path(), "geo.txt", deck_text);
    let cards = alix::parser::parse_str("geo.txt", deck_text).unwrap();
    let store_path = dir.path().join("progress.json");
    let mut store = alix::store::Store::open(&store_path).unwrap();
    for c in &cards {
        store.get_or_insert(c.id(), 0);
    }
    store.save().unwrap();

    let out = alix(&[
        "reset",
        &deck,
        "--card",
        "japan",
        "--yes",
        "--store",
        store_path.to_str().unwrap(),
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("Reset 1 card(s)."),
        "{}",
        stdout(&out)
    );

    let reloaded = alix::store::Store::open(&store_path).unwrap();
    assert!(
        reloaded.get(cards[0].id()).is_none(),
        "the matched card should be cleared"
    );
    assert!(
        reloaded.get(cards[1].id()).is_some(),
        "the other card should survive"
    );
}

#[test]
fn reset_by_text_query_with_no_match_reports_nothing() {
    let dir = TempDir::new().unwrap();
    let deck = write(dir.path(), "geo.txt", "# Capital of Japan?\n\tTokyo\n");
    let store_path = dir.path().join("progress.json");
    let out = alix(&[
        "reset",
        &deck,
        "--card",
        "nonexistent-query",
        "--yes",
        "--store",
        store_path.to_str().unwrap(),
    ]);
    assert!(out.status.success(), "stderr: {}", stderr(&out));
    assert!(
        stdout(&out).contains("No stored progress matching"),
        "{}",
        stdout(&out)
    );
}