mossaic 0.7.0

Draw pixel art in your GitHub contribution graph โ€” a terminal chart, an editor, and a planner that says what today owes
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
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
//! The `mossaic-art` binary, run as a user runs it.
//!
//! No PTY here: `mossaic-art` prints and exits, so this drives it the way a shell does
//! and asserts on what comes back. Everything is offline โ€” `--merge` reads a
//! saved calendar, so nothing needs `gh`.

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

fn art(args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .current_dir(env!("CARGO_MANIFEST_DIR"))
        .args(args)
        .output()
        .expect("the art binary runs")
}

/// A scratch path in the temp directory that no other process will touch.
///
/// The names here used to be constants, which made them shared state: a stress
/// loop beside an ordinary `cargo test`, or two people on one machine, raced
/// over the same file and failed in ways that looked like the code rather than
/// like the harness. CONTRIBUTING.md ยง3 asks for hermetic tests, and a fixed
/// global path is not one.
fn scratch(name: &str) -> std::path::PathBuf {
    std::env::temp_dir().join(format!("mossaic-{}-{name}", std::process::id()))
}

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

#[test]
fn the_font_can_be_looked_at() {
    let out = art(&["--font", "--no-colour"]);
    assert!(out.status.success());
    let text = stdout(&out);
    // A lower bound, like the unit test's: adding a glyph is the point of the
    // font, and a test that counted them would fail on the one contribution it
    // exists to protect.
    let count: usize = text
        .split_whitespace()
        .next()
        .and_then(|word| word.parse().ok())
        .unwrap_or_else(|| panic!("no glyph count in {text}"));
    assert!(count >= 39, "{count} glyphs: {text}");
    assert!(text.contains("glyphs, 5x5 each"), "{text}");
    assert!(
        text.contains("write any of them with mossaic-art TEXT"),
        "{text}"
    );
    // Every character it claims, drawn.
    for character in ['A', 'Z', '0', '9', '-', '.'] {
        assert!(
            text.contains(character),
            "the font view is missing {character}"
        );
    }
    assert!(
        text.contains("space"),
        "including the one with no glyph: {text}"
    );
}

/// A shape, typed the way anyone without a symbol keyboard has to type it.
#[test]
fn a_shape_can_be_written_between_colons() {
    let out = art(&["I :HEART: RUST", "--year", "2027", "--no-colour"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    // The header echoes the character, not the name it was typed as: the plan
    // is stored that way, and the tracker reads it back.
    assert!(text.contains("I \u{2665} RUST"), "{text}");
    // Eight glyphs at six columns apiece, less the gap after the last.
    assert!(text.contains("47 of 53 columns"), "{text}");

    // Upper and lower case name the same shape, because a plan is stored
    // uppercased and has to survive the round trip.
    let lower = art(&["I :heart: RUST", "--year", "2027", "--no-colour"]);
    assert_eq!(stdout(&lower), text, "case should not change the drawing");
}

/// The symbol itself, and the emoji someone is far more likely to paste.
#[test]
fn a_pasted_symbol_draws_the_same_shape_as_its_name() {
    let by_name = art(&[":star::heart:", "--year", "2027", "--no-colour"]);
    let by_symbol = art(&["\u{2605}\u{2665}", "--year", "2027", "--no-colour"]);
    let by_emoji = art(&["\u{2b50}\u{2764}\u{fe0f}", "--year", "2027", "--no-colour"]);

    assert!(
        by_name.status.success(),
        "{}",
        String::from_utf8_lossy(&by_name.stderr)
    );
    assert_eq!(stdout(&by_symbol), stdout(&by_name), "symbol vs name");
    assert_eq!(
        stdout(&by_emoji),
        stdout(&by_name),
        "a pasted emoji, variation selector and all, vs name"
    );
}

/// Both ways of getting the grammar wrong, and what each says.
#[test]
fn a_misspelt_shape_says_which_shapes_there_are() {
    let unknown = art(&[":wombat:", "--year", "2027"]);
    assert!(
        !unknown.status.success(),
        "it should refuse rather than guess"
    );
    let error = String::from_utf8_lossy(&unknown.stderr).into_owned();
    assert!(error.contains("wombat"), "{error}");
    assert!(
        error.contains(":star:") && error.contains(":heart:"),
        "{error}"
    );

    // A colon that opens nothing. The message is about the grammar rather
    // than about a missing glyph for ':', which would be true and useless.
    let unclosed = art(&["12:30", "--year", "2027"]);
    assert!(!unclosed.status.success());
    let error = String::from_utf8_lossy(&unclosed.stderr).into_owned();
    assert!(error.contains("unclosed"), "{error}");
    assert!(error.contains(":name:"), "{error}");
}

/// The font view names its shapes rather than printing them. Several of these
/// symbols are ambiguous-width, so a terminal may draw one in two columns and
/// tear the aligned output apart โ€” the same reason the README lists names.
#[test]
fn the_font_view_names_its_shapes() {
    let out = art(&["--font", "--no-colour"]);
    assert!(out.status.success());
    let text = stdout(&out);
    for named in [
        ":star:", ":heart:", ":smile:", ":sad:", ":moon:", ":flower:",
    ] {
        assert!(text.contains(named), "the font view is missing {named}");
    }
    // The label is the name, so the raw symbol never reaches the column
    // headings it would misalign.
    assert!(
        !text.contains('\u{2605}'),
        "a bare symbol in the headings: {text}"
    );
}

/// A shape has to survive being written to a plan and read back, which is the
/// path every tracked year takes each morning.
#[test]
fn a_shape_round_trips_through_a_saved_plan() {
    let dir = scratch("shape-plan");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();

    let run = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
            .current_dir(&dir)
            .args(args)
            .output()
            .expect("the art binary runs")
    };

    let saved = run(&[":heart::star:", "--year", "2027", "--save", "--no-colour"]);
    assert!(
        saved.status.success(),
        "{}",
        String::from_utf8_lossy(&saved.stderr)
    );

    // Stored as characters, so nothing downstream has to know the grammar.
    let plan =
        std::fs::read_to_string(dir.join(mossaic::plan::DEFAULT_SPEC)).expect("a plan on disk");
    assert!(
        plan.contains('\u{2665}') && plan.contains('\u{2605}'),
        "{plan}"
    );
    assert!(
        !plan.contains(":heart:"),
        "the name should not survive: {plan}"
    );

    // And read back by the tracker, which is the run that happens every day.
    // Against a saved calendar rather than the network: without `--merge` this
    // asks `gh` whose graph to read, which is not a question a test may ask.
    // The path is absolute because the run happens in the scratch directory.
    let calendar = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("art/vyncint-2027.json")
        .to_string_lossy()
        .into_owned();
    let tracked = run(&[
        "--track",
        "--merge",
        &calendar,
        "--no-colour",
        "--today",
        "2027-06-01",
    ]);
    assert!(
        tracked.status.success(),
        "{}",
        String::from_utf8_lossy(&tracked.stderr)
    );
    assert!(
        stdout(&tracked).contains('\u{2665}'),
        "{}",
        stdout(&tracked)
    );

    let _ = std::fs::remove_dir_all(&dir);
}

/// The README promises a set; the font has to be that set.
///
/// A table of glyphs is exactly the documentation that rots โ€” a shape gets
/// added and the list quietly stops being true, and the list is the only place
/// most people will look. So the list is checked rather than maintained.
#[test]
fn the_readme_lists_every_glyph_the_font_has() {
    let readme = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("README.md"))
        .expect("a README");
    let section = readme
        .split("## What you can draw")
        .nth(1)
        .expect("a section listing the font")
        .split("\n## ")
        .next()
        .expect("the section ends");

    for (name, _) in mossaic::art::shapes() {
        assert!(
            section.contains(&format!(":{name}:")),
            "the README does not list :{name}:"
        );
    }
    for character in mossaic::art::alphabet() {
        if character.is_whitespace() || mossaic::art::shape_name(character).is_some() {
            continue;
        }
        assert!(
            section.contains(character),
            "the README does not list {character:?}"
        );
    }

    // And nothing it lists is missing from the font: every `:name:` in the
    // section has to draw something.
    for token in section.split_whitespace() {
        let Some(name) = token
            .trim_matches('`')
            .strip_prefix(':')
            .and_then(|rest| rest.strip_suffix(':'))
        else {
            continue;
        };
        assert!(
            mossaic::art::shape(name).is_some(),
            "the README promises :{name}:, which the font does not have"
        );
    }

    // The table's own claim, row by row: every symbol and every emoji on a row
    // draws the shape that row names. This is the half most likely to rot โ€”
    // a fold gets removed and the table still advertises the emoji.
    let mut rows = 0;
    for line in section.lines().filter(|line| line.starts_with('|')) {
        let cells: Vec<&str> = line.split('|').map(str::trim).collect();
        let [_, symbols, names, pastes, ..] = cells.as_slice() else {
            continue;
        };
        let Some(first) = names.split_whitespace().next() else {
            continue;
        };
        let Some(name) = first
            .trim_matches('`')
            .strip_prefix(':')
            .and_then(|rest| rest.strip_suffix(':'))
        else {
            continue;
        };
        let wanted = mossaic::art::bitmap(&format!(":{name}:")).expect("a shape");
        rows += 1;

        // The arrows share a row, so a row may name several shapes and show
        // several symbols; each symbol is checked against its own name.
        let named: Vec<&str> = names
            .split_whitespace()
            .filter_map(|token| {
                token
                    .trim_matches('`')
                    .strip_prefix(':')
                    .and_then(|rest| rest.strip_suffix(':'))
            })
            .collect();
        for symbol in symbols.chars().filter(|c| !c.is_whitespace()) {
            let drawn = mossaic::art::bitmap(&symbol.to_string())
                .unwrap_or_else(|error| panic!("the README shows {symbol:?}: {error}"));
            assert!(
                named
                    .iter()
                    .any(|name| drawn == mossaic::art::bitmap(&format!(":{name}:")).unwrap()),
                "the README shows {symbol:?} beside {named:?}, which it does not draw"
            );
        }

        for pasted in pastes
            .chars()
            // A variation selector says how to draw the character before it,
            // not which character it is, and the README carries whatever an
            // emoji keyboard produced.
            .filter(|c| {
                !c.is_whitespace() && !c.is_ascii() && !matches!(c, '\u{fe0f}' | '\u{fe0e}')
            })
        {
            let drawn = mossaic::art::bitmap(&pasted.to_string())
                .unwrap_or_else(|error| panic!("the README offers {pasted:?}: {error}"));
            assert_eq!(
                drawn, wanted,
                "the README offers {pasted:?} for :{name}:, which is not what it draws"
            );
        }
    }
    assert!(
        rows >= 16,
        "only {rows} rows of the shape table were checked"
    );
}

/// A shape has to survive the last mile as well: into a commit message, and
/// back out of git. The message is the one place the text leaves the program
/// entirely, and a character that draws perfectly can still be mangled there.
#[test]
fn a_shape_reaches_the_commits_it_writes() {
    let dir = scratch("shape-write");
    let _ = std::fs::remove_dir_all(&dir);
    let repo = dir.to_string_lossy().into_owned();

    let out = art(&[
        ":heart:",
        "--year",
        "2027",
        "--commits",
        "1",
        "--repo",
        &repo,
        "--write",
        "--name",
        "Tester",
        "--email",
        "tester@example.invalid",
        "--no-colour",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        stdout(&out).contains("nothing has been pushed"),
        "{}",
        stdout(&out)
    );

    let log = Command::new("git")
        .current_dir(&dir)
        .args(["log", "--format=%s"])
        .output()
        .expect("git log runs");
    let subjects = String::from_utf8_lossy(&log.stdout).into_owned();
    assert!(!subjects.trim().is_empty(), "it wrote commits");
    assert!(
        subjects.contains("art: \u{2665}"),
        "the shape did not reach the commit message: {subjects}"
    );
    // The name is not what is stored, so it cannot be what comes back out.
    assert!(!subjects.contains(":heart:"), "{subjects}");

    let _ = std::fs::remove_dir_all(&dir);
}

/// The Action reads `--format json`, so a shape has to come out of it as valid
/// JSON rather than as whatever the character did to the encoder.
#[test]
fn a_shape_survives_the_json_the_action_reads() {
    let out = art(&[
        ":heart:",
        "--year",
        "2027",
        "--track",
        "--merge",
        "art/vyncint-2027.json",
        "--today",
        "2027-06-01",
        "--format",
        "json",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    // Parsed rather than matched, which is the only way to say "valid JSON".
    let parsed: serde_json::Value = serde_json::from_str(&text).expect("valid JSON");
    assert_eq!(parsed["text"], "\u{2665}", "{text}");
}

/// The font sheet in the README has to be the font the crate ships.
///
/// An image of the alphabet is documentation that cannot be spot-checked by
/// reading it: a glyph gets added, the picture keeps showing the old set, and
/// nothing says so. So the picture is regenerated here and compared with the
/// committed one, byte for byte โ€” the same input through the same encoder is
/// the same file.
#[test]
fn the_font_sheet_in_the_readme_is_the_font() {
    let committed = Path::new(env!("CARGO_MANIFEST_DIR")).join("art/font.png");
    let fresh = scratch("font-sheet.png");
    let _ = std::fs::remove_file(&fresh);

    let out = art(&["--font", "--png", &fresh.to_string_lossy()]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(stdout(&out).contains("76 glyphs"), "{}", stdout(&out));

    let drawn = std::fs::read(&fresh).expect("the sheet it just wrote");
    let shipped = std::fs::read(&committed).expect("art/font.png");
    assert_eq!(
        drawn.len(),
        shipped.len(),
        "art/font.png is {} bytes and the font now draws {} โ€” regenerate it:\n  \
         cargo run --bin mossaic-art -- --font --png art/font.png",
        shipped.len(),
        drawn.len()
    );
    assert!(
        drawn == shipped,
        "art/font.png is not what the font draws โ€” regenerate it:\n  \
         cargo run --bin mossaic-art -- --font --png art/font.png"
    );

    // It is a PNG, and the README points at it.
    assert_eq!(&shipped[..8], b"\x89PNG\r\n\x1a\n");
    let readme = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("README.md"))
        .expect("a README");
    assert!(
        readme.contains("](art/font.png)"),
        "the README shows the sheet"
    );

    let _ = std::fs::remove_file(&fresh);
}

#[test]
fn an_unknown_character_says_what_there_is() {
    let out = art(&["HI~THERE", "--year", "2027"]);
    assert!(!out.status.success(), "it should refuse rather than guess");
    let error = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(error.contains('~'), "{error}");
    assert!(error.contains("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), "{error}");
}

#[test]
fn tracking_a_finished_year_says_so() {
    // art/vyncint-2027.json is VYNCINT drawn on an otherwise empty year, at the
    // placement centring gives โ€” so tracking it back is a completed plan.
    //
    // `--today` is pinned because the last assertion is about a year that has
    // not started, which the clock would make true only until it did. Every
    // test that reads a report pins it, for the same reason.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--track",
        "--merge",
        "art/vyncint-2027.json",
        "--today",
        "2026-08-19",
        "--no-colour",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(text.contains("VYNCINT is drawn."), "{text}");
    assert!(text.contains("75 of 75 bright"), "{text}");
    assert!(!text.contains("cannot be drawn"), "{text}");
    // A year still ahead has no advice for this afternoon.
    assert!(text.contains("2027 has not started"), "{text}");
}

#[test]
fn tracking_a_busy_year_says_why_it_cannot_be_drawn() {
    // The same text over a year that already has contributions of its own: the
    // letters can be brightened, but the days inside them that are already lit
    // are permanent.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--no-colour",
        "--today",
        "2026-08-19",
        "--start-week",
        "1",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(
        text.contains("VYNCINT cannot be drawn cleanly in 2026."),
        "{text}"
    );
    assert!(
        text.contains("inside the letters already have contributions"),
        "and it should say why:\n{text}"
    );
    assert!(
        text.contains("a letter day has to reach"),
        "and what a day costs:\n{text}"
    );
    // The verdict is a fact about the data, not a mood: the same run twice says
    // the same thing.
    assert_eq!(
        text,
        stdout(&art(&[
            "VYNCINT",
            "--year",
            "2026",
            "--track",
            "--merge",
            "art/vyncint-2026.json",
            "--no-colour",
            "--today",
            "2026-08-19",
            "--start-week",
            "1",
        ]))
    );
}

#[test]
fn tracking_without_a_calendar_explains_itself() {
    // No --merge and no `gh` reachable: it has to say what it needed, not fail
    // with whatever the process error happened to be.
    let out = Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .current_dir(env!("CARGO_MANIFEST_DIR"))
        .env("PATH", "/nonexistent")
        .args(["VYNCINT", "--year", "2026", "--track"])
        .output()
        .expect("the art binary runs");
    assert!(!out.status.success());
    let error = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(
        error.contains("--track USER") || error.contains("gh auth login"),
        "{error}"
    );
}

#[test]
fn a_snapshot_round_trips_through_the_chart() {
    let out = scratch("art-cli.json");
    let path = out.to_string_lossy().into_owned();
    let made = art(&["HI", "--year", "2027", "--snapshot", &path, "--no-colour"]);
    assert!(
        made.status.success(),
        "{}",
        String::from_utf8_lossy(&made.stderr)
    );
    assert!(
        stdout(&made).contains("mossaic --file"),
        "it says what to do next"
    );
    assert!(Path::new(&path).exists());

    // And the chart renders it without a terminal.
    let png = scratch("art-cli.png");
    let drawn = Command::new(env!("CARGO_BIN_EXE_mossaic"))
        .args(["--file", &path, "--png", &png.to_string_lossy()])
        .output()
        .expect("the chart runs");
    assert!(
        drawn.status.success(),
        "{}",
        String::from_utf8_lossy(&drawn.stderr)
    );
    assert!(png.exists());
    let _ = std::fs::remove_file(&out);
    let _ = std::fs::remove_file(&png);
}

#[test]
fn the_help_lists_every_flag_the_parser_takes() {
    // Derived from the parser rather than from a list kept alongside it: adding
    // a flag and forgetting the help is exactly the mistake this catches, and a
    // hand-written list would have to be remembered too.
    let source = include_str!("../src/bin/mossaic-art.rs");
    // Every quoted token in a match arm, not just the first: an arm like
    // `"-h" | "--help" =>` documents two flags, and only checking one of them
    // is how `--help` itself went unverified.
    let arms: Vec<&str> = source
        .lines()
        .map(str::trim)
        .filter(|line| line.starts_with('"') && line.contains("=>"))
        .flat_map(|line| line.split('"').skip(1).step_by(2))
        .filter(|token| token.starts_with('-'))
        .collect();
    assert!(
        arms.len() > 15,
        "only found {} flags โ€” did the parser move?",
        arms.len()
    );

    let help = stdout(&art(&["--help"]));
    for flag in arms {
        assert!(help.contains(flag), "--help never mentions {flag}");
    }
    assert!(
        help.contains("examples:"),
        "and it should show how, not just what"
    );
    // The thing that removes the trap: a saved plan.
    assert!(help.contains("--save"), "{help}");
    assert!(help.contains("mossaic-art --track"), "{help}");
}

#[test]
fn the_report_is_machine_readable() {
    let out = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--start-week",
        "1",
        "--today",
        "2026-08-19",
        "--format",
        "json",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let json: serde_json::Value =
        serde_json::from_str(&stdout(&out)).expect("--format json emits json");

    // The fields the GitHub Action reads. A rename here breaks every workflow
    // in the wild, so they are pinned by name.
    for field in [
        "text",
        "year",
        "source",
        "start_week",
        "columns",
        "year_total",
        "peak",
        "need_per_day",
        "letters",
        "bright",
        "owing_days",
        "owing_commits",
        "holes",
        "around",
        "verdict",
        "headline",
        "ahead_days",
        "overdue_days",
    ] {
        assert!(!json[field].is_null(), "the report lost `{field}`");
    }
    assert_eq!(json["text"], "VYNCINT");
    assert_eq!(json["year"], 2026);
    assert_eq!(json["verdict"], "holed");
    assert_eq!(json["letters"], 75);
    assert!(json["holes"].as_u64().unwrap() > 0);
    // The headline is carried, not reconstructed downstream.
    let headline = json["headline"].as_str().unwrap();
    assert!(headline.contains("VYNCINT"), "{headline}");
    assert!(headline.contains("hole"), "{headline}");

    // Markdown says the same things, in a shape a message can carry.
    let md = stdout(&art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--start-week",
        "1",
        "--today",
        "2026-08-19",
        "--format",
        "markdown",
    ]));
    assert!(md.starts_with("### VYNCINT ยท 2026"), "{md}");
    assert!(md.contains("Cannot be drawn cleanly"), "{md}");
    assert!(md.contains("| letters bright | 75 of 75 |"), "{md}");
    assert!(
        !md.contains('\x1b'),
        "a message body carries no escape codes:\n{md}"
    );
}

#[test]
fn an_unknown_format_is_refused() {
    let out = art(&["VYNCINT", "--year", "2027", "--track", "--format", "yaml"]);
    assert!(!out.status.success());
    let error = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(error.contains("text, json or markdown"), "{error}");
}

#[test]
fn a_saved_plan_makes_the_flags_optional() {
    let dir = scratch("plan-test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();

    let run = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
            .current_dir(&dir)
            .args(args)
            .output()
            .expect("the art binary runs")
    };

    // With no plan and no text, it says what to do rather than what went wrong.
    let lost = run(&["--track"]);
    assert!(!lost.status.success());
    let hint = String::from_utf8_lossy(&lost.stderr).into_owned();
    assert!(hint.contains("--save"), "{hint}");
    assert!(hint.contains("no plan at"), "{hint}");

    // Save one. The placement is stored resolved, not as typed: this run never
    // said --start-week, and centring is what has to survive.
    let saved = run(&["VYNCINT", "--year", "2027", "--save", "--no-colour"]);
    assert!(
        saved.status.success(),
        "{}",
        String::from_utf8_lossy(&saved.stderr)
    );
    // On stderr since 0.7.0: under `--format json` or `--format markdown`
    // stdout is a document, and this line was its first. It is still shown,
    // in every format, where a human at a terminal sees it.
    assert!(
        String::from_utf8_lossy(&saved.stderr).contains("mossaic-art --track"),
        "it says what is next, on stderr"
    );
    let spec: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(dir.join("mossaic-plan.json")).unwrap())
            .unwrap();
    assert_eq!(spec["text"], "VYNCINT");
    assert_eq!(spec["year"], 2027);
    assert_eq!(spec["start_week"], 6, "the centred column, resolved");
    assert_eq!(spec["top"], 1);

    // Now the flags are optional, and the plan is the same one.
    let tracked = run(&["--track", "--merge", "../../nonexistent.json"]);
    let error = String::from_utf8_lossy(&tracked.stderr).into_owned();
    assert!(
        error.contains("nonexistent.json"),
        "it should have got as far as reading the calendar: {error}"
    );

    // A typed flag still wins over the saved one.
    let overridden = run(&["--year", "2028", "--no-colour"]);
    assert!(
        stdout(&overridden).contains("2028"),
        "{}",
        stdout(&overridden)
    );
    assert!(
        !stdout(&overridden).contains("ยท 2027 ยท"),
        "{}",
        stdout(&overridden)
    );

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn every_binary_answers_the_basics() {
    for (name, binary) in [
        ("mossaic", env!("CARGO_BIN_EXE_mossaic")),
        ("mossaic-art", env!("CARGO_BIN_EXE_mossaic-art")),
        ("mossaic-glyphs", env!("CARGO_BIN_EXE_mossaic-glyphs")),
    ] {
        for flag in ["--help", "-h", "--version", "-V"] {
            let out = Command::new(binary).arg(flag).output().expect("runs");
            assert!(out.status.success(), "{name} {flag} failed");
            let text = String::from_utf8_lossy(&out.stdout).into_owned();
            assert!(!text.trim().is_empty(), "{name} {flag} printed nothing");
            if flag.contains("version") || flag == "-V" {
                assert!(
                    text.contains(env!("CARGO_PKG_VERSION")),
                    "{name} {flag} does not print the version: {text}"
                );
                assert!(text.starts_with(name), "{name} {flag} says: {text}");
            }
        }
    }
}

#[test]
fn bad_input_is_refused_the_same_way_by_every_binary() {
    // The two CLIs used to disagree about a year: one range-checked it, the
    // other passed 999999 through to a panic in the calendar.
    for binary in [
        env!("CARGO_BIN_EXE_mossaic"),
        env!("CARGO_BIN_EXE_mossaic-art"),
    ] {
        for bad in ["abc", "999999", "-5", "2101", "0"] {
            let out = Command::new(binary)
                .args(["HI", "--year", bad])
                .output()
                .expect("runs");
            let error = String::from_utf8_lossy(&out.stderr).into_owned();
            assert!(!out.status.success(), "{binary} accepted --year {bad}");
            assert!(
                error.contains("wants a year between 2000 and 2100"),
                "{binary} --year {bad}: {error}"
            );
            assert!(
                !error.contains("panicked"),
                "{binary} --year {bad} panicked"
            );
        }
        // And a missing value is a missing value, not the next flag.
        let out = Command::new(binary)
            .args(["--year"])
            .output()
            .expect("runs");
        assert!(String::from_utf8_lossy(&out.stderr).contains("--year needs a value"));
    }
}

#[test]
fn colour_follows_the_convention() {
    // Piped: no escapes. NO_COLOR: no escapes even when forced by a tty. And
    // --color always: escapes regardless.
    let piped = stdout(&art(&["--font"]));
    assert!(!piped.contains('\x1b'), "a pipe should get no colour");

    let forced = Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .current_dir(env!("CARGO_MANIFEST_DIR"))
        .args(["--font", "--color", "always"])
        .output()
        .expect("runs");
    assert!(
        String::from_utf8_lossy(&forced.stdout).contains('\x1b'),
        "--color always should colour a pipe"
    );

    let no_color = Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .current_dir(env!("CARGO_MANIFEST_DIR"))
        .env("NO_COLOR", "1")
        .args(["--font", "--color", "auto"])
        .output()
        .expect("runs");
    assert!(!String::from_utf8_lossy(&no_color.stdout).contains('\x1b'));

    let bad = Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .args(["--font", "--color", "chartreuse"])
        .output()
        .expect("runs");
    assert!(!bad.status.success());
    assert!(String::from_utf8_lossy(&bad.stderr).contains("auto, always or never"));
}

#[test]
fn a_background_is_drawn_as_a_shade_and_priced_as_one() {
    let out = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--background",
        "1",
        "--no-colour",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);

    // The two shades, and what a reader will make of them.
    assert!(
        text.contains("background level 1 under letters at level 4"),
        "{text}"
    );
    assert!(text.contains("290 background days, 1 each"), "{text}");
    assert!(text.contains("clear"), "level 1 under 4 is clear: {text}");
    assert!(!text.contains("faint"), "{text}");

    // 75 letter days at 4 plus 290 background days at 1.
    assert!(text.contains("590 commits"), "{text}");

    // The preview has to show three states now, not two, or there is no way to
    // check the art before making a single commit.
    assert!(text.contains('โ–‘'), "the field: {text}");
    assert!(text.contains('โ–ˆ'), "the letters: {text}");
}

#[test]
fn neighbouring_shades_are_drawn_but_said_to_be_faint() {
    let out = art(&["VYNCINT", "--year", "2027", "--bg", "3", "--no-colour"]);
    assert!(out.status.success(), "faint is a warning, not a refusal");
    let text = stdout(&out);
    assert!(text.contains("faint"), "{text}");
    assert!(
        text.contains("neighbouring shades"),
        "it should say why: {text}"
    );
    assert!(
        text.contains("--background 2"),
        "and what to do instead: {text}"
    );
}

#[test]
fn a_background_that_would_hide_the_letters_is_refused() {
    // Equal shades draw nothing at all, so this is an error rather than a note.
    let same = art(&["VYNCINT", "--year", "2027", "--background", "4"]);
    assert!(!same.status.success());
    assert_eq!(same.status.code(), Some(2));
    let error = String::from_utf8_lossy(&same.stderr).into_owned();
    assert!(error.contains("darker"), "{error}");

    let wild = art(&["VYNCINT", "--year", "2027", "--background", "7"]);
    assert!(!wild.status.success());
    let error = String::from_utf8_lossy(&wild.stderr).into_owned();
    assert!(error.contains("between 0 and 4"), "{error}");

    // The subtle one: the shades are fine, but --commits is too small for the
    // year to hold both of them, so the letters would come out the same colour
    // as the field.
    let cramped = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--background",
        "1",
        "--commits",
        "1",
    ]);
    assert!(!cramped.status.success());
    let error = String::from_utf8_lossy(&cramped.stderr).into_owned();
    assert!(error.contains("would not show"), "{error}");
    assert!(
        error.contains("at least 2 commits"),
        "it should quote the fix: {error}"
    );
}

#[test]
fn tracking_reports_the_letters_and_the_field_apart() {
    // The saved calendar is VYNCINT at four commits a day on an otherwise empty
    // year: the letters are finished, the background has not been started.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--track",
        "--merge",
        "art/vyncint-2027.json",
        "--background",
        "1",
        "--today",
        "2027-06-01",
        "--no-colour",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);

    assert!(
        text.contains("75 of 75 bright"),
        "the letters are done: {text}"
    );
    assert!(
        text.contains("0 of 290 at level 1"),
        "and the field is not: {text}"
    );
    assert!(
        text.contains("the shades"),
        "the plan says which two shades it means: {text}"
    );
    assert!(
        text.contains("a background day has to reach 1"),
        "and what one costs: {text}"
    );
    assert!(
        !text.contains("VYNCINT is drawn."),
        "finished letters are not a finished picture: {text}"
    );
    // The bug this guards: the verdict used to count only the letters, and so
    // announced "0 contributions to go" with the whole field still bare.
    assert!(
        text.contains("0 for the letters, 290 for the field"),
        "the verdict has to count both: {text}"
    );
}

#[test]
fn a_saved_plan_remembers_the_background() {
    let dir = scratch("plan-background-test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();

    let run = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
            .current_dir(&dir)
            .args(args)
            .output()
            .expect("the art binary runs")
    };

    let saved = run(&[
        "VYNCINT",
        "--year",
        "2027",
        "--background",
        "2",
        "--save",
        "--no-colour",
    ]);
    assert!(
        saved.status.success(),
        "{}",
        String::from_utf8_lossy(&saved.stderr)
    );
    let spec: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(dir.join("mossaic-plan.json")).unwrap())
            .unwrap();
    assert_eq!(spec["background"], 2, "the shade is part of the plan");

    // Later runs need no flags, and get the same picture.
    let again = stdout(&run(&["--no-colour"]));
    assert!(
        again.contains("background level 2 under letters at level 4"),
        "{again}"
    );

    // A plan written before backgrounds existed still loads, as no background.
    std::fs::write(
        dir.join("mossaic-plan.json"),
        r#"{"text":"HI","year":2027,"start_week":10,"top":1,"commits":4,"user":null}"#,
    )
    .unwrap();
    let old = run(&["--no-colour"]);
    assert!(
        old.status.success(),
        "{}",
        String::from_utf8_lossy(&old.stderr)
    );
    assert!(
        !stdout(&old).contains("background level"),
        "an old plan draws no background: {}",
        stdout(&old)
    );

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn a_background_check_meant_for_drawing_does_not_block_tracking() {
    // `--commits` is what `--write` puts on a lit day. Tracking never writes
    // one โ€” it works out what a letter day needs from the year's real peak โ€”
    // so the "these shades cannot be told apart" guard must not fire there.
    //
    // The regression: over a busy year, `--track --merge --background` was
    // refused with "the letters would not show", telling the user their plan
    // was impossible when the only thing wrong was a flag that run ignores.
    // The GitHub Action never hit it (it passes no --merge), so the two
    // disagreed about the same plan.
    let tracking = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--start-week",
        "6",
        "--background",
        "1",
        "--commits",
        "4",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2026-08-19",
        "--no-colour",
    ]);
    assert!(
        tracking.status.success(),
        "tracking must not be refused over --commits: {}",
        String::from_utf8_lossy(&tracking.stderr)
    );
    let text = stdout(&tracking);
    assert!(
        text.contains("letters at level 4, background at level 1"),
        "and it reports the shades the plan actually wants: {text}"
    );

    // The same flags without --track *would* draw, and there the guard is
    // right: 4 commits in a year peaking in the hundreds is level 1, the same
    // as the background, so the letters would be invisible.
    let drawing = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--start-week",
        "6",
        "--background",
        "1",
        "--commits",
        "4",
        "--merge",
        "art/vyncint-2026.json",
        "--no-colour",
    ]);
    assert!(
        !drawing.status.success(),
        "drawing with indistinguishable shades is still refused"
    );
    let error = String::from_utf8_lossy(&drawing.stderr).into_owned();
    assert!(error.contains("would not show"), "{error}");
}

#[test]
fn a_hole_is_called_a_hole_not_a_background_at_level_zero() {
    // With no background there is no field, so describing a spoiled day as
    // "background โ€” 113 contributions, 113 too many for level 0" names a shade
    // the plan never asked for. Inside the letters it is a hole, and that is
    // what it has to say โ€” the markdown report always got this right, so the
    // text report was the one disagreeing.
    //
    // 2026-08-19 is a lit day inside the letters in the calendar this reads, and
    // it is pinned rather than left to the clock. Without `--today` this test
    // asserted that whatever day it happened to run on was one of those, which
    // held on the day it was written and failed the morning after.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2026-08-19",
        "--no-colour",
    ]);
    assert!(out.status.success());
    let text = stdout(&out);
    let today = text
        .lines()
        .find(|line| line.trim_start().starts_with("today"))
        .expect("a year under way reports on today");
    assert!(
        !today.contains("level 0"),
        "there is no level-0 background to be over: {today}"
    );
    assert!(
        today.contains("permanent hole"),
        "a lit day inside the letters is a hole: {today}"
    );
}

#[test]
fn a_day_that_must_stay_dark_says_so_before_it_arrives() {
    // 2026-08-20 sits inside VYNCINT's block and is not part of a letter, so a
    // contribution on it punches a hole nothing takes back. Every surface used
    // to call it free โ€” "not part of the text โ€” anything you commit today
    // shows" โ€” because a clean day inside the text was dropped from the plan
    // for having nothing to say. It has the most to say of any day in the year.
    let args = |format: &'static str| -> Vec<&'static str> {
        vec![
            "VYNCINT",
            "--year",
            "2026",
            "--track",
            "--merge",
            "art/vyncint-2026.json",
            "--today",
            "2026-08-20",
            "--no-colour",
            "--format",
            format,
        ]
    };

    let text = stdout(&art(&args("text")));
    let today = text
        .lines()
        .find(|line| line.trim_start().starts_with("today"))
        .expect("a year under way reports on today");
    assert!(
        today.contains("keep it dark"),
        "the instruction has to be the instruction: {today}"
    );
    assert!(
        !today.contains("anything committed on it shows"),
        "and never the opposite of it: {today}"
    );
    // The seven-day schedule is where it is read a day early, which is the only
    // time the warning is worth anything.
    assert!(
        text.contains("Thu Aug 20   keep dark"),
        "the schedule names it too:\n{text}"
    );

    // And a machine reading the report gets the same answer, with a ceiling of
    // zero rather than the `null` that said "nothing is asked of this day".
    let json: serde_json::Value = serde_json::from_str(&stdout(&art(&args("json")))).expect("json");
    assert_eq!(json["today"]["kind"], "keep-dark");
    assert_eq!(json["today"]["ceiling"], 0);
    assert_eq!(json["today"]["over"], 0, "clean, so not yet a hole");
    // The count of real holes must not move: a day that must stay dark and has
    // is not damage.
    assert_eq!(json["holes"], 61);

    let md = stdout(&art(&args("markdown")));
    assert!(
        md.contains("| today | inside the letters โ€” keep it dark |"),
        "{md}"
    );
}

#[test]
fn today_is_an_input_so_a_report_is_reproducible() {
    // The whole reason `--today` exists: the answer to "what does today owe"
    // has to be a fact about a calendar and a date, not about when the command
    // ran. Two different dates, two different answers, both stable forever.
    let on = |date: &str| {
        stdout(&art(&[
            "VYNCINT",
            "--year",
            "2026",
            "--track",
            "--merge",
            "art/vyncint-2026.json",
            "--today",
            date,
            "--no-colour",
        ]))
    };

    let lit = on("2026-08-19");
    assert!(
        lit.contains("today       Wed Aug 19"),
        "the date it was told, not the date it is: {lit}"
    );
    let dark = on("2026-08-20");
    assert!(dark.contains("today       Thu Aug 20"), "{dark}");
    assert_ne!(
        lit, dark,
        "two days inside the same block, reported differently"
    );
    // Run twice, byte for byte the same โ€” which is what the clock never was.
    assert_eq!(lit, on("2026-08-19"));

    // A date the plan's year does not hold is not an answer about that plan.
    // Tracking 2026 in 2027 used to report on a day in 2027 and call it
    // `outside`, which is true of the wrong calendar.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2027-03-01",
        "--format",
        "json",
    ]);
    let json: serde_json::Value = serde_json::from_str(&stdout(&out)).expect("json");
    assert!(json["today"].is_null(), "{}", json["today"]);
    assert!(json["tomorrow"].is_null(), "{}", json["tomorrow"]);
    // And it says so, because `--today` carries no year of its own: the whole
    // "what to do next" half of the report disappears otherwise, which looks
    // like a bug rather than like an answer.
    let note = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(note.contains("2027-03-01 is after 2026"), "{note}");
    assert!(
        note.contains("no today or tomorrow"),
        "and why that matters: {note}"
    );

    for bad in ["notadate", "2026-13-01", "1999-01-01"] {
        let out = art(&["VYNCINT", "--track", "--today", bad]);
        assert!(!out.status.success(), "--today {bad} was accepted");
        assert_eq!(out.status.code(), Some(2));
    }
}

#[test]
fn numeric_flags_are_bounded_rather_than_cast() {
    // `--year` was range-checked because one binary once passed 999999 through
    // to a panic. Every other number took the unguarded path and `as` is not a
    // check: `--commits -1` came out as 4,294,967,295 โ€” which `--write` would
    // then try to build a fast-import stream for โ€” and `--start-week -1`
    // reached `usize::MAX`, where building a date from it panicked.
    for (flag, value, wanted) in [
        ("--commits", "-1", "between 1 and 1000000"),
        ("--commits", "0", "between 1 and 1000000"),
        ("--top", "-1", "between 0 and 2"),
        ("--top", "9", "between 0 and 2"),
        ("--start-week", "-1", "between 0 and 60"),
        ("--background", "-1", "between 0 and 4"),
    ] {
        let out = art(&["VYNCINT", "--year", "2027", flag, value]);
        let error = String::from_utf8_lossy(&out.stderr).into_owned();
        assert!(!out.status.success(), "{flag} {value} was accepted");
        assert_eq!(out.status.code(), Some(2), "{flag} {value}");
        assert!(error.contains(wanted), "{flag} {value}: {error}");
        assert!(!error.contains("panicked"), "{flag} {value}: {error}");
    }

    // In range for the flag but not for the year: the tight bound needs both
    // the calendar and the text, so `place` is what refuses it โ€” and it names
    // the last column that would have fitted rather than drawing nothing.
    let out = art(&["VYNCINT", "--year", "2027", "--start-week", "20"]);
    assert!(!out.status.success());
    let error = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(error.contains("past the end of 2027"), "{error}");
    assert!(error.contains("the last one that fits is 12"), "{error}");
}

#[test]
fn a_saved_plan_remembers_who_to_track() {
    // The plan stores whose contributions to compare against, and `--track`
    // threw it away: the user was read out of the file and then overwritten
    // with the nothing a bare `--track` carries. With `gh` off PATH the loss is
    // visible; with `gh` present it was worse than visible, because it tracked
    // the authenticated user while reporting against someone else's plan.
    let dir = scratch("plan-user-test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("mossaic-plan.json"),
        r#"{"text":"HI","year":2026,"start_week":10,"top":1,"commits":4,
            "background":0,"user":"octocat"}"#,
    )
    .unwrap();

    let out = Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .current_dir(&dir)
        .env("PATH", "/nonexistent")
        .args(["--track"])
        .output()
        .expect("the art binary runs");
    let error = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(
        error.contains("octocat"),
        "the plan named who to track: {error}"
    );
    assert!(
        !error.contains("could not tell whose"),
        "it knew all along โ€” it just threw the answer away: {error}"
    );

    // A user typed on the command line still wins over the saved one.
    let typed = Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .current_dir(&dir)
        .env("PATH", "/nonexistent")
        .args(["--track", "someone-else"])
        .output()
        .expect("the art binary runs");
    let error = String::from_utf8_lossy(&typed.stderr).into_owned();
    assert!(error.contains("someone-else"), "{error}");
    assert!(!error.contains("octocat"), "{error}");

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn a_calendar_from_another_year_says_so() {
    // Every day of a 2026 calendar falls outside a 2027 grid, so it filters
    // down to nothing and everything downstream is correct about an empty year:
    // 9,527 contributions read as none, and a plan that cannot be drawn reads
    // as reachable at one commit a day. Silence there is the same mistake the
    // plan file was introduced to prevent.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2027-06-01",
        "--no-colour",
    ]);
    assert!(out.status.success(), "a warning, not a refusal");
    let error = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(error.contains("holds no contributions in 2027"), "{error}");
    assert!(error.contains("it covers 2026"), "{error}");
    assert_eq!(
        error
            .lines()
            .filter(|line| line.contains("holds no"))
            .count(),
        1,
        "said once, not once per read: {error}"
    );

    // The matching year is quiet.
    let fine = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2026-08-19",
        "--no-colour",
    ]);
    assert!(!String::from_utf8_lossy(&fine.stderr).contains("holds no"));
}

#[test]
fn backfill_commits_only_what_is_short() {
    // The command `--track` used to print was a plain `--write`, which puts the
    // same flat count on every lit day โ€” including the ones already bright, and
    // adding to the busiest of them raises the very peak every letter day is
    // measured against. A shortfall cannot do that.
    let dir = scratch("backfill-test");
    let _ = std::fs::remove_dir_all(&dir);
    let repo = dir.to_string_lossy().into_owned();

    // A finished plan is short of nothing at all.
    let done = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--backfill",
        "--merge",
        "art/vyncint-2027.json",
        "--repo",
        &repo,
        "--today",
        "2027-12-31",
        "--no-colour",
    ]);
    assert!(
        done.status.success(),
        "{}",
        String::from_utf8_lossy(&done.stderr)
    );
    assert!(
        stdout(&done).contains("nothing to backfill"),
        "{}",
        stdout(&done)
    );
    assert!(!dir.exists(), "and it made no repository to do it in");

    // HI over that same calendar: some of its letter days are already lit by
    // VYNCINT's, and those must be left alone.
    let out = art(&[
        "HI",
        "--year",
        "2027",
        "--backfill",
        "--merge",
        "art/vyncint-2027.json",
        "--repo",
        &repo,
        "--write",
        // Past-only, so the run has to be told about a day after the letters it
        // is meant to reach. Without this the whole of 2027 is still to come and
        // there is correctly nothing to back-date.
        "--today",
        "2027-12-31",
        "--no-colour",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(text.contains("backfilling against"), "{text}");
    assert!(text.contains("never a flat count"), "{text}");
    assert!(text.contains("nothing has been pushed"), "{text}");

    // What git actually holds: every commit dated in the plan's year, and every
    // day it touched short of the four that calendar's peak asks for.
    let log = Command::new("git")
        .current_dir(&dir)
        .args(["log", "--format=%ad", "--date=short"])
        .output()
        .expect("git log runs");
    let dates: Vec<String> = String::from_utf8_lossy(&log.stdout)
        .lines()
        .map(str::to_string)
        .collect();
    assert!(!dates.is_empty(), "it wrote commits");
    assert!(
        dates.iter().all(|date| date.starts_with("2027-")),
        "back-dated into the plan's year: {dates:?}"
    );
    let mut per_day: std::collections::BTreeMap<&String, usize> = std::collections::BTreeMap::new();
    for date in &dates {
        *per_day.entry(date).or_default() += 1;
    }
    assert!(
        per_day.values().all(|count| *count == 4),
        "each short day gets exactly what it lacked of 4: {per_day:?}"
    );

    // A dry run is a dry run: nothing new after it.
    let before = dates.len();
    let dry = art(&[
        "HI",
        "--year",
        "2027",
        "--backfill",
        "--merge",
        "art/vyncint-2027.json",
        "--repo",
        &repo,
        "--today",
        "2027-12-31",
        "--no-colour",
    ]);
    assert!(
        stdout(&dry).contains("this was a dry run"),
        "{}",
        stdout(&dry)
    );
    let after = Command::new("git")
        .current_dir(&dir)
        .args(["rev-list", "--count", "HEAD"])
        .output()
        .expect("git rev-list runs");
    assert_eq!(
        String::from_utf8_lossy(&after.stdout).trim(),
        before.to_string(),
        "a dry run wrote something"
    );

    // The two modes are different questions, and running both would mean
    // guessing which was meant.
    let both = art(&["VYNCINT", "--track", "--backfill"]);
    assert!(!both.status.success());
    assert!(String::from_utf8_lossy(&both.stderr).contains("pick one"));

    // And it needs somewhere to write.
    let nowhere = art(&["VYNCINT", "--year", "2027", "--backfill"]);
    assert!(!nowhere.status.success());
    assert!(String::from_utf8_lossy(&nowhere.stderr).contains("--repo"));

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn a_plan_file_cannot_smuggle_past_the_flag_bounds() {
    // The flags are bounded; a plan file was not, and `--plan PATH` is a path.
    // Each of these got past a different guard: `top` wrapped `place`'s check
    // and drew the letters on scrambled rows, `commits` quoted four billion a
    // day, and the two years panicked or drew a calendar `--year` refuses.
    let dir = scratch("plan-bounds-test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();

    let run = |plan: &str| {
        std::fs::write(dir.join("mossaic-plan.json"), plan).unwrap();
        Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
            .current_dir(&dir)
            .args(["--no-colour"])
            .output()
            .expect("the art binary runs")
    };
    let plan = |field: &str, value: &str| {
        let mut fields = [
            ("text", "\"HI\""),
            ("year", "2027"),
            ("start_week", "10"),
            ("top", "1"),
            ("commits", "4"),
            ("background", "0"),
            ("user", "null"),
        ];
        for entry in fields.iter_mut() {
            if entry.0 == field {
                entry.1 = value;
            }
        }
        let body: Vec<String> = fields
            .iter()
            .map(|(key, val)| format!("\"{key}\":{val}"))
            .collect();
        format!("{{{}}}", body.join(","))
    };

    for (field, value, wanted) in [
        ("top", "18446744073709551615", "between 0 and 2"),
        ("commits", "4294967295", "between 1 and 1000000"),
        ("commits", "0", "between 1 and 1000000"),
        ("year", "-262143", "between 2000 and 2100"),
        ("year", "180000", "between 2000 and 2100"),
        ("start_week", "18446744073709551615", "between 0 and 60"),
        ("background", "9", "between 0 and 4"),
    ] {
        let out = run(&plan(field, value));
        let error = String::from_utf8_lossy(&out.stderr).into_owned();
        assert!(!out.status.success(), "plan {field}={value} was accepted");
        assert_eq!(out.status.code(), Some(2), "{field}={value}");
        assert!(
            error.contains("is not a plan these tools can use"),
            "{field}={value}: {error}"
        );
        // And it names the way out, because 0.2.0 could write a plan this
        // refuses: it accepted `--commits -1`, which `--save` wrote down as four
        // billion.
        assert!(error.contains("--save"), "{field}={value}: {error}");
        assert!(error.contains(wanted), "{field}={value}: {error}");
        assert!(!error.contains("panicked"), "{field}={value}: {error}");
        // The refusal names the value it refused, not a wrapped version of it.
        assert!(error.contains(value), "{field}={value}: {error}");
    }

    // And a sound plan still loads, or this test would pass by refusing
    // everything.
    let out = run(&plan("text", "\"HI\""));
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(stdout(&out).contains("HI  ยท  2027"), "{}", stdout(&out));

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn backfill_reaches_only_the_days_that_have_gone() {
    // `--track` prints this command under "only back-dated commits reach
    // those", and the help calls it the flag for catching up โ€” but it wrote the
    // whole year, future days included, and ignored `--today` entirely. A day
    // still to come wants an ordinary commit when it arrives, and whether
    // GitHub counts a future-dated one is unverified.
    let args = |today: &'static str| -> Vec<&'static str> {
        vec![
            "VYNCINT",
            "--year",
            "2026",
            "--backfill",
            "--merge",
            "art/vyncint-2026.json",
            "--repo",
            "/nonexistent-dry-run",
            "--today",
            today,
            "--no-colour",
        ]
    };

    let mid = stdout(&art(&args("2026-08-19")));
    // The same 34 days and 3,464 commits `--track` calls "already past": both
    // answers come from one plan and one date, so they agree by construction.
    assert!(mid.contains("3,464 commits across 34 days"), "{mid}");
    assert!(
        mid.contains("latest 2026-08-14"),
        "nothing after today: {mid}"
    );
    assert!(
        mid.contains("23 days from 2026-08-19 on are short too, and left alone"),
        "and it says what it is leaving: {mid}"
    );

    // Later in the year, more of it is reachable.
    let end = stdout(&art(&args("2026-12-31")));
    assert!(end.contains("5,994 commits across 57 days"), "{end}");

    // Before the year starts, none of it is โ€” and it says why rather than
    // claiming the plan is finished.
    let early = stdout(&art(&args("2026-01-01")));
    assert!(
        early.contains("every day the plan is short of is still to come"),
        "{early}"
    );

    // A year that cannot be drawn cleanly says so before an irreversible write.
    assert!(
        mid.contains("cannot be drawn cleanly in 2026") && mid.contains("61 days inside the"),
        "a warning belongs where the commits do: {mid}"
    );
}

#[test]
fn tracking_a_year_that_has_not_started_is_not_a_mistake() {
    // The first example in the help, the README and docs/ART.md. The clock is
    // not in 2027, and that is the normal case โ€” the report answers it properly.
    // A note saying "add --year 2026" told people their own year was wrong.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--track",
        "--merge",
        "art/vyncint-2027.json",
        "--today",
        "2026-08-19",
        "--no-colour",
    ]);
    assert!(out.status.success());
    let note = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(note.is_empty(), "nothing to warn about: {note}");
    assert!(
        stdout(&out).contains("2027 has not started"),
        "{}",
        stdout(&out)
    );
    // Nor when the date comes from the clock, whatever year that turns out to
    // be: the note is about a year that has ended, not about one it is not.
    let bare = art(&[
        "VYNCINT",
        "--year",
        "2100",
        "--track",
        "--merge",
        "art/vyncint-2027.json",
        "--no-colour",
    ]);
    assert!(String::from_utf8_lossy(&bare.stderr)
        .lines()
        .all(|line| !line.contains("no today or tomorrow")));

    // A typed `--today` that misses the year still explains itself, because
    // there the missing today/tomorrow section is a surprise.
    let missed = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2027-03-01",
        "--no-colour",
    ]);
    assert!(String::from_utf8_lossy(&missed.stderr).contains("2027-03-01 is after 2026"));
}

#[test]
fn tracking_refuses_a_flag_it_would_have_ignored() {
    // Tracking writes nothing, so a flag asking it to write was doing nothing at
    // all โ€” silently, which is worse than refusing. Distinct from `--commits`,
    // which tracking has no use for but which is a tuning parameter rather than a
    // side effect somebody asked for.
    for extra in [
        vec!["--snapshot", "/tmp/mossaic-should-not-exist.json"],
        vec!["--write"],
        vec!["--repo", "/tmp/mossaic-should-not-exist"],
    ] {
        let mut args = vec![
            "VYNCINT",
            "--year",
            "2026",
            "--track",
            "--merge",
            "art/vyncint-2026.json",
            "--today",
            "2026-08-19",
            "--no-colour",
        ];
        args.extend_from_slice(&extra);
        let out = art(&args);
        let error = String::from_utf8_lossy(&out.stderr).into_owned();
        assert!(!out.status.success(), "{extra:?} was accepted");
        assert_eq!(out.status.code(), Some(2), "{extra:?}");
        assert!(error.contains("writes nothing"), "{extra:?}: {error}");
        assert!(error.contains(extra[0]), "{extra:?}: {error}");
    }
    assert!(
        !Path::new("/tmp/mossaic-should-not-exist.json").exists(),
        "and nothing was written on the way to refusing"
    );

    // `--commits` is still fine, which is the distinction.
    let fine = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2026-08-19",
        "--commits",
        "4",
        "--no-colour",
    ]);
    assert!(
        fine.status.success(),
        "{}",
        String::from_utf8_lossy(&fine.stderr)
    );
}

#[test]
fn every_binary_parses_arguments_the_same_way() {
    // `cli::Args` exists "so that the tools agree about the things a user
    // notices: that `--year 2027` and `--year=2027` are the same, that a missing
    // value says so rather than being read as the next flag, and that every error
    // looks like `mossaic-art: โ€ฆ` and exits 2". `mossaic-glyphs` parsed by hand
    // and agreed about none of it.
    for (name, binary) in [
        ("mossaic", env!("CARGO_BIN_EXE_mossaic")),
        ("mossaic-art", env!("CARGO_BIN_EXE_mossaic-art")),
        ("mossaic-glyphs", env!("CARGO_BIN_EXE_mossaic-glyphs")),
    ] {
        let run = |args: &[&str]| {
            Command::new(binary)
                .current_dir(env!("CARGO_MANIFEST_DIR"))
                .args(args)
                .output()
                .expect("runs")
        };

        // An unknown option is an error, and says whose.
        let out = run(&["--definitely-not-a-flag"]);
        let error = String::from_utf8_lossy(&out.stderr).into_owned();
        assert_eq!(out.status.code(), Some(2), "{name}: {error}");
        assert!(error.starts_with(&format!("{name}: ")), "{name}: {error}");
        assert!(error.contains("unknown option"), "{name}: {error}");

        // `--key=value` is the same as `--key value`: forced colour reaches a pipe
        // either way. (`mossaic` needs a source it can render without a network.)
        let colour_args: Vec<Vec<&str>> = match name {
            "mossaic-art" => vec![
                vec!["--font", "--color", "always"],
                vec!["--font", "--color=always"],
            ],
            "mossaic-glyphs" => vec![vec!["--color", "always"], vec!["--color=always"]],
            // The chart's colour comes from the terminal, not a flag; check the
            // `=` form on one it does take.
            _ => vec![
                vec!["--demo", "--png", "/dev/null", "--theme", "light"],
                vec!["--demo", "--png", "/dev/null", "--theme=light"],
            ],
        };
        let mut outcomes = Vec::new();
        for args in &colour_args {
            let out = run(&args.to_vec());
            outcomes.push((
                out.status.success(),
                String::from_utf8_lossy(&out.stdout).contains('\x1b'),
            ));
        }
        assert_eq!(
            outcomes[0], outcomes[1],
            "{name}: the `=` form behaves differently"
        );
        assert!(outcomes[0].0, "{name}: the spaced form should work at all");

        // A missing value says so rather than swallowing the next argument.
        let flag = match name {
            "mossaic-glyphs" => "--color",
            _ => "--year",
        };
        let out = run(&[flag]);
        let error = String::from_utf8_lossy(&out.stderr).into_owned();
        assert_eq!(out.status.code(), Some(2), "{name} {flag}: {error}");
        assert!(
            error.contains("needs a value") || error.contains("wants a"),
            "{name} {flag}: {error}"
        );
    }
}

/// A flag that names a companion either honours it or refuses the pair.
///
/// #26 settled this in the maintainer's own words โ€” "They are side effects
/// and inputs the user explicitly asked for โ€ฆ Either honour them or refuse
/// the combination" โ€” and enumerated `--snapshot`, `--write` and `--file`,
/// all three of which are refused. `--png`, `-o` and `--format` were missed:
/// each was accepted in every mode and honoured in one, at exit 0, with an
/// empty stderr and no file.
///
/// The cost is the shape a script cannot see.
/// `mossaic-art --template dragon --png preview.png` in a workflow printed a
/// cheerful report, exited 0 and produced nothing, so the next step read a
/// file that was not there โ€” or republished the previous run's stale PNG.
/// `install.yml` only ever runs `--font --png`, the one pair that works.
#[test]
fn a_flag_that_names_a_companion_is_refused_without_it() {
    let png = scratch("refused.png");
    let png = png.to_str().unwrap();
    let cases: [(&[&str], &str); 7] = [
        (
            &["--template", "dragon", "--year", "2027", "--png"],
            "--font",
        ),
        (
            &[
                "--matrix",
                "art/templates/dragon.art",
                "--year",
                "2027",
                "--png",
            ],
            "--font",
        ),
        (&["VYNCINT", "--year", "2027", "--png"], "--font"),
        (&["--list-templates", "--png"], "--font"),
        (&["--track", "--png"], "--font"),
        (&["--backfill", "--repo", "/tmp/nope", "--png"], "--font"),
        (
            &["--image", "art/dragon.png", "--year", "2027", "--png"],
            "--font",
        ),
    ];
    for (args, needs) in cases {
        let _ = std::fs::remove_file(png);
        let mut argv: Vec<&str> = args.to_vec();
        argv.push(png);
        argv.extend(["--no-colour", "--plan", "/dev/null"]);
        let out = art(&argv);
        let text = String::from_utf8_lossy(&out.stderr);
        assert_eq!(
            out.status.code(),
            Some(2),
            "{args:?} must be refused\n{text}"
        );
        assert!(
            text.contains(needs),
            "{args:?}: the message names {needs}\n{text}"
        );
        assert!(
            !Path::new(png).exists(),
            "{args:?}: a refused run writes no file"
        );
    }

    // The one pair that works is untouched.
    let out = art(&["--font", "--png", png, "--no-colour"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(Path::new(png).exists(), "--font --png still writes it");
    let _ = std::fs::remove_file(png);

    // The two adjacent silent no-ops.
    for (args, needs) in [
        (
            vec!["-o", "/tmp/nope.art", "VYNCINT", "--year", "2027"],
            "--draw",
        ),
        (
            vec!["VYNCINT", "--year", "2027", "--format", "json"],
            "--track",
        ),
    ] {
        let mut argv = args.clone();
        argv.extend(["--no-colour", "--plan", "/dev/null"]);
        let out = art(&argv);
        let text = String::from_utf8_lossy(&out.stderr);
        assert_eq!(out.status.code(), Some(2), "{args:?}\n{text}");
        assert!(text.contains(needs), "{args:?}\n{text}");
    }
}

/// `--` means the rest is text, including the hyphen the font draws.
///
/// `-` is a glyph this project lists three times โ€” README's punctuation
/// line, `action.yml`'s `text:` description, and the binary's own no-glyph
/// message โ€” and it could not be typed in the position all three put it in.
/// Worse, `--` was itself reported as the unknown option, so the escape
/// hatch a user reaches for named itself as the mistake, and no quoting
/// helped. You reach for `mossaic-art -- "$TEXT"` precisely when the text is
/// not yours to control, which is what the Action does with `text:`.
#[test]
fn a_double_dash_makes_the_rest_text() {
    for (text, columns) in [("-", 5), ("-.-", 17), ("A-B", 17)] {
        let out = art(&[
            "--year",
            "2027",
            "--no-colour",
            "--plan",
            "/dev/null",
            "--",
            text,
        ]);
        let first = String::from_utf8_lossy(&out.stdout)
            .lines()
            .next()
            .unwrap_or_default()
            .to_string();
        assert!(
            out.status.success(),
            "{text:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(
            first.starts_with(&text.to_uppercase()),
            "{text:?} is the subject: {first}"
        );
        assert!(
            first.contains(&format!("{columns} of 53 columns")),
            "{text:?} draws {columns} columns: {first}"
        );
    }

    // An argument that looks like a flag is text after `--`.
    let out = art(&["--no-colour", "--plan", "/dev/null", "--", "-h"]);
    assert!(
        String::from_utf8_lossy(&out.stdout).starts_with("-H"),
        "`-- -h` draws rather than printing help"
    );

    // A genuine unknown option is still one, and the message points at `--`
    // when the argument could plausibly have been the text.
    let out = art(&["-A-"]);
    let text = String::from_utf8_lossy(&out.stderr);
    assert_eq!(out.status.code(), Some(2));
    assert!(text.contains("unknown option"), "{text}");
    assert!(text.contains("--"), "the way out is named: {text}");

    // And `--` means *everything* after it, as it does in `ls` and `git`, so
    // an option written after the text is an error that says so.
    let out = art(&["--", "-", "--year", "2027"]);
    let text = String::from_utf8_lossy(&out.stderr);
    assert_eq!(out.status.code(), Some(2), "{text}");
    assert!(text.contains("put the options before it"), "{text}");
}

/// `--track --save` writes a machine document to stdout and nothing else.
///
/// The `saved โ€ฆ` confirmation was the single `println!` that could run ahead
/// of the document, so `--format json | jq .` got two lines of prose first โ€”
/// at exit 0, with an empty stderr, so there was no signal anywhere. It bit
/// only on the run that writes the plan, so it read as a flake on first use.
#[test]
fn saving_a_plan_does_not_write_prose_into_a_machine_document() {
    let plan = scratch("saveformat.json");
    let merge = Path::new(env!("CARGO_MANIFEST_DIR")).join("art/vyncint-2026.json");

    for format in ["json", "markdown"] {
        let _ = std::fs::remove_file(&plan);
        let out = art(&[
            "VYNCINT",
            "--year",
            "2026",
            "--start-week",
            "6",
            "--track",
            "--save",
            "--plan",
            plan.to_str().unwrap(),
            "--merge",
            merge.to_str().unwrap(),
            "--today",
            "2026-08-19",
            "--format",
            format,
            "--no-colour",
        ]);
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
        let text = String::from_utf8_lossy(&out.stdout);
        match format {
            "json" => {
                serde_json::from_str::<serde_json::Value>(&text)
                    .unwrap_or_else(|e| panic!("stdout must be one JSON document: {e}\n{text}"));
            }
            _ => assert!(
                text.starts_with("### "),
                "stdout must start with the heading:\n{text}"
            ),
        }
        // The confirmation is still shown โ€” on stderr, where a human sees it.
        assert!(
            String::from_utf8_lossy(&out.stderr).contains("mossaic-art --track"),
            "the confirmation is not lost, only moved"
        );
        assert!(plan.exists(), "and the plan is written");
    }
    let _ = std::fs::remove_file(&plan);
}

/// `--help`'s description of `--commits` has to price what the tool prices.
///
/// It said "commits per lit day", and a reader who did that multiplication
/// on the shipped dragon arrived at 584 where the tool prints 442 โ€” a 32%
/// overestimate from following the help exactly. `--commits` prices the
/// *brightest* day; darker shades are priced against it, which docs/ART.md
/// and the source comment both say correctly. The help is the only
/// description a `cargo install` user gets: `docs/*` is excluded from the
/// published archive and README never mentions the flag.
#[test]
fn the_help_prices_commits_the_way_the_report_does() {
    let help = String::from_utf8_lossy(&art(&["--help"]).stdout).into_owned();
    let line = help
        .lines()
        .find(|l| l.trim_start().starts_with("--commits"))
        .expect("--commits is documented");
    assert!(
        line.contains("brightest"),
        "the help must price the brightest shade, not every lit day: {line}"
    );

    // And the arithmetic it now describes is the one the report performs.
    let report = String::from_utf8_lossy(
        &art(&[
            "--template",
            "dragon",
            "--year",
            "2027",
            "--no-colour",
            "--plan",
            "/dev/null",
        ])
        .stdout,
    )
    .into_owned();
    let header: u32 = report
        .lines()
        .next()
        .and_then(|l| l.rsplit("ยท").next())
        .and_then(|tail| tail.split_whitespace().next().map(str::to_string))
        .and_then(|n| n.replace(',', "").parse().ok())
        .expect("the header names a commit total");
    // Sum the level rows: `      4    75   4`.
    let mut table = 0u32;
    for line in report.lines() {
        let cells: Vec<&str> = line.split_whitespace().collect();
        // Edition 2021 here, so no let-chains.
        if let [level, days, each] = cells.as_slice() {
            if let (Ok(_), Ok(days), Ok(each)) = (
                level.parse::<u32>(),
                days.replace(',', "").parse::<u32>(),
                each.replace(',', "").parse::<u32>(),
            ) {
                table += days * each;
            }
        }
    }
    assert_eq!(
        table, header,
        "the level table must price out to the header:\n{report}"
    );
}

/// The cost table counts the days the year has, not the cells the canvas has.
///
/// A full-width picture is 7 x 53 = 371 cells against a year of 365, and the
/// preview table counted all of them โ€” so it disagreed with the header
/// directly above it and with what `--write` makes, immediately after a note
/// saying cells had been dropped. The four shipped templates cannot catch
/// this: all of them are drawn clear of the partial weeks across 2000-2100,
/// which is why this plants its own ink there.
///
/// README says of the editor panel "the same arithmetic `--write` uses, not
/// an estimate of it", and the table is what somebody budgets against before
/// making commits that cannot be unmade.
#[test]
fn the_cost_table_prices_out_to_the_header() {
    // 2027-01-01 is a Friday, so column 0's Sun..Thu and column 52's tail are
    // outside the year. Ink in both, plus one cell that is genuinely inside.
    let mut rows = vec![vec!['0'; 53]; 7];
    rows[0][0] = '4'; // outside: before Jan 1
    rows[6][52] = '4'; // outside: after Dec 31
    rows[5][0] = '4'; // inside: Friday of week 0 is Jan 1 itself
    rows[3][10] = '2'; // inside, comfortably
    let body = format!(
        "# name: Edges\n{}\n",
        rows.iter()
            .map(|row| row.iter().collect::<String>())
            .collect::<Vec<_>>()
            .join("\n")
    );
    let path = scratch("edges.art");
    std::fs::write(&path, body).unwrap();

    let out = art(&[
        "--matrix",
        path.to_str().unwrap(),
        "--year",
        "2027",
        "--no-colour",
        "--plan",
        "/dev/null",
    ]);
    let report = String::from_utf8_lossy(&out.stdout).into_owned();
    let _ = std::fs::remove_file(&path);

    // The header: `Edges  ยท  2027  ยท  N of 53 columns  ยท  D days  ยท  C commits`
    let header = report.lines().next().unwrap_or_default();
    let fields: Vec<&str> = header.split('ยท').map(str::trim).collect();
    let header_days: usize = fields[3]
        .split_whitespace()
        .next()
        .unwrap()
        .parse()
        .unwrap();
    let header_commits: u32 = fields[4]
        .split_whitespace()
        .next()
        .unwrap()
        .replace(',', "")
        .parse()
        .unwrap();

    // The table: `      4     2   4` and `      0   363   must stay dark`.
    let (mut table_days, mut table_commits, mut dark) = (0usize, 0u32, 0usize);
    for line in report.lines() {
        let cells: Vec<&str> = line.split_whitespace().collect();
        if cells.len() == 3 {
            if let (Ok(level), Ok(days), Ok(each)) = (
                cells[0].parse::<u8>(),
                cells[1].replace(',', "").parse::<usize>(),
                cells[2].replace(',', "").parse::<u32>(),
            ) {
                if level > 0 {
                    table_days += days;
                    table_commits += days as u32 * each;
                }
            }
        }
        if cells.len() == 5 && cells[0] == "0" && line.contains("must stay dark") {
            dark = cells[1].replace(',', "").parse().unwrap();
        }
    }

    assert_eq!(
        table_days, header_days,
        "the level rows must sum to the header's day count:\n{report}"
    );
    assert_eq!(
        table_commits, header_commits,
        "and price out to its commit total:\n{report}"
    );
    assert_eq!(
        table_days + dark,
        365,
        "lit rows plus level 0 are the days 2027 has, not 53x7:\n{report}"
    );
}

/// A picture whose only ink falls outside the year gets no legibility verdict.
///
/// The verdict was computed from the raw canvas, so a drawing that puts
/// nothing at all inside the year still reported `shades 0 4 ยท closest pair
/// 0 and 4 ยท ฮ”E 70, clear` โ€” the one check this project tells you to read
/// twice, passing on a drawing that does not exist.
#[test]
fn a_picture_that_draws_nothing_claims_no_legibility() {
    let mut rows = vec![vec!['0'; 53]; 7];
    rows[0][0] = '4';
    rows[6][52] = '4';
    let body = format!(
        "# name: Outside\n{}\n",
        rows.iter()
            .map(|row| row.iter().collect::<String>())
            .collect::<Vec<_>>()
            .join("\n")
    );
    let path = scratch("outside.art");
    std::fs::write(&path, body).unwrap();
    let out = art(&[
        "--matrix",
        path.to_str().unwrap(),
        "--year",
        "2027",
        "--no-colour",
        "--plan",
        "/dev/null",
    ]);
    let report = String::from_utf8_lossy(&out.stdout).into_owned();
    let _ = std::fs::remove_file(&path);

    assert!(
        !report.contains("closest pair"),
        "a drawing with no ink in the year has no shades to compare:\n{report}"
    );
    assert!(
        report.contains("0 days") && report.contains("0 commits"),
        "and its header says so:\n{report}"
    );
}

/// A template that does not parse is named, not silently skipped.
///
/// `templates::read_dir`'s own doc comment calls `--list-templates` "the
/// command you would reach for to find out which one is broken" โ€” and it
/// named nothing, counted nothing and wrote no byte to stderr. So the same
/// file got "a canvas is exactly 7 rows" from `--matrix` and "no template
/// named sixer" from `--template`: an error about a *name*, for a file
/// sitting right there under that name, which sends the search to the wrong
/// place.
///
/// #57 โ€” this project's own good-first-issue walkthrough โ€” puts a
/// first-time contributor on exactly this path: `cp your-name.art
/// templates/ && mossaic-art --list-templates`.
#[test]
fn a_broken_template_is_named_rather_than_skipped_in_silence() {
    let dir = scratch("tpl");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("templates")).unwrap();
    std::fs::write(dir.join("templates/broken.art"), "ZZZZZ\nZZZZ\n").unwrap();
    std::fs::write(
        dir.join("templates/sixer.art"),
        "# name: Sixer\n000\n000\n000\n000\n000\n000\n",
    )
    .unwrap();
    // A valid one beside them, so the listing still lists.
    std::fs::write(
        dir.join("templates/goodun.art"),
        "# name: Goodun\n0000\n0400\n0040\n0004\n0000\n0000\n0000\n",
    )
    .unwrap();

    let in_dir = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
            .current_dir(&dir)
            .args(args)
            .output()
            .expect("the art binary runs")
    };

    let listing = in_dir(&["--list-templates", "--no-colour"]);
    let text = String::from_utf8_lossy(&listing.stdout).into_owned();
    assert!(
        listing.status.success(),
        "one broken file must not fail the listing"
    );
    assert!(text.contains("Goodun"), "the good one still lists:\n{text}");
    for (file, why) in [("broken.art", "not a shade"), ("sixer.art", "7 rows")] {
        assert!(text.contains(file), "{file} must be named:\n{text}");
        assert!(text.contains(why), "and why it was skipped:\n{text}");
    }

    // And `--template <stem>` gives the parse error, not "no template named".
    let miss = in_dir(&[
        "--template",
        "sixer",
        "--year",
        "2027",
        "--no-colour",
        "--plan",
        "/dev/null",
    ]);
    let text = String::from_utf8_lossy(&miss.stderr).into_owned();
    assert_eq!(miss.status.code(), Some(2), "{text}");
    assert!(
        text.contains("7 rows"),
        "the parse error, not a name miss:\n{text}"
    );
    assert!(!text.contains("no template named"), "{text}");

    // A broken local file that shadows a built-in no longer silently draws
    // the built-in: the same command used to produce two different pictures
    // depending on whether the user's file happened to parse.
    std::fs::write(dir.join("templates/dragon.art"), "000\n000\n000\n").unwrap();
    let shadowed = in_dir(&[
        "--template",
        "dragon",
        "--year",
        "2027",
        "--no-colour",
        "--plan",
        "/dev/null",
    ]);
    let text = String::from_utf8_lossy(&shadowed.stderr).into_owned();
    assert_eq!(shadowed.status.code(), Some(2), "{text}");
    assert!(text.contains("dragon.art"), "{text}");

    let _ = std::fs::remove_dir_all(&dir);
}

/// A plan's mistyped key is refused by name, the way a bad value already was.
///
/// The loader was loud about every wrong *value* โ€” `background: 99` is "not
/// between 0 and 4" โ€” and silent about a wrong *key*: `backgruond: 2` was
/// accepted and the default applied, turning about 290 background days into
/// keep-dark days at exit 0 with nothing on stderr. Dropping `art` turned a
/// 146-day picture into a 79-day text. A plan is the input to
/// `--backfill --write`, and contributions cannot be unlit.
#[test]
fn a_plan_with_a_key_it_does_not_know_is_refused() {
    let plan = scratch("keys.json");
    let good = r#"{"text":"VYNCINT","year":2027,"start_week":6,"top":1,
                   "commits":4,"background":2,"user":null}"#;
    std::fs::write(&plan, good).unwrap();
    let out = art(&["--plan", plan.to_str().unwrap(), "--no-colour"]);
    assert!(
        out.status.success(),
        "the control plan loads: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    for (label, body) in [
        ("a typo", good.replace("background", "backgruond")),
        ("a case change", good.replace("\"user\"", "\"User\"")),
        (
            "a key from the future",
            good.replace("}", r#","outline":true}"#),
        ),
    ] {
        std::fs::write(&plan, &body).unwrap();
        let out = art(&["--plan", plan.to_str().unwrap(), "--no-colour"]);
        let text = String::from_utf8_lossy(&out.stderr).into_owned();
        assert_eq!(
            out.status.code(),
            Some(2),
            "{label}: must be refused\n{text}"
        );
        assert!(text.contains("unknown field"), "{label}: by name\n{text}");
    }

    // A bad *value* is still refused the way it always was.
    std::fs::write(&plan, good.replace("\"background\":2", "\"background\":99")).unwrap();
    let out = art(&["--plan", plan.to_str().unwrap(), "--no-colour"]);
    let text = String::from_utf8_lossy(&out.stderr).into_owned();
    assert_eq!(out.status.code(), Some(2), "{text}");
    assert!(text.contains("background"), "{text}");
    let _ = std::fs::remove_file(&plan);
}

/// A file the user named is not blamed on `gh`.
///
/// `--file` and the network share one parser, whose only wording was
/// "unexpected response from gh" โ€” so a truncated local file was reported as
/// the GitHub CLI returning something odd, on a run where `gh` was never
/// executed, and `{"data":{}}` was reported as GitHub having no such login.
/// The reader then checks `gh auth status`, the username and the network:
/// everything except the JSON in front of them. `--file` is also the flag
/// most likely to be handed a file another process is still writing.
#[test]
fn a_file_the_user_named_is_not_blamed_on_gh() {
    let cases: [(&str, &str); 4] = [
        ("notjson", "not json"),
        ("empty", ""),
        ("nouser", r#"{"data":{}}"#),
        ("nocalendar", r#"{"data":{"user":{"login":"x"}}}"#),
    ];
    for (label, body) in cases {
        let path = scratch(&format!("{label}.json"));
        std::fs::write(&path, body).unwrap();
        let named = path.to_str().unwrap();

        // Through the chartโ€ฆ
        let out = Command::new(env!("CARGO_BIN_EXE_mossaic"))
            .current_dir(env!("CARGO_MANIFEST_DIR"))
            .args(["--file", named, "--png", "/tmp/mossaic-blame.png"])
            .stdin(std::process::Stdio::null())
            .output()
            .expect("the chart binary runs");
        let text = String::from_utf8_lossy(&out.stderr).into_owned();
        assert_eq!(out.status.code(), Some(2), "{label}: {text}");
        assert!(text.contains(named), "{label}: the path is named\n{text}");
        assert!(
            !text.contains("gh"),
            "{label}: and gh is not blamed\n{text}"
        );

        // โ€ฆand through the tracker's --merge, which shares the loader.
        let out = art(&[
            "VYNCINT",
            "--year",
            "2026",
            "--track",
            "--merge",
            named,
            "--no-colour",
            "--plan",
            "/dev/null",
        ]);
        let text = String::from_utf8_lossy(&out.stderr).into_owned();
        assert!(text.contains(named), "{label} via --merge:\n{text}");
        assert!(!text.contains("gh"), "{label} via --merge:\n{text}");
        // And the path is named once, not quoted and then repeated.
        assert_eq!(
            text.matches(named).count(),
            1,
            "{label}: the path appears once\n{text}"
        );
        let _ = std::fs::remove_file(&path);
    }
}

/// Every block the docs label "to reproduce this exactly" still reproduces.
///
/// These blocks are not illustrations, they are the project's fixtures:
/// `--today` exists precisely so "a documented sample stops being true
/// overnight" cannot happen, and the pages hand a reader a command and the
/// exact output it produces. 0.6.3's plural pass changed the wording of
/// sixteen quoted lines and regenerated none of them, so every figure
/// matched and every line was worded differently โ€” a reader diffing their
/// own output against the page cannot tell wording drift from a real
/// regression, and a contributor copying the documented wording into a new
/// message reintroduces the plural the release removed.
///
/// AGENTS.md states the standard this enforces: "Documentation is checked,
/// not maintained. Where a README states a fact the code owns, there is
/// usually a test asserting the two agree."
#[test]
fn the_documented_reports_still_read_the_way_the_docs_print_them() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let m26 = root.join("art/vyncint-2026.json");
    let m26 = m26.to_str().unwrap();
    let m27 = root.join("art/vyncint-2027.json");
    let m27 = m27.to_str().unwrap();

    // Each documented invocation, and the quoted lines it has to produce.
    // Pinned by `--today` and `--merge`, which is why this is possible.
    let cases: Vec<(Vec<&str>, Vec<&str>)> = vec![
        (
            vec![
                "VYNCINTNG",
                "--year",
                "2027",
                "--no-colour",
                "--plan",
                "/dev/null",
            ],
            vec!["3 lit pixels fell outside 2027"],
        ),
        (
            vec![
                "VYNCINT",
                "--year",
                "2027",
                "--background",
                "1",
                "--no-colour",
                "--plan",
                "/dev/null",
            ],
            vec!["290 background days, 1 each"],
        ),
        (
            vec![
                "VYNCINT",
                "--year",
                "2026",
                "--start-week",
                "6",
                "--track",
                "--merge",
                m26,
                "--today",
                "2026-08-19",
                "--no-colour",
                "--plan",
                "/dev/null",
            ],
            vec![
                "owing       57 days short, 5,994 contributions between them",
                "holes       61 days are lit inside the letters and cannot be unlit",
                "around      23 days outside the text with contributions",
                "61 days inside the letters already have contributions, and",
                "23 letter days still to come, 2,530 contributions",
                "34 letter days already past, 3,464 contributions",
            ],
        ),
        (
            vec![
                "--template",
                "dragon",
                "--year",
                "2027",
                "--track",
                "--merge",
                m27,
                "--today",
                "2027-08-19",
                "--no-colour",
                "--plan",
                "/dev/null",
            ],
            vec!["still owing  104 days ยท 302 contributions"],
        ),
    ];

    let docs = ["README.md", "docs/ART.md"]
        .iter()
        .map(|name| std::fs::read_to_string(root.join(name)).expect("a documented page"))
        .collect::<Vec<_>>()
        .join("\n");

    for (args, quoted) in cases {
        let out = art(&args);
        let text = format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        for line in quoted {
            assert!(
                text.contains(line),
                "the tool no longer prints a documented line.\n  wanted: {line}\n  from:  \
                 mossaic-art {}\n--- got ---\n{text}",
                args.join(" ")
            );
            assert!(
                docs.contains(line),
                "the docs no longer quote a line the tool prints: {line}"
            );
        }
    }

    // And nothing anywhere still prints a parenthesized plural, which is what
    // 0.6.3 announced and what this test exists to keep true.
    assert!(
        !docs.contains("day(s)") && !docs.contains("commit(s)") && !docs.contains("pixel(s)"),
        "a parenthesized plural is back in the docs"
    );
}