tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
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
//! Cross-surface verification target (mission `cycle-capacity-planning-01M3C85C`, WP09).
//!
//! Every other capacity target proves **one** surface: `capacity_config.rs` the section,
//! `capacity_estimate.rs` the conversion/index pass, `capacity_calculate.rs` the DTO,
//! `capacity_snapshot.rs` the evidence, `capacity_cli.rs` the commands,
//! `capacity_portable.rs` the document, `tests/mcp.rs` the tools, `tests/tui_state.rs`
//! the page. This one proves the claim they all exist to make: that the four surfaces are
//! **one answer**. A single fixture is read through the CLI, the TUI (its Capacity tab,
//! its board cell), the MCP tools and the portable document, and the values, the unit,
//! the rounding, the warnings, the snapshot identity and the History summary are
//! compared field for field.
//!
//! It is also where the mission's structural performance evidence lives (NFR-001):
//! 10,000 in-memory issues, indexed once, asserted on the snapshot's own work counters
//! rather than on a wall clock. A wall-clock budget is already owned by
//! `tests/capacity_estimate.rs::one_pass_indexes_ten_thousand_issues_within_the_budget`,
//! and the tracer records that a contended machine breaks it (one `mcp` run reported
//! 173/4 under load, and a lone `cycle_schedules` budget failure was never reproducible
//! serially) — so this target deliberately adds no second clock gate, only a work gate.
//!
//! Tests are named by the requirement they are evidence for (C-0xx / FR-0xx / NFR-0xx).
//! Every negative or no-write claim carries a **positive control** — a fixture or a
//! second call that *does* move the measured thing — so a test that cannot fail is
//! impossible to miss.

use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde_json::{Value, json};
use tempfile::TempDir;
use tix::app::{App, Mode};
use tix::capacity::calculate::{CapacityCalculation, CapacityScope};
use tix::capacity::scope::IssueSnapshot;
use tix::capacity::{CapacityScopeKind, schedule_index};
use tix::config::Config;
use tix::model::Issue;
use tix::ui::schedule::ScheduleTab;

// ---------------------------------------------------------------------------
// The shared fixture
// ---------------------------------------------------------------------------

/// The board every fixture runs under: two estimate units (`d` = 1, `w` = 5, the
/// conversion ratio this mission's C-004 evidence turns on), one team, and—crucially—a
/// `category_map` that makes `done` the *completed* column while leaving `todo`
/// unstarted, so completion comes from the shared #183 category service and not from a
/// status string this target happens to write (C-002).
const BOARD: &str = "[kanban.default]
columns = [\"todo\", \"done\"]
done_column = \"done\"
category_map = { todo = \"unstarted\", done = \"completed\" }

[kanban.default.wip.units]
d = 1
w = 5

[teams.Platform]
members = [\"ada\"]
";

/// One weekly schedule: its first instance is `sprint:000001`, the only cycle kind a
/// close captures a snapshot for.
const SCHEDULE: &str = "
[cycle_schedules.sprint]
name = \"Weekly sprint\"
cadence = { kind = \"weekly\" }
duration = { count = 1, unit = \"weeks\" }
start_date = \"2026-01-05\"
timezone = \"UTC\"
look_ahead = 1
";

/// The generated instance's own name — what an issue's `cycles` field must hold.
const INSTANCE_NAME: &str = "Weekly sprint 2026-01-05 000001";

/// The generated instance's stable id — the other spelling of the same scope (C-003).
const INSTANCE_ID: &str = "sprint:000001";

fn tix_bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_tix"))
}

/// A hand-written `[capacity.<id>]` section naming `reference` in `unit` — the fixture's
/// way to configure a ceiling without running `tix capacity set` (which walks a read seam).
fn capacity_entry(reference: &str, value: i64, unit: &str) -> String {
    format!(
        "\n[capacity.cycle-sprint-000001]\ncycle = \"{reference}\"\ncapacity = {value}\n\
         unit = \"{unit}\"\n"
    )
}

/// A temporary project: `tix.toml` (an absolute `issues_dir`, so the CLI, the TUI and MCP
/// never disagree about which tree they read) plus room for a schedule and a capacity
/// section.
struct Project {
    dir: TempDir,
}

impl Project {
    /// A project with `BOARD`, `SCHEDULE` and whichever `[capacity]` entries `capacity`
    /// spells (an empty string for none).
    fn new(capacity: &str) -> Self {
        Self::with_board_and_capacity(BOARD, capacity)
    }

    /// A project on a **different** board — used by the status-category control, whose
    /// whole point is a board where the completing column is not the `done` column.
    fn with_board(board: &str) -> Self {
        Self::with_board_and_capacity(board, "")
    }

    fn with_board_and_capacity(board: &str, capacity: &str) -> Self {
        let dir = TempDir::new().unwrap();
        let issues = dir.path().join("issues");
        fs::create_dir_all(&issues).unwrap();
        fs::write(
            dir.path().join("tix.toml"),
            format!("issues_dir = {issues:?}\n{board}{SCHEDULE}{capacity}"),
        )
        .unwrap();
        Self { dir }
    }

    fn root(&self) -> &Path {
        self.dir.path()
    }

    fn config(&self) -> Config {
        Config::load(self.root()).expect("the fixture loads")
    }

    /// A fresh in-process `App` over the fixture — the same read `tix`'s own TUI makes.
    fn app(&self) -> App {
        App::new(&self.config()).expect("the TUI opens")
    }

    /// Generate the schedule's first instance through the CLI's own write path and return
    /// its stable id, so every surface starts from the same record bytes.
    fn generate(&self) -> String {
        let _ = stdout(
            self.root(),
            &["cycle", "schedule", "generate", "sprint", "--confirm"],
        );
        INSTANCE_ID.to_string()
    }

    /// Configure the instance's ceiling through `tix capacity set` (the real write path).
    fn set(&self, id: &str, value: i64, unit: &str) {
        let _ = stdout(
            self.root(),
            &[
                "capacity",
                "set",
                "--scope",
                "cycle",
                "--id",
                id,
                "--value",
                &value.to_string(),
                "--unit",
                unit,
            ],
        );
    }

    /// Configure a team scope's ceiling (used as the "a write changes the tree" control).
    fn set_team(&self, id: &str, value: i64, unit: &str) {
        let _ = stdout(
            self.root(),
            &[
                "capacity",
                "set",
                "--scope",
                "team",
                "--id",
                id,
                "--value",
                &value.to_string(),
                "--unit",
                unit,
            ],
        );
    }

    /// One issue in the generated instance, assigned to `ada`.
    fn create(&self, title: &str, estimate: &str, status: &str) {
        let _ = stdout(
            self.root(),
            &[
                "create",
                "--title",
                title,
                "--estimate",
                estimate,
                "--cycles",
                INSTANCE_NAME,
                "--assignee",
                "ada",
                "--status",
                status,
            ],
        );
    }

    /// A fully-assembled fixture written **without running any `tix` command**: `tix.toml`
    /// (the capacity section already in it), the generated instance's record through the
    /// store's own writer, and room for the issues.
    ///
    /// Required wherever the baseline must precede **every** read seam. `tix capacity set`
    /// and `tix create` themselves walk `schedule_index` (`src/commands/capacity.rs`), so a
    /// fixture built by running them already carries whatever that seam writes — and a
    /// write-on-read there would then be invisible to a fingerprint taken afterwards. This
    /// constructor runs no `tix` command at all, so the only way a read seam's output can
    /// appear in the tree is *after* the baseline.
    fn assembled(capacity: &str) -> Self {
        let project = Self::new(capacity);
        let record = tix::cycle_store::CycleRecord {
            name: INSTANCE_NAME.to_string(),
            start_date: Some("2026-01-05".to_string()),
            due_date: Some("2026-01-12".to_string()),
            schedule_id: Some("sprint".to_string()),
            sequence: Some(1),
            state: Some("active".to_string()),
            ..tix::cycle_store::CycleRecord::default()
        };
        tix::cycle_store::CycleStore::new(project.root())
            .save_record(&record, Some("The weekly instance.\n"))
            .expect("the generated cycle is stored");
        project
    }

    /// One issue file written directly, in the legacy flat layout — the fixture's way to
    /// place an issue without running `tix create` (which resolves cycles, i.e. walks a
    /// read seam).
    fn write_issue(&self, number: u32, status: &str, extra: &str) {
        fs::write(
            self.root().join(format!("issues/2026-01-01-issue-{number}.md")),
            format!(
                "---\nnumber: {number}\ntitle: \"Issue {number}\"\nstatus: \"{status}\"\n\
                 labels: []\npriority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n\
                 {extra}---\n\nBody.\n"
            ),
        )
        .unwrap();
    }

    fn close(&self, id: &str) {
        let _ = stdout(
            self.root(),
            &[
                "cycle",
                "schedule",
                "close",
                "sprint",
                "--cycle",
                id,
                "--reason",
                "iteration complete",
                "--confirm",
            ],
        );
    }

    fn reopen(&self, id: &str) {
        let _ = stdout(
            self.root(),
            &[
                "cycle",
                "schedule",
                "reopen",
                "sprint",
                "--cycle",
                id,
                "--reason",
                "correction",
                "--confirm",
            ],
        );
    }

    /// The path of the instance's immutable close snapshot.
    fn snapshot_path(&self) -> PathBuf {
        self.root().join("docs/cycle_snapshots/sprint.000001.md")
    }

    fn snapshot_bytes(&self) -> Vec<u8> {
        fs::read(self.snapshot_path()).expect("the close wrote its snapshot")
    }
}

// ---------------------------------------------------------------------------
// CLI helpers
// ---------------------------------------------------------------------------

/// Run `tix <args>` in `dir`: `(exit_code, stdout, stderr)` without asserting a status.
fn run(dir: &Path, args: &[&str]) -> (i32, String, String) {
    let out = Command::new(tix_bin())
        .args(args)
        .current_dir(dir)
        .output()
        .unwrap_or_else(|error| panic!("spawn tix {args:?}: {error}"));
    (
        out.status.code().unwrap_or(-1),
        String::from_utf8(out.stdout).unwrap(),
        String::from_utf8(out.stderr).unwrap(),
    )
}

/// Run `tix <args>` asserting success, returning `stdout`.
fn stdout(dir: &Path, args: &[&str]) -> String {
    let (code, out, err) = run(dir, args);
    assert_eq!(code, 0, "tix {args:?} failed: {err}");
    out
}

/// `tix capacity calculate ...` for the fixture's instance, `key: value` per line.
fn calculate_cli(project: &Project, args: &[&str]) -> BTreeMap<String, String> {
    fields(&stdout(project.root(), args))
}

/// The `key: value` lines of a capacity text block, as a map.
fn fields(text: &str) -> BTreeMap<String, String> {
    text.lines()
        .filter_map(|line| line.split_once(": "))
        .map(|(key, value)| (key.to_string(), value.to_string()))
        .collect()
}

/// The CLI's own `category calculate` map for the instance scope (no `--warnings`).
fn cli_calculation(project: &Project, id: &str) -> BTreeMap<String, String> {
    calculate_cli(
        project,
        &["capacity", "calculate", "--scope", "cycle", "--id", id],
    )
}

/// One numeric field of a CLI map, parsed.
fn cli_number(map: &BTreeMap<String, String>, key: &str) -> u64 {
    map.get(key)
        .unwrap_or_else(|| panic!("the CLI printed `{key}`: {map:?}"))
        .parse()
        .unwrap_or_else(|_| panic!("the CLI's `{key}` is a number: {map:?}"))
}

/// The CLI's `utilization` percentage, with its `%` stripped.
fn cli_percent(map: &BTreeMap<String, String>, key: &str) -> u32 {
    map.get(key)
        .unwrap_or_else(|| panic!("the CLI printed `{key}`: {map:?}"))
        .trim_end_matches('%')
        .parse()
        .unwrap_or_else(|_| panic!("the CLI's `{key}` is a percentage: {map:?}"))
}

// ---------------------------------------------------------------------------
// TUI helpers
// ---------------------------------------------------------------------------

fn press(code: KeyCode) -> KeyEvent {
    KeyEvent::new(code, KeyModifiers::NONE)
}

/// Open the `F8` Schedule page and step to its **Capacity** tab, the way a reader does.
fn open_capacity_tab(app: &mut App) {
    let _ = app.handle_key(press(KeyCode::F(8))).unwrap();
    assert!(matches!(app.mode, Mode::Schedule), "F8 opens the page");
    let _ = app.handle_key(press(KeyCode::Tab)).unwrap();
    let _ = app.handle_key(press(KeyCode::Tab)).unwrap();
    assert_eq!(
        app.schedule_state().tab,
        ScheduleTab::Capacity,
        "`Tab` twice reaches the Capacity tab"
    );
}

/// The selected scope's detail fields, as the CLI's own map shape.
fn tui_fields(app: &App, selected: usize) -> BTreeMap<String, String> {
    app.capacity_detail(selected)
        .unwrap_or_else(|| panic!("scope {selected} has a detail pane"))
        .fields
        .iter()
        .map(|(key, value)| (key.clone(), value.clone()))
        .collect()
}

// ---------------------------------------------------------------------------
// Fingerprint helper — the no-write control
// ---------------------------------------------------------------------------

/// Every file under `root`, by relative path and exact bytes. A read-only claim is a map
/// equal to the one taken before the read; a *write* claim is a map that differs.
fn tree(root: &Path) -> BTreeMap<String, Vec<u8>> {
    let mut out = BTreeMap::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(current) = stack.pop() {
        for entry in fs::read_dir(&current).expect("the directory reads") {
            let path = entry.expect("the entry reads").path();
            if path.is_dir() {
                stack.push(path);
            } else {
                let name = path
                    .strip_prefix(root)
                    .expect("under the root")
                    .to_string_lossy()
                    .into_owned();
                out.insert(name, fs::read(&path).expect("the file reads"));
            }
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Portable helper
// ---------------------------------------------------------------------------

/// The capacity document the CLI emits, parsed as JSON.
fn export(project: &Project, extra: &[&str]) -> Value {
    let mut args = vec!["export", "--target", "capacity"];
    args.extend_from_slice(extra);
    serde_json::from_str(&stdout(project.root(), &args))
        .expect("the export writes one JSON document")
}

/// One numeric field of a portable calculation, asserted equal to the CLI's own line.
fn portable_equals_cli(
    document: &Value,
    calculation: &Value,
    field: &str,
    cli: &str,
    expected: u64,
) {
    assert_eq!(
        calculation[field].as_u64(),
        Some(expected),
        "`{field}` must be the CLI's `{cli}` ({expected}): {document}"
    );
}

/// The document's findings of one kind.
fn portable_findings<'a>(document: &'a Value, kind: &str) -> Vec<&'a Value> {
    document["diagnostics"]
        .as_array()
        .expect("diagnostics is an array")
        .iter()
        .filter(|finding| finding["kind"] == json!(kind))
        .collect()
}

// ---------------------------------------------------------------------------
// MCP session harness (a trimmed copy of `tests/mcp.rs`'s; a test target is its own
// crate, so the harness cannot be shared — and this target needs only the request/response
// shape, not the stderr-drain purity cases that file owns).
// ---------------------------------------------------------------------------

struct Reader {
    thread: std::thread::JoinHandle<()>,
}

fn spawn_reader(
    stdout: std::process::ChildStdout,
    tx: mpsc::Sender<String>,
    sink: Arc<Mutex<Vec<String>>>,
) -> Reader {
    let thread = std::thread::spawn(move || {
        let mut reader = BufReader::new(stdout);
        loop {
            let mut line = String::new();
            match reader.read_line(&mut line) {
                Ok(0) | Err(_) => break,
                Ok(_) => {
                    let trimmed = line
                        .trim_end_matches('\n')
                        .trim_end_matches('\r')
                        .to_string();
                    sink.lock().unwrap().push(trimmed.clone());
                    if tx.send(trimmed).is_err() {
                        break;
                    }
                }
            }
        }
    });
    Reader { thread }
}

struct Session {
    child: Child,
    stdin: Option<ChildStdin>,
    rx: mpsc::Receiver<String>,
    all_lines: Arc<Mutex<Vec<String>>>,
    reader: Option<Reader>,
    id: Cell<u32>,
}

impl Session {
    fn start(repo: &Path) -> Self {
        let mut child = Command::new(tix_bin())
            .arg("mcp")
            .current_dir(repo)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("spawn tix mcp");
        let stdin = child.stdin.take().expect("stdin piped");
        let stdout = child.stdout.take().expect("stdout piped");
        let (tx, rx) = mpsc::channel();
        let sink = Arc::new(Mutex::new(Vec::new()));
        let reader = spawn_reader(stdout, tx, Arc::clone(&sink));
        Session {
            child,
            stdin: Some(stdin),
            rx,
            all_lines: sink,
            reader: Some(reader),
            id: Cell::new(1),
        }
    }

    fn write_line(&mut self, line: &str) {
        writeln!(self.stdin.as_mut().unwrap(), "{line}").unwrap();
        self.stdin.as_mut().unwrap().flush().unwrap();
    }

    fn next_id(&self) -> u32 {
        let id = self.id.get();
        self.id.set(id + 1);
        id
    }

    fn send_request(&mut self, method: &str, params: &Value) {
        let id = self.next_id();
        let msg = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params});
        self.write_line(&serde_json::to_string(&msg).unwrap());
    }

    fn recv_json(&self) -> Value {
        let line = self
            .rx
            .recv_timeout(Duration::from_secs(10))
            .expect("no response within 10 s");
        serde_json::from_str(&line).unwrap_or_else(|e| panic!("invalid JSON: {e}\nraw: {line}"))
    }

    fn handshake(&mut self) {
        self.send_request(
            "initialize",
            &json!({"protocolVersion": "2025-06-18", "capabilities": {}}),
        );
        let resp = self.recv_json();
        assert_eq!(resp["result"]["serverInfo"]["name"], "tix");
        self.write_line(
            &serde_json::to_string(
                &json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
            )
            .unwrap(),
        );
        assert!(
            self.rx.recv_timeout(Duration::from_millis(300)).is_err(),
            "the initialized notification expects no response"
        );
    }

    fn call_tool(&mut self, name: &str, args: &Value) -> Value {
        let id = self.next_id();
        let msg = json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": "tools/call",
            "params": {"name": name, "arguments": args}
        });
        self.write_line(&serde_json::to_string(&msg).unwrap());
        let resp = self.recv_json();
        resp.get("result").or(resp.get("error")).cloned().unwrap()
    }

    fn close(mut self) -> (std::process::ExitStatus, Vec<String>) {
        drop(self.stdin.take());
        let status = self.child.wait().expect("wait");
        self.reader
            .take()
            .expect("reader present")
            .thread
            .join()
            .ok();
        let lines = std::mem::take(self.all_lines.lock().unwrap().as_mut());
        (status, lines)
    }
}

/// Every raw stdout line is valid JSON — the stream stays machine-readable.
fn assert_pure_stdout(lines: &[String]) {
    for (i, line) in lines.iter().enumerate() {
        assert!(
            serde_json::from_str::<Value>(line).is_ok(),
            "non-JSON on stdout line {i}: {line:?}"
        );
    }
}

fn tool_result(value: &Value) -> &Value {
    value.get("result").or(value.get("error")).unwrap_or(value)
}

fn tool_text(value: &Value) -> &str {
    tool_result(value)["content"][0]["text"]
        .as_str()
        .expect("a tool result carries text")
}

fn tool_structured(value: &Value) -> &Value {
    &tool_result(value)["structuredContent"]
}

/// Open a session and handshake, returning it ready to call tools.
fn open_session(project: &Project) -> Session {
    let mut session = Session::start(project.root());
    session.handshake();
    session
}

// ===========================================================================
// T045 — units, formulas and the close snapshot (C-004, C-005, FR-002, FR-005)
// ===========================================================================

/// C-005 / FR-002: for one fixture, committed/completed/remaining/overflow/utilization
/// are one set of numbers, and every surface prints that set — the CLI's fields, the
/// TUI's detail pane key for key, the board's compact cell, the MCP structure and text,
/// and the portable document's calculation.
///
/// The positive control at the end runs the whole comparison over a *different* fixture
/// (a single `done` issue), so none of the equalities can be satisfied by a constant.
#[test]
fn c_005_fr_002_same_unit_values_are_one_answer_across_cli_tui_mcp_and_portable() {
    let project = Project::new("");
    let id = project.generate();
    project.set(&id, 10, "d");
    project.create("one", "6d", "todo");
    project.create("two", "2d", "done");

    // --- The CLI: the shared DTO's own fields.
    let cli = cli_calculation(&project, &id);
    assert_eq!(cli.get("scope").map(String::as_str), Some("cycle"));
    assert_eq!(cli.get("reference").map(String::as_str), Some(INSTANCE_ID));
    assert_eq!(cli.get("display").map(String::as_str), Some(INSTANCE_NAME));
    assert_eq!(cli.get("state").map(String::as_str), Some("configured"));
    assert_eq!(cli.get("capacity").map(String::as_str), Some("10"));
    assert_eq!(cli.get("unit").map(String::as_str), Some("d"));
    assert_eq!(cli.get("committed").map(String::as_str), Some("8"));
    assert_eq!(cli.get("completed").map(String::as_str), Some("2"));
    assert_eq!(cli.get("remaining").map(String::as_str), Some("6"));
    assert_eq!(cli.get("overflow").map(String::as_str), Some("0"));
    assert_eq!(cli.get("utilization").map(String::as_str), Some("80%"));
    assert_eq!(cli.get("counted_issues").map(String::as_str), Some("2"));
    assert_eq!(cli.get("uncounted_issues").map(String::as_str), Some("0"));
    assert_eq!(cli.get("unestimated_issues").map(String::as_str), Some("0"));

    // --- The TUI: the Capacity tab's detail is the CLI's fields, key for key.
    let mut app = project.app();
    open_capacity_tab(&mut app);
    assert_eq!(
        tui_fields(&app, 0),
        cli,
        "the page prints exactly the CLI's fields, no more and no fewer"
    );
    // …and the board's compact cell is the same numbers on one line, under both
    // spellings of the scope (C-003).
    let summaries = app.capacity_summaries().expect("the board read ran");
    for key in [INSTANCE_ID, INSTANCE_NAME] {
        assert_eq!(
            summaries.get(key).map(String::as_str),
            Some("8/10 d · 80%"),
            "the board cell for `{key}` is the shared numbers"
        );
    }

    // --- MCP: the text is the CLI's stdout and the structure carries the same numbers.
    let mut session = open_session(&project);
    let calculated = session.call_tool(
        "capacity_calculate",
        &json!({"scope": "cycle", "id": INSTANCE_ID}),
    );
    assert_eq!(
        tool_text(&calculated),
        stdout(
            project.root(),
            &[
                "capacity",
                "calculate",
                "--scope",
                "cycle",
                "--id",
                INSTANCE_ID
            ]
        ),
        "MCP words the calculation as the CLI does"
    );
    let mcp = tool_structured(&calculated);
    assert_eq!(mcp["state"], json!("configured"));
    assert_eq!(mcp["scope"]["display"], json!(INSTANCE_NAME));
    assert_eq!(mcp["unit"], json!("d"));
    for (field, key) in [
        ("capacity", "capacity"),
        ("committed", "committed"),
        ("completed", "completed"),
        ("remaining", "remaining"),
        ("overflow", "overflow"),
        ("counted_issues", "counted_issues"),
        ("uncounted_issues", "uncounted_issues"),
        ("unestimated_issues", "unestimated_issues"),
    ] {
        assert_eq!(
            mcp[field].as_u64(),
            Some(cli_number(&cli, key)),
            "MCP `{field}` is the CLI's `{key}`"
        );
    }
    assert_eq!(
        mcp["utilization"].as_u64(),
        Some(u64::from(cli_percent(&cli, "utilization")))
    );
    let (status, lines) = session.close();
    assert!(status.success());
    assert_pure_stdout(&lines);

    // --- Portable: the document's one scope is the same calculation.
    let document = export(&project, &[]);
    assert_eq!(document["format"], json!("tix-capacity"));
    assert_eq!(document["version"], json!(1));
    let portable = &document["scopes"][0]["calculation"];
    assert_eq!(portable["state"], json!("configured"));
    assert_eq!(portable["unit"], json!("d"));
    assert_eq!(portable["scope"]["reference"], json!(INSTANCE_ID));
    assert_eq!(portable["scope"]["display"], json!(INSTANCE_NAME));
    for (field, key) in [
        ("capacity", "capacity"),
        ("committed", "committed"),
        ("completed", "completed"),
        ("remaining", "remaining"),
        ("overflow", "overflow"),
        ("counted_issues", "counted_issues"),
        ("uncounted_issues", "uncounted_issues"),
        ("unestimated_issues", "unestimated_issues"),
    ] {
        portable_equals_cli(&document, portable, field, key, cli_number(&cli, key));
    }
    assert_eq!(
        portable["utilization"].as_u64(),
        Some(u64::from(cli_percent(&cli, "utilization")))
    );

    // --- Positive control: a different fixture gives different numbers on every surface,
    // so nothing above is a value a surface could have printed without reading the data.
    let control = Project::new("");
    let control_id = control.generate();
    control.set(&control_id, 10, "d");
    control.create("only", "6d", "done");
    let control_cli = cli_calculation(&control, &control_id);
    assert_eq!(control_cli.get("committed").map(String::as_str), Some("6"));
    assert_eq!(control_cli.get("completed").map(String::as_str), Some("6"));
    assert_ne!(
        control_cli, cli,
        "the control fixture is a different answer"
    );
    let mut control_app = control.app();
    open_capacity_tab(&mut control_app);
    assert_eq!(
        tui_fields(&control_app, 0),
        control_cli,
        "the parity assertion tracks the fixture, not a constant"
    );
    let control_document = export(&control, &[]);
    assert_eq!(
        control_document["scopes"][0]["calculation"]["committed"].as_u64(),
        Some(6)
    );
}

/// C-004 / FR-002: a value counts only through an **explicit** conversion — the board's
/// declared ratio (`1w` = `5d` here) — never as an implicit identity. The control asserts
/// the counted value is the ratio's product and not the raw magnitude.
#[test]
fn c_004_explicit_conversion_uses_the_declared_ratio_and_is_never_implicit() {
    let project = Project::new("");
    let id = project.generate();
    project.set(&id, 10, "d");
    project.create("week", "1w", "todo");

    let cli = cli_calculation(&project, &id);
    assert_eq!(
        cli.get("committed").map(String::as_str),
        Some("5"),
        "{cli:?}"
    );
    assert_eq!(cli.get("counted_issues").map(String::as_str), Some("1"));
    assert_eq!(cli.get("uncounted_issues").map(String::as_str), Some("0"));
    assert_eq!(cli.get("unestimated_issues").map(String::as_str), Some("0"));
    assert_eq!(cli.get("utilization").map(String::as_str), Some("50%"));
    // The control: an implicit identity (`1w` counted as `1`) would print `committed: 1`.
    assert_ne!(cli.get("committed").map(String::as_str), Some("1"));

    // Every surface converts once, through the same table.
    let mut app = project.app();
    open_capacity_tab(&mut app);
    assert_eq!(tui_fields(&app, 0), cli);

    let mut session = open_session(&project);
    let mcp = session.call_tool(
        "capacity_calculate",
        &json!({"scope": "cycle", "id": INSTANCE_ID}),
    );
    assert_eq!(tool_structured(&mcp)["committed"].as_u64(), Some(5));
    assert_eq!(tool_structured(&mcp)["unit"], json!("d"));
    let (status, _) = session.close();
    assert!(status.success());

    let document = export(&project, &[]);
    assert_eq!(
        document["scopes"][0]["calculation"]["committed"].as_u64(),
        Some(5),
        "the portable document converts through the same ratio: {document}"
    );
}

/// C-005 / FR-002: an unestimated issue stays **visible** and contributes nothing. The
/// control is the two counts telling different stories — a design that silently made the
/// unestimated issue a zero would print `unestimated_issues: 0` and `committed: 5`.
#[test]
fn c_005_fr_002_an_unestimated_issue_is_visible_and_contributes_nothing() {
    let project = Project::new("");
    let id = project.generate();
    project.set(&id, 10, "d");
    project.create("estimated", "4d", "todo");
    project.create("no estimate", "", "todo");

    let cli = cli_calculation(&project, &id);
    assert_eq!(
        cli.get("committed").map(String::as_str),
        Some("4"),
        "{cli:?}"
    );
    assert_eq!(cli.get("counted_issues").map(String::as_str), Some("1"));
    assert_eq!(cli.get("unestimated_issues").map(String::as_str), Some("1"));
    assert_eq!(cli.get("uncounted_issues").map(String::as_str), Some("0"));
    assert_eq!(cli.get("utilization").map(String::as_str), Some("40%"));

    let mut app = project.app();
    open_capacity_tab(&mut app);
    assert_eq!(tui_fields(&app, 0), cli);

    let mut session = open_session(&project);
    let mcp = session.call_tool(
        "capacity_calculate",
        &json!({"scope": "cycle", "id": INSTANCE_ID}),
    );
    let structured = tool_structured(&mcp);
    assert_eq!(structured["committed"].as_u64(), Some(4));
    assert_eq!(structured["unestimated_issues"].as_u64(), Some(1));
    assert_eq!(structured["uncounted_issues"].as_u64(), Some(0));
    let (status, _) = session.close();
    assert!(status.success());

    let document = export(&project, &[]);
    let portable = &document["scopes"][0]["calculation"];
    assert_eq!(portable["committed"].as_u64(), Some(4));
    assert_eq!(portable["unestimated_issues"].as_u64(), Some(1));
}

/// C-004 / FR-002: an estimate in a unit the board never declared is a **diagnostic**,
/// never a silent zero — and the countable work beside it is still counted (the control
/// that the zero is not the sum being discarded entirely).
#[test]
fn c_004_fr_002_an_undeclared_unit_is_reported_and_never_a_silent_zero() {
    let project = Project::new("");
    let id = project.generate();
    project.set(&id, 10, "d");
    project.create("countable", "6d", "todo");
    // `h` is well-formed and declared by no board: the one case C-004 names.
    project.create("hours", "3h", "todo");

    let (out, err) = {
        let (code, out, err) = run(
            project.root(),
            &[
                "capacity",
                "calculate",
                "--scope",
                "cycle",
                "--id",
                INSTANCE_ID,
            ],
        );
        assert_eq!(code, 0, "{err}");
        (out, err)
    };
    let cli = fields(&out);
    assert_eq!(cli.get("state").map(String::as_str), Some("configured"));
    assert_eq!(cli.get("committed").map(String::as_str), Some("6"), "{out}");
    assert_eq!(cli.get("counted_issues").map(String::as_str), Some("1"));
    assert_eq!(cli.get("uncounted_issues").map(String::as_str), Some("1"));
    // The finding names the unit, the offending issue and a remedy, and it is always
    // rendered (an estimate finding is not the opt-in overflow half).
    assert!(err.contains("missing_conversion"), "{err}");
    assert!(err.contains("unit: d"), "{err}");
    assert!(err.contains("issues: #2"), "{err}");
    assert!(err.contains("help:"), "the finding carries a remedy: {err}");

    // The TUI's detail pane renders the same finding, remedy and all.
    let mut app = project.app();
    open_capacity_tab(&mut app);
    assert_eq!(tui_fields(&app, 0), cli);
    let detail = app.capacity_detail(0).expect("the scope has a detail");
    let diagnostics = detail.diagnostics.join("\n");
    assert!(diagnostics.contains("missing_conversion"), "{diagnostics}");
    assert!(diagnostics.contains("help:"), "{diagnostics}");
    assert!(app.capacity_rows()[0].warned, "the row carries the finding");

    // MCP and the portable document carry the same finding with the same context.
    let mut session = open_session(&project);
    let calculated = session.call_tool(
        "capacity_calculate",
        &json!({"scope": "cycle", "id": INSTANCE_ID}),
    );
    assert_eq!(tool_structured(&calculated)["committed"].as_u64(), Some(6));
    let finding = tool_structured(&calculated)["diagnostics"]
        .as_array()
        .expect("diagnostics")
        .iter()
        .find(|finding| finding["kind"] == json!("missing_conversion"))
        .expect("a missing_conversion finding");
    assert_eq!(finding["unit"], json!("d"));
    assert_eq!(finding["issues"], json!([2]));
    assert!(
        finding["remedy"]
            .as_str()
            .is_some_and(|remedy| !remedy.is_empty()),
        "the remedy travels: {finding}"
    );
    let (status, _) = session.close();
    assert!(status.success());

    let document = export(&project, &[]);
    let portable = portable_findings(&document["scopes"][0]["calculation"], "missing_conversion");
    assert_eq!(portable.len(), 1, "{document}");
    assert_eq!(portable[0]["unit"], json!("d"));
    assert_eq!(portable[0]["issues"], json!([2]));

    // The control: the countable issue is counted, so `committed: 6` is not the whole
    // scope being dropped when one estimate cannot be read.
    assert_ne!(cli.get("committed").map(String::as_str), Some("0"));
}

/// C-003 / C-004: a scope with no ceiling in force is an **explicit unconfigured state**,
/// never a zero ceiling, and a reference that resolves nowhere is a diagnostic — the same
/// answer on the CLI, the TUI's unconfigured row, MCP and the portable document.
#[test]
fn c_003_c_004_an_unconfigured_scope_is_explicit_and_never_a_zero() {
    let project = Project::new("");
    let id = project.generate();
    // A ceiling that is present but **not in force**: disabled, it keeps the scope (and
    // its unit) for later without changing today's calculation.
    let _ = stdout(
        project.root(),
        &[
            "capacity",
            "set",
            "--scope",
            "cycle",
            "--id",
            &id,
            "--value",
            "10",
            "--unit",
            "d",
            "--disabled",
        ],
    );
    project.create("work", "6d", "todo");

    // CLI: the disabled ceiling leaves the scope unconfigured and every value `-`.
    let cli = cli_calculation(&project, &id);
    assert_eq!(cli.get("state").map(String::as_str), Some("unconfigured"));
    for absent in [
        "capacity",
        "unit",
        "committed",
        "completed",
        "remaining",
        "overflow",
        "utilization",
        "counted_issues",
        "uncounted_issues",
        "unestimated_issues",
    ] {
        assert_eq!(
            cli.get(absent).map(String::as_str),
            Some("-"),
            "`{absent}`: {cli:?}"
        );
    }

    // TUI: the disabled entry is listed as its own unconfigured scope — same fields.
    let mut app = project.app();
    open_capacity_tab(&mut app);
    assert_eq!(tui_fields(&app, 0), cli, "the page agrees with the CLI");
    assert!(
        app.capacity_rows()[0].subtitle.contains("unconfigured"),
        "the row states the explicit unconfigured state: {}",
        app.capacity_rows()[0].subtitle
    );
    assert!(
        !app.capacity_nothing_committed(),
        "no answer is not the statement that the answer is zero"
    );

    // MCP: unconfigured is `null` everywhere, and the value is never `0`.
    let mut session = open_session(&project);
    let disabled = session.call_tool(
        "capacity_calculate",
        &json!({"scope": "cycle", "id": INSTANCE_ID}),
    );
    let absent = tool_structured(&disabled);
    assert_eq!(absent["state"], json!("unconfigured"));
    for key in [
        "capacity",
        "unit",
        "committed",
        "completed",
        "remaining",
        "overflow",
        "utilization",
        "counted_issues",
        "uncounted_issues",
        "unestimated_issues",
    ] {
        assert_eq!(absent[key], json!(null), "`{key}` must be null, never 0");
    }
    assert!(
        tool_text(&disabled).contains("capacity: -"),
        "{}",
        tool_text(&disabled)
    );

    // A reference nothing resolves to is its own diagnostic, not a guess.
    let unknown = session.call_tool(
        "capacity_calculate",
        &json!({"scope": "cycle", "id": "Ghost"}),
    );
    let unknown_structured = tool_structured(&unknown);
    assert_eq!(unknown_structured["state"], json!("unconfigured"));
    let finding = unknown_structured["diagnostics"]
        .as_array()
        .expect("diagnostics")
        .iter()
        .find(|finding| finding["kind"] == json!("unknown_scope"))
        .expect("an unknown_scope finding");
    assert!(finding["remedy"].as_str().is_some(), "{finding}");
    let (status, _) = session.close();
    assert!(status.success());

    // The control: the very same scope with the ceiling in force is `configured` with
    // real numbers, so `unconfigured` is a state the surface derived, not a default.
    let enabled = Project::new("");
    let enabled_id = enabled.generate();
    enabled.set(&enabled_id, 10, "d");
    enabled.create("work", "6d", "todo");
    let enabled_cli = cli_calculation(&enabled, &enabled_id);
    assert_eq!(
        enabled_cli.get("state").map(String::as_str),
        Some("configured")
    );
    assert_eq!(enabled_cli.get("committed").map(String::as_str), Some("6"));
    let mut enabled_app = enabled.app();
    open_capacity_tab(&mut enabled_app);
    assert_eq!(tui_fields(&enabled_app, 0), enabled_cli);
}

/// FR-005 / C-008: an explicit close captures the **same calculation** as immutable
/// evidence, and the CLI readback, the MCP tool and the portable document all report that
/// one snapshot identity and those one numbers.
#[test]
fn fr_005_c_008_a_close_captures_the_shared_calculation_as_immutable_evidence() {
    let project = Project::new("");
    let id = project.generate();
    project.set(&id, 10, "d");
    project.create("one", "6d", "todo");
    project.create("two", "2d", "done");

    // The live calculation, immediately before the close.
    let live = cli_calculation(&project, &id);
    // Nothing is closed yet, so the readback refuses rather than inventing evidence — the
    // control that a later "evidence: present" is a fact about a close, not the command's
    // default output.
    let (code, _out, missing) = run(project.root(), &["capacity", "snapshot", &id]);
    assert_ne!(code, 0, "no snapshot exists yet");
    assert!(missing.contains("has no snapshot"), "{missing}");

    project.close(&id);

    let readback = stdout(project.root(), &["capacity", "snapshot", &id]);
    assert!(readback.contains("evidence: present"), "{readback}");
    let evidence = fields(&readback);
    // The evidence is the live calculation: the close captured the shared DTO.
    for key in [
        "state",
        "capacity",
        "unit",
        "committed",
        "completed",
        "remaining",
        "overflow",
        "utilization",
        "counted_issues",
        "uncounted_issues",
        "unestimated_issues",
    ] {
        assert_eq!(
            evidence.get(key),
            live.get(key),
            "the evidence's `{key}` is the live calculation's"
        );
    }
    assert_eq!(evidence.get("committed").map(String::as_str), Some("8"));
    assert_eq!(evidence.get("utilization").map(String::as_str), Some("80%"));
    let snapshot_id = evidence.get("snapshot_id").cloned().expect("a snapshot id");

    // MCP: the tool's text is the CLI's readback and its structure carries the identity.
    let mut session = open_session(&project);
    let tool = session.call_tool("capacity_snapshot", &json!({"cycle": INSTANCE_ID}));
    assert_eq!(
        tool_text(&tool),
        readback,
        "MCP reads the snapshot as the CLI does"
    );
    let structured = tool_structured(&tool);
    assert_eq!(structured["evidence"], json!("present"));
    assert_eq!(structured["capacity"]["snapshot_id"], json!(snapshot_id));
    assert_eq!(structured["capacity"]["committed"].as_u64(), Some(8));
    let history = structured["history"].as_array().expect("history");
    assert_eq!(history.len(), 1, "{structured}");
    assert_eq!(history[0]["kind"], json!("cycle_closed"));
    let (status, _) = session.close();
    assert!(status.success());

    // Portable: the document carries the same immutable evidence and the same History.
    let document = export(&project, &[]);
    let snapshots = document["snapshots"].as_array().expect("snapshots");
    assert_eq!(snapshots.len(), 1, "{document}");
    assert_eq!(snapshots[0]["snapshot_id"], json!(snapshot_id));
    assert_eq!(snapshots[0]["cycle_id"], json!(INSTANCE_ID));
    assert_eq!(snapshots[0]["committed"].as_u64(), Some(8));
    assert_eq!(snapshots[0]["utilization"].as_u64(), Some(80));
    let history = document["history"].as_array().expect("history");
    assert_eq!(history.len(), 1);
    assert_eq!(history[0]["kind"], json!("cycle_closed"));

    // A read never rewrites the evidence: a second readback and a second export carry the
    // identical snapshot bytes.
    let bytes = project.snapshot_bytes();
    let _ = stdout(project.root(), &["capacity", "snapshot", &id]);
    let _ = export(&project, &[]);
    assert_eq!(
        project.snapshot_bytes(),
        bytes,
        "the evidence is immutable under reads"
    );
}

/// C-002: `completed` comes from the shared status-category service (#183), not from a
/// status string or the board's `done_column`. The fixture maps `done` to `active` and
/// `shipped` to `completed`, so a surface that compared `status == done_column` (or
/// `status == "done"`) would count exactly the wrong issue — and every surface must
/// agree with the category service instead.
///
/// The control runs the mirror board (`done` is `completed`), so `completed: 2` above is
/// the category service's answer for this board rather than a constant any surface could
/// print.
#[test]
fn c_002_completion_is_the_shared_status_category_on_every_surface() {
    // The trap `tests/capacity_calculate.rs` sets, reused here to compare all four
    // surfaces rather than one.
    let board = "[kanban.default]\ncolumns = [\"todo\", \"done\", \"shipped\"]\n\
                 done_column = \"done\"\n\
                 category_map = { todo = \"unstarted\", done = \"active\", shipped = \"completed\" }\n\
                 \n\
                 [kanban.default.wip.units]\nd = 1\n";
    let project = Project::with_board(board);
    let id = project.generate();
    project.set(&id, 10, "d");
    // 2d is complete (`shipped`), 5d is **not** (it sits in `done`, which the category
    // map calls `active`), 1d is unstarted.
    project.create("complete", "2d", "shipped");
    project.create("not yet", "5d", "done");
    project.create("todo", "1d", "todo");

    let cli = cli_calculation(&project, &id);
    assert_eq!(
        cli.get("committed").map(String::as_str),
        Some("8"),
        "{cli:?}"
    );
    assert_eq!(
        cli.get("completed").map(String::as_str),
        Some("2"),
        "the category answer, not the `done` column: {cli:?}"
    );
    assert_eq!(cli.get("remaining").map(String::as_str), Some("6"));

    let mut app = project.app();
    open_capacity_tab(&mut app);
    assert_eq!(tui_fields(&app, 0), cli, "the page agrees with the CLI");

    let mut session = open_session(&project);
    let mcp = session.call_tool(
        "capacity_calculate",
        &json!({"scope": "cycle", "id": INSTANCE_ID}),
    );
    let structured = tool_structured(&mcp);
    assert_eq!(structured["committed"].as_u64(), Some(8));
    assert_eq!(
        structured["completed"].as_u64(),
        Some(2),
        "the tool agrees with the CLI"
    );
    let (status, _) = session.close();
    assert!(status.success());

    let document = export(&project, &[]);
    assert_eq!(
        document["scopes"][0]["calculation"]["completed"].as_u64(),
        Some(2),
        "the document agrees with the CLI: {document}"
    );

    // Positive control: on the board where `done` **is** `completed`, the same 5d issue
    // is complete — so the assertion above tracks the category service, not a constant.
    let control = Project::new("");
    let control_id = control.generate();
    control.set(&control_id, 10, "d");
    control.create("done", "5d", "done");
    let control_cli = cli_calculation(&control, &control_id);
    assert_eq!(
        control_cli.get("completed").map(String::as_str),
        Some("5"),
        "{control_cli:?}"
    );
    assert_ne!(control_cli.get("completed"), cli.get("completed"));
}

// ===========================================================================
// T046 — warnings and the closed-cycle lifecycle (C-006, C-008, NFR-002)
// ===========================================================================

/// C-006 / FR-003: overflow is a **shared report** — the same numbers, scope and remedy on
/// every surface — and reading it writes nothing. The control runs the same fixture one
/// unit under the ceiling, where the excess is genuinely `0` and no overflow is reported,
/// so neither the `1` nor the warning can be a constant.
#[test]
fn c_006_fr_003_overflow_is_a_shared_report_and_writes_nothing() {
    let project = Project::new("");
    let id = project.generate();
    project.set(&id, 5, "d");
    project.create("six", "6d", "todo");

    let before = tree(project.root());

    let (code, out, err) = run(
        project.root(),
        &[
            "capacity",
            "calculate",
            "--scope",
            "cycle",
            "--id",
            INSTANCE_ID,
            "--warnings",
        ],
    );
    assert_eq!(code, 0, "{err}");
    let cli = fields(&out);
    assert_eq!(cli.get("capacity").map(String::as_str), Some("5"));
    assert_eq!(cli.get("committed").map(String::as_str), Some("6"));
    assert_eq!(cli.get("overflow").map(String::as_str), Some("1"));
    assert_eq!(cli.get("utilization").map(String::as_str), Some("120%"));
    assert!(err.contains("capacity_overflow"), "{err}");
    assert!(
        err.contains("exceeds the configured capacity of 5d by 1d"),
        "{err}"
    );
    assert!(err.contains("issues: #1"), "{err}");
    assert!(err.contains("help:"), "the report carries a remedy: {err}");

    // The TUI's row and detail are the DTO's own excess.
    let mut app = project.app();
    open_capacity_tab(&mut app);
    assert_eq!(tui_fields(&app, 0), cli);
    assert!(app.capacity_rows()[0].overflowing);
    assert!(
        app.capacity_rows()[0].subtitle.contains("overflow 1d"),
        "{}",
        app.capacity_rows()[0].subtitle
    );
    assert!(
        app.capacity_rows()[0].subtitle.contains("120%"),
        "{}",
        app.capacity_rows()[0].subtitle
    );

    // MCP: a structured report with current/limit/excess/unit, reason and remedy.
    let mut session = open_session(&project);
    let calculated = session.call_tool(
        "capacity_calculate",
        &json!({"scope": "cycle", "id": INSTANCE_ID, "warnings": true}),
    );
    let calculation = tool_structured(&calculated);
    assert_eq!(calculation["overflow"].as_u64(), Some(1));
    assert_eq!(calculation["over_capacity"], json!(true));
    let overflow = calculation["diagnostics"]
        .as_array()
        .expect("diagnostics")
        .iter()
        .find(|finding| finding["kind"] == json!("capacity_overflow"))
        .expect("an overflow warning");
    assert_eq!(overflow["current"].as_u64(), Some(6));
    assert_eq!(overflow["limit"].as_u64(), Some(5));
    assert_eq!(overflow["overflow"].as_u64(), Some(1));
    assert_eq!(overflow["unit"], json!("d"));
    assert!(
        overflow["reason"]
            .as_str()
            .is_some_and(|r| r.contains("exceeds"))
    );
    assert!(overflow["remedy"].as_str().is_some_and(|r| !r.is_empty()));
    let (status, lines) = session.close();
    assert!(status.success());
    assert_pure_stdout(&lines);

    // Portable: the same finding survives into the document.
    let document = export(&project, &[]);
    let portable = portable_findings(&document["scopes"][0]["calculation"], "capacity_overflow");
    assert_eq!(portable.len(), 1, "{document}");
    assert_eq!(portable[0]["current"].as_u64(), Some(6));
    assert_eq!(portable[0]["limit"].as_u64(), Some(5));
    assert_eq!(portable[0]["overflow"].as_u64(), Some(1));
    assert_eq!(portable[0]["unit"], json!("d"));

    // No read above — CLI, TUI, MCP or export — wrote a byte.
    assert_eq!(
        tree(project.root()),
        before,
        "a shared report never mutates an issue, a record or a snapshot"
    );

    // --- Positive control: at the ceiling the excess is 0 and nothing is reported.
    let at_ceiling = Project::new("");
    let at_id = at_ceiling.generate();
    at_ceiling.set(&at_id, 6, "d");
    at_ceiling.create("six", "6d", "todo");
    let (code, out, err) = run(
        at_ceiling.root(),
        &[
            "capacity",
            "calculate",
            "--scope",
            "cycle",
            "--id",
            INSTANCE_ID,
            "--warnings",
        ],
    );
    assert_eq!(code, 0, "{err}");
    let cli = fields(&out);
    assert_eq!(cli.get("overflow").map(String::as_str), Some("0"), "{out}");
    assert_eq!(cli.get("utilization").map(String::as_str), Some("100%"));
    assert!(
        !err.contains("capacity_overflow"),
        "no warning at the ceiling: {err}"
    );
    let mut app = at_ceiling.app();
    open_capacity_tab(&mut app);
    assert!(!app.capacity_rows()[0].overflowing);
}

/// NFR-002 / C-008: a reopen appends exactly one append-only History event and leaves the
/// closed snapshot **and** the configuration byte-identical; the portable document and the
/// MCP tool both carry that History. The vocabulary contains only the events a cycle
/// can actually produce.
#[test]
fn nfr_002_c_008_a_reopen_appends_one_event_and_leaves_the_prior_snapshot_identical() {
    let project = Project::new("");
    let id = project.generate();
    project.set(&id, 10, "d");
    project.create("one", "6d", "todo");
    project.create("two", "2d", "done");
    project.close(&id);

    let snapshot_before = project.snapshot_bytes();
    let config_before = fs::read(project.root().join("tix.toml")).unwrap();

    project.reopen(&id);

    // The prior snapshot is immutable: a reopen computes a new current view and rewrites
    // nothing that was already evidence.
    assert_eq!(
        project.snapshot_bytes(),
        snapshot_before,
        "a reopen never rewrites the closed snapshot"
    );
    assert_eq!(
        fs::read(project.root().join("tix.toml")).unwrap(),
        config_before,
        "a reopen never rewrites the configuration"
    );

    // The one History entry is the reopen, and it is append-only.
    let mut session = open_session(&project);
    let tool = session.call_tool("capacity_snapshot", &json!({"cycle": INSTANCE_ID}));
    let history = tool_structured(&tool)["history"]
        .as_array()
        .expect("history")
        .clone();
    let kinds: Vec<&str> = history
        .iter()
        .filter_map(|event| event["kind"].as_str())
        .collect();
    assert_eq!(
        kinds,
        vec!["cycle_closed", "cycle_reopened"],
        "exactly the close and the one reopen: {history:?}"
    );
    let (status, _) = session.close();
    assert!(status.success());

    // The portable document's History is the same, and the evidence is carried whole.
    let document = export(&project, &[]);
    let portable_kinds: Vec<&str> = document["history"]
        .as_array()
        .expect("history")
        .iter()
        .filter_map(|event| event["kind"].as_str())
        .collect();
    assert_eq!(
        portable_kinds,
        vec!["cycle_closed", "cycle_reopened"],
        "{document}"
    );
    assert_eq!(
        document["snapshots"][0]["committed"].as_u64(),
        Some(8),
        "the snapshot is carried, not recomputed"
    );

    // The reopen is still readable as the live calculation, and the snapshot readback
    // agrees with the evidence (a reopen leaves the history readable, not rewritten).
    let readback = stdout(project.root(), &["capacity", "snapshot", &id]);
    assert!(readback.contains("evidence: present"), "{readback}");

    // The control: the reopen *did* write, so the immutability assertions above are a
    // property of the snapshot, not of a fixture that cannot change.
    let record = fs::read_to_string(
        project
            .root()
            .join("docs/cycles/weekly-sprint-2026-01-05-000001.md"),
    )
    .expect("the cycle record reads");
    assert!(
        record.contains("cycle_reopened"),
        "the reopen is a real write to the cycle record: {record}"
    );
}

// ===========================================================================
// T047 — the comprehensive parity check (C-007, NFR-003)
// ===========================================================================

/// C-007 / NFR-003: one fixture that exercises every state at once — a same-unit estimate,
/// a converted one, an uncountable one, an unestimated one, and an overflow — is reported
/// identically by the CLI, the TUI, MCP and the portable document: scope, unit, values,
/// rounding, warning kinds, snapshot identity and History summary.
#[test]
fn nfr_003_c_007_every_surface_agrees_on_scope_values_rounding_warnings_and_snapshot() {
    let project = Project::new("");
    let id = project.generate();
    project.set(&id, 10, "d");
    // committed = 6 (d) + 2 (d, complete) + 5 (1w converted) = 13; overflow 3; 130%.
    project.create("six", "6d", "todo");
    project.create("two", "2d", "done");
    project.create("week", "1w", "todo");
    project.create("hours", "3h", "todo");
    project.create("blank", "", "todo");
    project.close(&id);
    project.reopen(&id);

    // --- CLI, with the warnings opted in.
    let (code, out, err) = run(
        project.root(),
        &[
            "capacity",
            "calculate",
            "--scope",
            "cycle",
            "--id",
            INSTANCE_ID,
            "--warnings",
        ],
    );
    assert_eq!(code, 0, "{err}");
    let cli = fields(&out);
    assert_eq!(
        cli.get("committed").map(String::as_str),
        Some("13"),
        "{out}"
    );
    assert_eq!(cli.get("completed").map(String::as_str), Some("2"));
    assert_eq!(cli.get("remaining").map(String::as_str), Some("11"));
    assert_eq!(cli.get("capacity").map(String::as_str), Some("10"));
    assert_eq!(cli.get("overflow").map(String::as_str), Some("3"));
    assert_eq!(cli.get("utilization").map(String::as_str), Some("130%"));
    assert_eq!(cli.get("counted_issues").map(String::as_str), Some("3"));
    assert_eq!(cli.get("uncounted_issues").map(String::as_str), Some("1"));
    assert_eq!(cli.get("unestimated_issues").map(String::as_str), Some("1"));
    // The two findings the fixture must raise, by their shared vocabulary.
    for kind in ["missing_conversion", "capacity_overflow"] {
        assert!(err.contains(kind), "the CLI reports `{kind}`: {err}");
    }

    // --- TUI: the detail is the CLI's fields, warning kinds and all.
    let mut app = project.app();
    open_capacity_tab(&mut app);
    assert_eq!(
        tui_fields(&app, 0),
        cli,
        "the page prints exactly the CLI's fields"
    );
    let detail = app.capacity_detail(0).expect("the scope has a detail");
    let tui_text = detail.diagnostics.join("\n");
    let summaries = app.capacity_summaries().expect("the board read ran");
    assert_eq!(
        summaries.get(INSTANCE_ID).map(String::as_str),
        Some("13/10 d · 130% · over"),
        "the board cell is the same values, rounding and overflow flag"
    );

    // --- MCP: text is the CLI's stdout joined with the same findings, and the structure
    // carries the same numbers and kinds.
    let mut session = open_session(&project);
    let calculated = session.call_tool(
        "capacity_calculate",
        &json!({"scope": "cycle", "id": INSTANCE_ID, "warnings": true}),
    );
    assert_eq!(
        tool_text(&calculated),
        format!("{out}\n{err}"),
        "MCP words the calculation and its findings as the CLI does"
    );
    let mcp = tool_structured(&calculated);
    assert_eq!(mcp["committed"].as_u64(), Some(13));
    assert_eq!(mcp["completed"].as_u64(), Some(2));
    assert_eq!(mcp["remaining"].as_u64(), Some(11));
    assert_eq!(mcp["overflow"].as_u64(), Some(3));
    assert_eq!(
        mcp["utilization"].as_u64(),
        Some(130),
        "the same floored percentage"
    );
    assert_eq!(mcp["unit"], json!("d"));
    assert_eq!(mcp["scope"]["display"], json!(INSTANCE_NAME));
    let mcp_kinds: BTreeSet<String> = mcp["diagnostics"]
        .as_array()
        .expect("diagnostics")
        .iter()
        .filter_map(|finding| finding["kind"].as_str().map(str::to_string))
        .collect();
    assert_eq!(
        mcp_kinds,
        BTreeSet::from([
            "capacity_overflow".to_string(),
            "missing_conversion".to_string()
        ]),
        "the fixture raises exactly the overflow and the missing conversion"
    );
    // The CLI's own rendering and the TUI's detail both carry every kind the tool
    // structured — one warning vocabulary across the surfaces (C-006/C-007).
    for kind in &mcp_kinds {
        assert!(
            err.contains(kind),
            "the CLI's stderr carries `{kind}`: {err}"
        );
        assert!(
            tui_text.contains(kind),
            "the TUI's detail carries `{kind}`: {tui_text}"
        );
    }

    // The snapshot tool's History is the same close+reopen the lifecycle wrote.
    let snapshot = session.call_tool("capacity_snapshot", &json!({"cycle": INSTANCE_ID}));
    let structured = tool_structured(&snapshot);
    let history_kinds: Vec<String> = structured["history"]
        .as_array()
        .expect("history")
        .iter()
        .filter_map(|event| event["kind"].as_str().map(str::to_string))
        .collect();
    assert_eq!(history_kinds, vec!["cycle_closed", "cycle_reopened"]);
    let (status, lines) = session.close();
    assert!(status.success());
    assert_pure_stdout(&lines);

    // --- Portable: the same calculation, the same findings, the same snapshot and History.
    let document = export(&project, &[]);
    let portable = &document["scopes"][0]["calculation"];
    assert_eq!(portable["state"], json!("configured"));
    assert_eq!(portable["unit"], json!("d"));
    assert_eq!(portable["scope"]["reference"], json!(INSTANCE_ID));
    assert_eq!(portable["scope"]["display"], json!(INSTANCE_NAME));
    for (field, key) in [
        ("capacity", "capacity"),
        ("committed", "committed"),
        ("completed", "completed"),
        ("remaining", "remaining"),
        ("overflow", "overflow"),
        ("counted_issues", "counted_issues"),
        ("uncounted_issues", "uncounted_issues"),
        ("unestimated_issues", "unestimated_issues"),
    ] {
        portable_equals_cli(&document, portable, field, key, cli_number(&cli, key));
    }
    assert_eq!(portable["utilization"].as_u64(), Some(130));
    let portable_kinds: BTreeSet<String> = portable["diagnostics"]
        .as_array()
        .expect("diagnostics")
        .iter()
        .filter_map(|finding| finding["kind"].as_str().map(str::to_string))
        .collect();
    assert_eq!(
        portable_kinds, mcp_kinds,
        "the document preserves every finding kind the tool structured"
    );
    assert_eq!(
        document["snapshots"][0]["committed"].as_u64(),
        Some(13),
        "the close captured the same 13"
    );
    let portable_history: Vec<String> = document["history"]
        .as_array()
        .expect("history")
        .iter()
        .filter_map(|event| event["kind"].as_str().map(str::to_string))
        .collect();
    assert_eq!(
        portable_history, history_kinds,
        "the History summary is shared"
    );
}

// ===========================================================================
// T045/C-001 — the read surfaces write nothing (with a write control)
// ===========================================================================

/// C-001: every capacity **read** — CLI, TUI, MCP, portable export — leaves the tree
/// byte-identical, both before and after a close. The control is a real write, which
/// *does* move the fingerprint, so the equality is a measurement of read-only-ness and not
/// of an unchanging fixture.
///
/// The baseline is taken on a tree **no `tix` command has touched**. That placement is
/// load-bearing and is the whole point of [`Project::assembled`]: `tix capacity set` and
/// `tix create` themselves walk `schedule_index`, so a fixture built by running them has
/// already produced whatever that seam writes, and a write-on-read that leaves an
/// identical file behind would be invisible to a baseline taken afterwards — for *any*
/// seam, not just the close's.
#[test]
fn c_001_every_capacity_read_writes_nothing() {
    // Assembled from files and library calls only: a hand-written capacity section, a
    // generated-cycle record written through the store, and two issue files. Not one
    // `tix` command has run, so no read seam has been walked when `before` is taken.
    let project = Project::assembled(&capacity_entry(INSTANCE_ID, 10, "d"));
    project.write_issue(
        1,
        "todo",
        &format!("cycles: [\"{INSTANCE_NAME}\"]\nassignee: \"ada\"\nestimate: \"6d\"\n"),
    );
    project.write_issue(
        2,
        "todo",
        &format!("cycles: [\"{INSTANCE_NAME}\"]\nassignee: \"ada\"\nestimate: \"3h\"\n"),
    );

    let before = tree(project.root());

    // --- Phase 1: the read surfaces before any close (no evidence exists yet).
    let _ = stdout(project.root(), &["capacity", "list"]);
    let _ = stdout(project.root(), &["capacity", "show", INSTANCE_ID]);
    let _ = stdout(
        project.root(),
        &[
            "capacity",
            "calculate",
            "--scope",
            "cycle",
            "--id",
            INSTANCE_ID,
        ],
    );
    // The snapshot read refuses (nothing is closed) and still writes nothing.
    let (code, _out, _err) = run(
        project.root(),
        &["capacity", "snapshot", INSTANCE_ID, "--warnings"],
    );
    assert_ne!(code, 0, "no snapshot exists yet");
    assert_eq!(tree(project.root()), before, "the CLI reads wrote nothing");

    // TUI read (a fresh in-process app opens each configured scope and its snapshot).
    let mut app = project.app();
    open_capacity_tab(&mut app);
    assert!(app.capacity_read(), "the TUI read ran");
    assert_eq!(tree(project.root()), before, "the TUI read wrote nothing");

    // MCP reads.
    let mut session = open_session(&project);
    let _ = session.call_tool("capacity_list", &json!({}));
    let _ = session.call_tool("capacity_show", &json!({"reference": INSTANCE_ID}));
    let _ = session.call_tool(
        "capacity_calculate",
        &json!({"scope": "cycle", "id": INSTANCE_ID, "warnings": true}),
    );
    let _ = session.call_tool("capacity_snapshot", &json!({"cycle": INSTANCE_ID}));
    let (status, _) = session.close();
    assert!(status.success());
    assert_eq!(tree(project.root()), before, "the MCP reads wrote nothing");

    // Portable read.
    let _ = export(&project, &[]);
    assert_eq!(
        tree(project.root()),
        before,
        "the portable read wrote nothing"
    );

    // --- Phase 2: close (a real write), then read the evidence and again write nothing.
    project.close(INSTANCE_ID);
    let closed = tree(project.root());
    assert_ne!(
        closed, before,
        "the close wrote its snapshot and its history — the fingerprint sees writes"
    );
    let _ = stdout(
        project.root(),
        &["capacity", "snapshot", INSTANCE_ID, "--warnings"],
    );
    let mut app = project.app();
    open_capacity_tab(&mut app);
    let mut session = open_session(&project);
    let _ = session.call_tool("capacity_snapshot", &json!({"cycle": INSTANCE_ID}));
    let (status, _) = session.close();
    assert!(status.success());
    let _ = export(&project, &[]);
    assert_eq!(
        tree(project.root()),
        closed,
        "reads over the closed evidence wrote nothing"
    );

    // --- Write control: a configuration write does change the tree. (The closed cycle's
    // own ceiling cannot be the control: editing a closed cycle's capacity is refused by
    // design, C-008 — the team scope beside it is neither closed nor configured.)
    project.set_team("Platform", 12, "d");
    let after = tree(project.root());
    assert_ne!(
        after, closed,
        "`tix capacity set` writes, and the fingerprint sees it"
    );
    assert_ne!(
        after.get("tix.toml"),
        closed.get("tix.toml"),
        "the changed file is the configuration"
    );
}

// ===========================================================================
// T048 — NFR-001, measured structurally
// ===========================================================================

/// The estimate a performance issue states: `(frontmatter, states an estimate, states a
/// readable one)`. A mix of completed/open, assigned/unassigned, scoped/unscoped, and
/// every estimate state the index must handle — the same shape `tests/capacity_estimate.rs`
/// uses, so the two measurements are about the same work.
fn performance_issue(number: u32) -> (String, bool, bool) {
    let mut extra = String::new();
    if number % 2 == 0 {
        extra.push_str("assignee: \"ada\"\n");
    } else if number % 5 == 0 {
        extra.push_str("assignee: \"grace\"\n");
    }
    if number % 4 != 0 {
        extra.push_str("cycles: [\"Cycle 1\"]\n");
    } else {
        extra.push_str("cycles: [\"Ghost\"]\n");
    }
    let residue = number % 6;
    extra.push_str(match residue {
        0 => "estimate: \"3d\"\n",
        1 => "estimate: \"1w\"\n",
        2 => "estimate: \"5\"\n",
        3 => "estimate: \"3h\"\n",
        4 => "estimate: \"twenty\"\n",
        _ => "estimate: \"\"\n",
    });
    (extra, residue != 5, residue <= 3)
}

/// NFR-001: 10,000 in-memory issues are indexed **once** — each stated estimate parsed
/// once and the conversion seam consulted once per readable estimate per unit, not once
/// per queried scope. The assertion is on the snapshot's own counters, so it is a
/// statement about the work done, not about how fast a machine happened to be; a wall
/// clock is printed for the record but never asserted (a contended machine breaks it, as
/// the mission's tracer records).
///
/// After the index is built, calculations are zero-work by **construction**, not by a
/// runtime check: `for_scope` takes `&IssueSnapshot`, whose every accessor is `&self`
/// with no interior mutability, so a calculation cannot parse or convert. This test
/// therefore asserts the counters **at the build**, where the work happens, and the
/// finite-work claim rests on that signature rather than on a tuple that could not move.
#[test]
fn nfr_001_ten_thousand_issues_are_indexed_once_and_calculated_structurally() {
    let dir = TempDir::new().unwrap();
    let issues = dir.path().join("issues");
    fs::create_dir_all(&issues).unwrap();
    fs::write(
        dir.path().join("tix.toml"),
        format!(
            "issues_dir = {issues:?}\n\
             {BOARD}\n\
             [cycles.\"Cycle 1\"]\nstart_date = \"2026-01-01\"\n\n\
             [capacity.sprint]\ncycle = \"Cycle 1\"\ncapacity = 100000\nunit = \"d\"\n\n\
             [capacity.platform]\nteam = \"Platform\"\ncapacity = 100000\nunit = \"d\"\n\n\
             [capacity.ada]\nassignee = \"ada\"\ncapacity = 100000\nunit = \"d\"\n",
            issues = issues.to_string_lossy(),
        ),
    )
    .unwrap();
    let config = Config::load(dir.path()).expect("the fixture loads");
    let index = schedule_index(&config, dir.path()).expect("the cycle index builds");

    const COUNT: u32 = 10_000;
    let mut parsed = 0usize;
    let mut readable = 0usize;
    let parsed_issues: Vec<Issue> = (1..=COUNT)
        .map(|number| {
            let (extra, stated, valid) = performance_issue(number);
            if stated {
                parsed += 1;
            }
            if valid {
                readable += 1;
            }
            Issue::parse(&format!(
                "---\nnumber: {number}\ntitle: \"Issue {number}\"\nstatus: \"{status}\"\n\
                 labels: []\npriority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n{extra}---\n\nBody.\n",
                status = if number % 3 == 0 { "done" } else { "todo" },
            ))
            .expect("the generated issue parses")
        })
        .collect();
    assert_eq!(parsed_issues.len(), COUNT as usize);

    // One index, built once.
    let started = Instant::now();
    let snapshot = IssueSnapshot::build(&config, &index, &parsed_issues);
    let build = started.elapsed();

    let units = snapshot.targets().len();
    assert_eq!(
        units,
        2,
        "the board declares two units: {:?}",
        snapshot.targets()
    );
    assert_eq!(snapshot.len(), COUNT as usize, "every issue is indexed");
    assert_eq!(
        snapshot.issue_visits(),
        COUNT as usize,
        "each issue is visited exactly once by the one pass"
    );
    assert_eq!(
        snapshot.estimates_parsed(),
        parsed,
        "each stated estimate is parsed exactly once"
    );
    assert_eq!(
        snapshot.conversions_resolved(),
        readable * units,
        "the conversion seam is consulted once per readable estimate, per unit — a second \
         pass, or one resolution repeated per queried scope, would exceed this"
    );

    // Three scopes are then calculated from the one finished index. This is *not* where the
    // zero-work guarantee is enforced: `CapacityCalculation::for_scope` takes `&IssueSnapshot`
    // (and every accessor on it is `&self` with no interior mutability), so a calculation
    // structurally cannot parse or convert anything — the guarantee is the signature, and a
    // runtime tuple re-read here would be tautological. What this block does assert is that
    // the calculations really ran over the indexed slice (a value, not an early return).
    let cycle_calc = CapacityCalculation::for_scope(
        &snapshot,
        &index,
        &config,
        CapacityScope::new(CapacityScopeKind::Cycle, "Cycle 1", &index),
    );
    let team_calc = CapacityCalculation::for_scope(
        &snapshot,
        &index,
        &config,
        CapacityScope::new(CapacityScopeKind::Team, "Platform", &index),
    );
    let assignee_calc = CapacityCalculation::for_scope(
        &snapshot,
        &index,
        &config,
        CapacityScope::new(CapacityScopeKind::Assignee, "ada", &index),
    );
    // The calculations really ran (a value, not an early return).
    assert!(cycle_calc.committed.is_some(), "{cycle_calc:?}");
    assert!(team_calc.committed.is_some());
    assert!(assignee_calc.committed.is_some());
    assert_eq!(
        cycle_calc.state(),
        tix::capacity::calculate::CapacityState::Configured
    );

    // Positive control: the counters follow the work, not the fixture. Indexing the same
    // records twice over doubles every measure, so the equalities above are quantities the
    // build actually produced.
    let doubled: Vec<Issue> = parsed_issues
        .iter()
        .chain(parsed_issues.iter())
        .cloned()
        .collect();
    let twice = IssueSnapshot::build(&config, &index, &doubled);
    assert_eq!(twice.issue_visits(), 2 * COUNT as usize);
    assert_eq!(twice.estimates_parsed(), 2 * parsed);
    assert_eq!(twice.conversions_resolved(), 2 * readable * units);
    assert_ne!(twice.issue_visits(), snapshot.issue_visits());

    println!(
        "NFR-001: {COUNT} issues indexed in {build:?} \
         ({} estimates parsed, {} conversions resolved for {units} units); \
         three scopes then calculated over that one index",
        snapshot.estimates_parsed(),
        snapshot.conversions_resolved(),
    );
}