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
//! WP08 cross-surface verification for `roadmap-initiatives-01M3C8SX`.
//!
//! One target for the mission's cross-cutting acceptance evidence, so the parity
//! assertions do not compete with the per-surface files WP01–WP07 own
//! (`tests/roadmap_registry.rs`, `tests/roadmap_filter.rs`,
//! `tests/roadmap_projection.rs`, `tests/roadmap_cli.rs`,
//! `tests/roadmap_portable.rs`). Every test is named with its requirement ID so a
//! reviewer can trace evidence by ID.
//!
//! | Test prefix | Requirement |
//! |---|---|
//! | `nfr003_` | CLI, TUI, MCP and the portable document report the same ordered ids, filter sets, summary values, provenance, policy versions and diagnostics by value |
//! | `nfr002_` | stable ids survive a round trip and a rename; repeated operations are idempotent |
//! | `nfr001_` | one indexed aggregation over 10,000 entities, excluding file I/O |
//! | `c004_`  | the summary is a join of the owning services' values, never a blend |
//! | `c005_`  | a missing reference stays visible on every surface |
//! | `c006_`  | empty, unknown and a genuine zero are distinct states, never one `0` |
//! | `c008_`  | every rejected mutation leaves the tree byte-identical and appends nothing |
//! | `boundary_` | `tix lint` reports issue-held references, not an initiative's config-held ones |
//!
//! The CLI half drives the real binary (`assert_cmd`); the TUI half drives
//! `App::handle_key` and reads the `F10` Portfolio page's **Roadmap** tab; the MCP
//! half calls `tix::mcp::tools::call` in process, as `tests/project_parity.rs` and
//! `tests/epic_parity.rs` do; the portable half reads the versioned document the
//! export builds. No TTY, no network, deterministic.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Instant;

use assert_cmd::Command;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde_json::{Value, json};
use tempfile::TempDir;
use tix::app::App;
use tix::config::{Config, EpicConfiguration, InitiativeConfiguration, ProjectConfiguration};
use tix::epics::EpicIndex;
use tix::health::HealthPolicy;
use tix::model::Issue;
use tix::projects::ProjectIndex;
use tix::relationships::{IssueView, RelationshipGraph};
use tix::roadmap::portable::PortableRoadmap;
use tix::roadmap::projection::{ProgressValue, RoadmapProjection, RoadmapSources, SummaryState};
use tix::roadmap::{RoadmapConsumed, RoadmapFilter};
use tix::storage::Store;

// ---------------------------------------------------------------------------
// Harnesses
// ---------------------------------------------------------------------------

fn tix() -> Command {
    let mut c = Command::cargo_bin("tix").expect("the tix binary must build");
    c.env("NO_COLOR", "1").env("TERM", "dumb");
    c
}

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

/// Run a CLI invocation inside the fixture and return `(stdout, stderr, success)`.
fn cli(tmp: &TempDir, args: &[&str]) -> (String, String, bool) {
    cli_args(
        tmp,
        &args.iter().map(|a| (*a).to_string()).collect::<Vec<_>>(),
    )
}

/// The same, for an argument vector built at runtime (the roadmap filter flags).
fn cli_args(tmp: &TempDir, args: &[String]) -> (String, String, bool) {
    let out = tix()
        .current_dir(tmp.path())
        .args(args)
        .output()
        .expect("the CLI must run");
    (
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
        out.status.success(),
    )
}

/// A well-formed in-process MCP call.
fn mcp(config: &Config, store: &Store, name: &str, args: Value) -> Value {
    tix::mcp::tools::call(
        config,
        store,
        tix::mcp::protocol::Id::Number(1),
        name,
        &args,
    )
    .expect("a well-formed call must not fail at the protocol level")
}

fn mcp_is_error(value: &Value) -> bool {
    value.get("isError").and_then(Value::as_bool) == Some(true)
}

fn mcp_structured(value: &Value) -> &Value {
    value
        .get("structuredContent")
        .expect("a success result carries structuredContent")
}

/// Every file under `root`, keyed by its relative path, as raw bytes.
fn snapshot(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
    let mut out = BTreeMap::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(next) = stack.pop() {
        for entry in fs::read_dir(&next).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                stack.push(path);
            } else {
                let rel = path.strip_prefix(root).unwrap().to_path_buf();
                out.insert(rel, fs::read(&path).unwrap());
            }
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Fixture: one snapshot the four surfaces read
// ---------------------------------------------------------------------------

/// Write one issue file with the lists that carry membership.
#[allow(clippy::too_many_arguments)]
fn write_issue(
    dir: &Path,
    number: u32,
    title: &str,
    status: &str,
    projects: &[&str],
    epics: &[&str],
    milestones: &[&str],
    assignee: Option<&str>,
) {
    let mut raw = format!("---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"{status}\"\n");
    for (key, values) in [
        ("projects", projects),
        ("epics", epics),
        ("milestones", milestones),
    ] {
        if values.is_empty() {
            continue;
        }
        raw.push_str(&format!("{key}:\n"));
        for value in values {
            raw.push_str(&format!("- \"{value}\"\n"));
        }
    }
    if let Some(assignee) = assignee {
        raw.push_str(&format!("assignee: \"{assignee}\"\n"));
    }
    raw.push_str("created: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody.\n");
    fs::write(
        dir.join(format!("2026-01-{number:02}-issue-{number}.md")),
        raw,
    )
    .unwrap();
}

/// One milestone registry file (the planner reads `docs/milestones/*.md`).
fn write_milestone(root: &Path, name: &str) {
    let dir = root.join("docs/milestones");
    fs::create_dir_all(&dir).unwrap();
    fs::write(
        dir.join(format!("2026-01-01-{}.md", name.to_lowercase())),
        format!(
            "---\nname: {name}\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\n{name}.\n"
        ),
    )
    .unwrap();
}

/// The one snapshot every surface is compared over: seven initiatives covering
/// every summary state (`complete`, `partial`, `missing_reference`, `empty`,
/// `unknown`, and an undated row), a zero-progress project, a resolved and a
/// missing reference of each kind, and the filter dimensions.
///
/// Timestamps are chosen so the roadmap order is `i-alpha, i-partial, i-missing,
/// i-empty, i-zero, i-unknown, i-undated`.
fn parity_fixture() -> (TempDir, Config) {
    let tmp = TempDir::new().unwrap();
    let issues = tmp.path().join("issues");
    fs::create_dir_all(&issues).unwrap();

    let mut toml = format!(
        "issues_dir = \"{}\"\n\n[kanban.default]\ncolumns = [\"todo\", \"in progress\", \"done\"]\n\
         done_column = \"done\"\n\n",
        issues.display()
    );
    for (id, name) in [
        ("p-alpha", "Alpha program"),
        ("p-beta", "Beta program"),
        ("p-zero", "Zero program"),
    ] {
        toml.push_str(&format!("[projects.\"{id}\"]\nname = \"{name}\"\n\n"));
    }
    toml.push_str("[epics.\"e-alpha\"]\nname = \"Alpha epic\"\n\n");
    toml.push_str(
        "[initiatives.\"i-alpha\"]\nname = \"Alpha portfolio\"\noutcome = \"Ship the alpha launch\"\n\
         owner = \"alice\"\nstatus = \"active\"\nlabels = [\"strategic\"]\ntarget_date = \"2026-01-01\"\n\
         projects = [\"p-alpha\"]\nepics = [\"e-alpha\"]\nmilestones = [\"M-live\"]\n\n",
    );
    toml.push_str(
        "[initiatives.\"i-partial\"]\nname = \"Beta plus ghost\"\nowner = \"bob\"\n\
         status = \"planning\"\nlabels = [\"strategic\", \"apac\"]\ntarget_date = \"2026-02-15\"\n\
         projects = [\"p-alpha\"]\nepics = [\"e-ghost\"]\n\n",
    );
    toml.push_str(
        "[initiatives.\"i-missing\"]\nname = \"All ghosts\"\nlabels = [\"legacy\"]\n\
         target_date = \"2026-03-10\"\nprojects = [\"p-ghost-initiative\"]\nepics = [\"e-ghost-2\"]\n\n",
    );
    toml.push_str(
        "[initiatives.\"i-empty\"]\nname = \"Empty slate\"\nowner = \"carol\"\n\
         labels = [\"legacy\"]\ntarget_date = \"2026-04-01\"\n\n",
    );
    toml.push_str(
        "[initiatives.\"i-zero\"]\nname = \"Zero progress\"\ntarget_date = \"2026-05-20\"\n\
         projects = [\"p-zero\"]\n\n",
    );
    toml.push_str(
        "[initiatives.\"i-unknown\"]\nname = \"Unknown milestone\"\ntarget_date = \"2026-06-30\"\n\
         milestones = [\"M-empty\"]\n\n",
    );
    toml.push_str(
        "[initiatives.\"i-undated\"]\nname = \"Undated work\"\nowner = \"alice\"\n\
         projects = [\"p-beta\"]\n",
    );
    fs::write(tmp.path().join("tix.toml"), toml).unwrap();

    write_milestone(tmp.path(), "M-live");
    write_milestone(tmp.path(), "M-empty");

    write_issue(
        &issues,
        1,
        "Alpha done",
        "done",
        &["p-alpha"],
        &["e-alpha"],
        &["M-live"],
        Some("alice"),
    );
    write_issue(
        &issues,
        2,
        "Alpha todo",
        "todo",
        &["p-alpha"],
        &[],
        &[],
        Some("alice"),
    );
    write_issue(
        &issues,
        3,
        "Beta work",
        "todo",
        &["p-beta"],
        &[],
        &[],
        Some("bob"),
    );
    // An issue-held dangling project reference: `tix lint` reports this one, and
    // must not report the initiative's config-held `p-ghost-initiative` (boundary).
    write_issue(
        &issues,
        4,
        "Dangling project",
        "todo",
        &["p-ghost-issue"],
        &[],
        &[],
        None,
    );

    let config = Config::load_with_warning(&tmp.path().join("tix.toml"), |_| {}).unwrap();
    (tmp, config)
}

fn store_for(config: &Config) -> Store {
    Store::open(config).expect("the fixture store opens")
}

/// The shared projection over the fixture, through the real source composition.
fn projection_for(config: &Config, filter: &RoadmapFilter) -> RoadmapProjection {
    let store = store_for(config);
    let issues = store.list_all().unwrap();
    let sources = tix::commands::roadmap::build_sources(config, &store, &issues).unwrap();
    tix::roadmap::project(config, &sources, filter).expect("the projection succeeds")
}

/// The `F10` Portfolio page's **Roadmap** projection for `filter`.
///
/// The real surface: `F10` opens the page, two `Tab` presses reach the Roadmap
/// tab, the normalized filter is installed, and `r` re-reads through the tab's own
/// handler. The returned value is the page's own cached projection, not a second
/// read.
fn tui_projection(config: &Config, filter: &RoadmapFilter) -> RoadmapProjection {
    let mut app = App::new(config).expect("the app builds");
    let _ = app.handle_key(press(KeyCode::F(10))).unwrap();
    let _ = app.handle_key(press(KeyCode::Tab)).unwrap();
    let _ = app.handle_key(press(KeyCode::Tab)).unwrap();
    assert_eq!(
        app.portfolio_state().tab,
        tix::ui::portfolio::PortfolioTab::Roadmap,
        "two `Tab` presses reach the Roadmap tab"
    );
    app.roadmap_filter = filter.clone();
    let _ = app.handle_key(press(KeyCode::Char('r'))).unwrap();
    app.portfolio_roadmap()
        .expect("the Roadmap tab built a projection")
        .clone()
}

/// The portable document for `filter`, through the shared builder.
fn portable_document(config: &Config, filter: &RoadmapFilter) -> PortableRoadmap {
    let store = store_for(config);
    let issues = store.list_all().unwrap();
    let sources = tix::commands::roadmap::build_sources(config, &store, &issues).unwrap();
    PortableRoadmap::build(config, &sources, filter).expect("the document builds")
}

// ---------------------------------------------------------------------------
// The by-value observation every surface is reduced to
// ---------------------------------------------------------------------------

/// One contribution as a surface exposes it: provenance, resolution, policy.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Contribution {
    source_entity: String,
    resolution: String,
    policy_version: Option<String>,
}

/// One diagnostic as a surface exposes it. The CLI's rendered line does not carry
/// the record field separately, so its `field`/`reference` are `None`; the three
/// structured surfaces carry them, and their parity is asserted separately.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Diagnostic {
    kind: String,
    field: Option<String>,
    reference: Option<String>,
}

/// One row, reduced to the values that must be equal across surfaces.
#[derive(Debug, Clone, PartialEq, Eq)]
struct RowView {
    id: String,
    target_date: String,
    state: String,
    contributions: Vec<Contribution>,
    diagnostics: Vec<Diagnostic>,
}

impl RowView {
    fn diagnostic_kinds(&self) -> Vec<&str> {
        self.diagnostics.iter().map(|d| d.kind.as_str()).collect()
    }
}

fn views_from_projection(projection: &RoadmapProjection) -> Vec<RowView> {
    projection
        .initiatives
        .iter()
        .map(|row| RowView {
            id: row.id.clone(),
            target_date: row.target_date.clone().unwrap_or_else(|| "undated".into()),
            state: row.summary.state.as_str().to_string(),
            contributions: row
                .summary
                .contributions
                .iter()
                .map(|c| Contribution {
                    source_entity: c.source_entity(),
                    resolution: c.resolution.as_str().to_string(),
                    policy_version: c.policy_version.clone(),
                })
                .collect(),
            diagnostics: row
                .diagnostics
                .iter()
                .map(|d| Diagnostic {
                    kind: d.kind.as_str().to_string(),
                    field: d.field.clone(),
                    reference: d.reference.clone(),
                })
                .collect(),
        })
        .collect()
}

fn views_from_document(document: &PortableRoadmap) -> Vec<RowView> {
    document
        .rows
        .iter()
        .map(|row| RowView {
            id: row.id.clone(),
            target_date: row.target_date.clone().unwrap_or_else(|| "undated".into()),
            state: row.summary.state.clone(),
            contributions: row
                .summary
                .contributions
                .iter()
                .map(|c| Contribution {
                    source_entity: c.source_entity.clone(),
                    resolution: c.resolution.clone(),
                    policy_version: c.policy_version.clone(),
                })
                .collect(),
            diagnostics: row
                .diagnostics
                .iter()
                .map(|d| Diagnostic {
                    kind: d.kind.clone(),
                    field: d.field.clone(),
                    reference: d.reference.clone(),
                })
                .collect(),
        })
        .collect()
}

/// Reduce the `roadmap_list` structured payload to the same view.
fn views_from_mcp(config: &Config, store: &Store, filter: &RoadmapFilter) -> Vec<RowView> {
    let result = mcp(config, store, "roadmap_list", mcp_filter_args(filter));
    assert!(!mcp_is_error(&result), "roadmap_list failed");
    let structured = mcp_structured(&result);
    structured["initiatives"]
        .as_array()
        .expect("initiatives is an array")
        .iter()
        .map(|row| RowView {
            id: row["id"].as_str().unwrap().to_string(),
            target_date: row["target_date"].as_str().unwrap_or("undated").to_string(),
            state: row["summary"]["state"].as_str().unwrap().to_string(),
            contributions: row["summary"]["contributions"]
                .as_array()
                .unwrap()
                .iter()
                .map(|c| Contribution {
                    source_entity: c["source_entity"].as_str().unwrap().to_string(),
                    resolution: c["resolution"].as_str().unwrap().to_string(),
                    policy_version: c["policy_version"].as_str().map(str::to_string),
                })
                .collect(),
            diagnostics: row["diagnostics"]
                .as_array()
                .unwrap()
                .iter()
                .map(|d| Diagnostic {
                    kind: d["kind"].as_str().unwrap().to_string(),
                    field: d["field"].as_str().map(str::to_string),
                    reference: d["reference"].as_str().map(str::to_string),
                })
                .collect(),
        })
        .collect()
}

/// Parse `tix roadmap list`'s rendered rows into the same view.
///
/// The header is `id<TAB>name<TAB>target date<TAB>summary state`; a contribution
/// is `  <kind>:<id> (<label>) [<resolution>] progress=… risk=… policy=…`; a
/// finding is `  ! <kind>:…`; the empty state is `  (empty: no source
/// references)`. The CLI's finding line carries the kind but not the record field
/// separately, so `field`/`reference` stay `None` here.
fn views_from_cli(stdout: &str) -> Vec<RowView> {
    let mut rows: Vec<RowView> = Vec::new();
    for line in stdout.lines() {
        let columns: Vec<&str> = line.split('\t').collect();
        if columns.len() == 4 {
            rows.push(RowView {
                id: columns[0].to_string(),
                target_date: columns[2].to_string(),
                state: columns[3].to_string(),
                contributions: Vec::new(),
                diagnostics: Vec::new(),
            });
            continue;
        }
        let Some(row) = rows.last_mut() else {
            continue;
        };
        let trimmed = line.trim_start();
        if trimmed.starts_with('(') {
            continue;
        }
        if let Some(rest) = trimmed.strip_prefix("! ") {
            row.diagnostics.push(Diagnostic {
                kind: rest
                    .split(':')
                    .next()
                    .unwrap_or_default()
                    .trim()
                    .to_string(),
                field: None,
                reference: None,
            });
            continue;
        }
        if line.starts_with("  ") {
            let source_entity = trimmed.split_whitespace().next().unwrap_or_default();
            let resolution = trimmed
                .split('[')
                .nth(1)
                .and_then(|rest| rest.split(']').next())
                .unwrap_or_default();
            let policy_version = trimmed
                .rsplit("policy=")
                .next()
                .map(str::trim)
                .filter(|value| *value != "-")
                .map(str::to_string);
            row.contributions.push(Contribution {
                source_entity: source_entity.to_string(),
                resolution: resolution.to_string(),
                policy_version,
            });
        }
    }
    rows
}

// ---------------------------------------------------------------------------
// The filter DTO as CLI flags and as MCP arguments
// ---------------------------------------------------------------------------

fn cli_filter_args(filter: &RoadmapFilter) -> Vec<String> {
    let mut args: Vec<String> = vec!["roadmap".into(), "list".into()];
    let mut push = |flag: &str, value: &str| {
        args.push(flag.to_string());
        args.push(value.to_string());
    };
    if let Some(value) = &filter.period_from {
        push("--from", value);
    }
    if let Some(value) = &filter.period_to {
        push("--to", value);
    }
    if let Some(value) = &filter.owner {
        push("--owner", value);
    }
    if let Some(value) = &filter.status {
        push("--status", value);
    }
    for label in &filter.labels {
        push("--label", label);
    }
    if let Some(value) = &filter.query {
        push("--query", value);
    }
    args
}

fn mcp_filter_args(filter: &RoadmapFilter) -> Value {
    let mut map = serde_json::Map::new();
    if let Some(value) = &filter.period_from {
        map.insert("period_from".into(), json!(value));
    }
    if let Some(value) = &filter.period_to {
        map.insert("period_to".into(), json!(value));
    }
    if let Some(value) = &filter.owner {
        map.insert("owner".into(), json!(value));
    }
    if let Some(value) = &filter.status {
        map.insert("status".into(), json!(value));
    }
    if !filter.labels.is_empty() {
        map.insert("labels".into(), json!(filter.labels));
    }
    if let Some(value) = &filter.query {
        map.insert("query".into(), json!(value));
    }
    Value::Object(map)
}

fn ids(rows: &[RowView]) -> Vec<&str> {
    rows.iter().map(|row| row.id.as_str()).collect()
}

// ---------------------------------------------------------------------------
// NFR-003 — CLI / TUI / MCP / portable equality, by value
// ---------------------------------------------------------------------------

#[test]
fn nfr003_cli_tui_mcp_and_portable_report_the_same_ordered_initiative_ids() {
    let (tmp, config) = parity_fixture();
    let store = store_for(&config);
    let filter = RoadmapFilter::default();

    let (stdout, stderr, ok) = cli_args(&tmp, &cli_filter_args(&filter));
    assert!(ok, "tix roadmap list failed: {stderr}");

    let cli_rows = views_from_cli(&stdout);
    let tui_rows = views_from_projection(&tui_projection(&config, &filter));
    let mcp_rows = views_from_mcp(&config, &store, &filter);
    let portable_rows = views_from_document(&portable_document(&config, &filter));

    // The exact order, so four surfaces agreeing on an empty set cannot pass.
    let expected = vec![
        "i-alpha",
        "i-partial",
        "i-missing",
        "i-empty",
        "i-zero",
        "i-unknown",
        "i-undated",
    ];
    assert_eq!(ids(&cli_rows), expected, "CLI order: {stdout}");
    assert_eq!(ids(&tui_rows), expected, "TUI order");
    assert_eq!(ids(&mcp_rows), expected, "MCP order");
    assert_eq!(ids(&portable_rows), expected, "portable order");

    // Every row's ordering/summary core — id, target date, explicit state and the
    // source-attributed contributions — is equal across all four surfaces. The
    // diagnostics' field/reference detail is compared in the summary-provenance
    // test below, where the three structured surfaces carry it.
    let core = |row: &RowView| {
        (
            row.id.clone(),
            row.target_date.clone(),
            row.state.clone(),
            row.contributions.clone(),
        )
    };
    for (cli, tui, mcp_row, portable) in zip_four(&cli_rows, &tui_rows, &mcp_rows, &portable_rows) {
        assert_eq!(
            core(&cli),
            core(&tui),
            "TUI differs from the CLI for {}",
            cli.id
        );
        assert_eq!(
            core(&cli),
            core(&mcp_row),
            "MCP differs from the CLI for {}",
            cli.id
        );
        assert_eq!(
            core(&cli),
            core(&portable),
            "the portable document differs from the CLI for {}",
            cli.id
        );
    }
}

/// Zip four equally-ordered row slices, panicking when their lengths differ.
fn zip_four<'a>(
    cli: &'a [RowView],
    tui: &'a [RowView],
    mcp: &'a [RowView],
    portable: &'a [RowView],
) -> impl Iterator<Item = (RowView, RowView, RowView, RowView)> + 'a {
    assert!(
        cli.len() == tui.len() && cli.len() == mcp.len() && cli.len() == portable.len(),
        "surface row counts differ: cli={} tui={} mcp={} portable={}",
        cli.len(),
        tui.len(),
        mcp.len(),
        portable.len()
    );
    let zipped: Vec<_> = cli
        .iter()
        .zip(tui)
        .zip(mcp)
        .zip(portable)
        .map(|(((a, b), c), d)| (a.clone(), b.clone(), c.clone(), d.clone()))
        .collect();
    zipped.into_iter()
}

#[test]
fn nfr003_every_filter_dimension_and_a_combination_agrees_across_the_surfaces() {
    let (tmp, config) = parity_fixture();
    let store = store_for(&config);

    // Every dimension plus one combination, each with the ids it must select so an
    // agreed-upon empty set cannot pass.
    let cases: Vec<(RoadmapFilter, Vec<&str>)> = vec![
        (
            RoadmapFilter {
                period_from: Some("2026-02-01".into()),
                period_to: Some("2026-05-31".into()),
                ..RoadmapFilter::default()
            },
            vec!["i-partial", "i-missing", "i-empty", "i-zero"],
        ),
        (
            RoadmapFilter {
                owner: Some("BOB".into()), // normalized, case-insensitively
                ..RoadmapFilter::default()
            },
            vec!["i-partial"],
        ),
        (
            RoadmapFilter {
                status: Some("planning".into()),
                ..RoadmapFilter::default()
            },
            vec!["i-partial"],
        ),
        (
            RoadmapFilter {
                labels: vec!["strategic".into(), "apac".into()], // an AND
                ..RoadmapFilter::default()
            },
            vec!["i-partial"],
        ),
        (
            RoadmapFilter {
                query: Some("ghost".into()),
                ..RoadmapFilter::default()
            },
            vec!["i-partial", "i-missing"],
        ),
        (
            RoadmapFilter {
                period_from: Some("2026-01-01".into()),
                period_to: Some("2026-01-31".into()),
                owner: Some("alice".into()),
                status: Some("active".into()),
                labels: vec!["strategic".into()],
                ..RoadmapFilter::default()
            },
            vec!["i-alpha"],
        ),
    ];

    for (filter, expected) in cases {
        let (stdout, stderr, ok) = cli_args(&tmp, &cli_filter_args(&filter));
        assert!(ok, "tix roadmap list {filter:?} failed: {stderr}");
        let cli_rows = views_from_cli(&stdout);
        let tui_rows = views_from_projection(&tui_projection(&config, &filter));
        let mcp_rows = views_from_mcp(&config, &store, &filter);
        let portable = portable_document(&config, &filter);
        let portable_rows = views_from_document(&portable);

        assert_eq!(ids(&cli_rows), expected, "CLI ids for {filter:?}: {stdout}");
        assert_eq!(ids(&tui_rows), expected, "TUI ids for {filter:?}");
        assert_eq!(ids(&mcp_rows), expected, "MCP ids for {filter:?}");
        assert_eq!(ids(&portable_rows), expected, "portable ids for {filter:?}");

        // The normalized filter the structured surfaces report is the same DTO.
        let mcp_filters: RoadmapFilter =
            serde_json::from_value(mcp_filters_json(&config, &store, &filter)).unwrap();
        assert_eq!(mcp_filters, filter, "MCP reports the normalized filter");
        assert_eq!(
            portable.filters, filter,
            "the document reports the normalized filter"
        );
    }
}

/// The `filters` object the `roadmap_list` structured channel reports.
fn mcp_filters_json(config: &Config, store: &Store, filter: &RoadmapFilter) -> Value {
    let result = mcp(config, store, "roadmap_list", mcp_filter_args(filter));
    assert!(!mcp_is_error(&result), "roadmap_list failed");
    mcp_structured(&result)["filters"].clone()
}

#[test]
fn nfr003_every_surface_reports_the_same_summary_provenance_and_policy_versions() {
    let (tmp, config) = parity_fixture();
    let store = store_for(&config);
    let filter = RoadmapFilter::default();

    let (stdout, stderr, ok) = cli_args(&tmp, &cli_filter_args(&filter));
    assert!(ok, "tix roadmap list failed: {stderr}");
    let cli_rows = views_from_cli(&stdout);
    let tui_rows = views_from_projection(&tui_projection(&config, &filter));
    let mcp_rows = views_from_mcp(&config, &store, &filter);
    let portable_rows = views_from_document(&portable_document(&config, &filter));
    let projection = projection_for(&config, &filter);

    // The exact states, so a coincidental agreement is not enough.
    let expected_states = vec![
        ("i-alpha", "complete"),
        ("i-partial", "partial"),
        ("i-missing", "missing_reference"),
        ("i-empty", "empty"),
        ("i-zero", "complete"),
        ("i-unknown", "unknown"),
        ("i-undated", "complete"),
    ];
    assert_eq!(
        tui_rows
            .iter()
            .map(|r| (r.id.as_str(), r.state.as_str()))
            .collect::<Vec<_>>(),
        expected_states
    );

    // Contributions (provenance, resolution, policy version) agree by value.
    for (cli, tui, mcp_row, portable) in zip_four(&cli_rows, &tui_rows, &mcp_rows, &portable_rows) {
        assert_eq!(
            cli.contributions, tui.contributions,
            "contributions differ for `{}`",
            cli.id
        );
        assert_eq!(cli.contributions, mcp_row.contributions, "{}", cli.id);
        assert_eq!(cli.contributions, portable.contributions, "{}", cli.id);
    }

    // The provenance each surface reports is exactly the projection's, and the
    // policy version is the shared health policy's.
    for row in &projection.initiatives {
        let view = tui_rows.iter().find(|v| v.id == row.id).unwrap();
        let expected: Vec<Contribution> = row
            .summary
            .contributions
            .iter()
            .map(|c| Contribution {
                source_entity: c.source_entity(),
                resolution: c.resolution.as_str().to_string(),
                policy_version: c.policy_version.clone(),
            })
            .collect();
        assert_eq!(view.contributions, expected, "provenance for `{}`", row.id);
        assert!(
            row.summary
                .policy_versions
                .iter()
                .all(|version| version == tix::health::HEALTH_POLICY_VERSION),
            "every policy version is the shared health policy's: {:?}",
            row.summary.policy_versions
        );
    }

    // The diagnostic *kinds* agree on all four surfaces; the structured three also
    // agree on the field and reference each finding names.
    for (cli, tui, mcp_row, portable) in zip_four(&cli_rows, &tui_rows, &mcp_rows, &portable_rows) {
        assert_eq!(
            cli.diagnostic_kinds(),
            tui.diagnostic_kinds(),
            "diagnostic kinds for `{}`",
            cli.id
        );
        assert_eq!(
            cli.diagnostic_kinds(),
            mcp_row.diagnostic_kinds(),
            "{}",
            cli.id
        );
        assert_eq!(
            cli.diagnostic_kinds(),
            portable.diagnostic_kinds(),
            "{}",
            cli.id
        );
        assert_eq!(tui.diagnostics, mcp_row.diagnostics, "{}", cli.id);
        assert_eq!(tui.diagnostics, portable.diagnostics, "{}", cli.id);
    }
}

// ---------------------------------------------------------------------------
// C-004 — the summary is a join of owning services, never a blend
// ---------------------------------------------------------------------------

#[test]
fn c004_each_contribution_equals_its_owning_service_and_no_surface_adds_a_figure() {
    let (_tmp, config) = parity_fixture();
    let store = store_for(&config);
    let issues = store.list_all().unwrap();
    let sources = tix::commands::roadmap::build_sources(&config, &store, &issues).unwrap();
    let projection = tix::roadmap::project(&config, &sources, &RoadmapFilter::default()).unwrap();

    // Fresh indices and graph over the same snapshot: the "called directly" side.
    let fresh_projects = ProjectIndex::build(&config, &issues);
    let fresh_epics = EpicIndex::build(&config, &issues);
    let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
    let graph = RelationshipGraph::new(&views, &sources.consumed.done_column);

    let mut checked = 0usize;
    for row in &projection.initiatives {
        for contribution in &row.summary.contributions {
            match &contribution.progress {
                Some(ProgressValue::Project(report)) => {
                    let direct = fresh_projects
                        .health(
                            &config,
                            &contribution.target,
                            &sources.consumed.assigned,
                            &sources.consumed.overdue,
                            &sources.consumed.blocked,
                        )
                        .expect("the owning project service values the reference");
                    assert_eq!(
                        (report.progress.done, report.progress.total),
                        (direct.progress.done, direct.progress.total),
                        "the projection's project figure is the service's, for `{}`",
                        contribution.target
                    );
                    assert_eq!(
                        report.health.overdue, direct.health.overdue,
                        "the projection forwards the service's health counts"
                    );
                    checked += 1;
                }
                Some(ProgressValue::Epic(rollup)) => {
                    let direct = fresh_epics
                        .rollup(
                            &config,
                            &contribution.target,
                            &sources.consumed.targets,
                            &graph,
                        )
                        .expect("the owning epic service values the reference");
                    assert_eq!(
                        (rollup.progress.done, rollup.progress.total),
                        (direct.progress.done, direct.progress.total),
                        "the projection's epic figure is the service's, for `{}`",
                        contribution.target
                    );
                    checked += 1;
                }
                None => {}
            }
        }
    }
    assert!(checked >= 4, "the fixture exercises both owning services");

    // The only aggregate is a **count of contributions**, never a rate or score.
    for row in &projection.initiatives {
        let knowable = row
            .summary
            .contributions
            .iter()
            .filter(|c| c.is_knowable())
            .count();
        assert_eq!(
            row.summary.knowable_contributions(),
            knowable,
            "the summary's only aggregate is a count of knowable contributions"
        );
        let resolved = row
            .summary
            .contributions
            .iter()
            .filter(|c| c.resolution.is_resolved())
            .count();
        assert_eq!(
            row.summary.source_entities.len(),
            resolved,
            "one provenance entry per resolved contribution, no more"
        );
    }

    // No surface invents a figure: the portable document's values are the
    // projection's, contribution for contribution.
    let document = portable_document(&config, &RoadmapFilter::default());
    for (row, portable_row) in projection.initiatives.iter().zip(&document.rows) {
        assert_eq!(row.id, portable_row.id);
        for (contribution, portable) in row
            .summary
            .contributions
            .iter()
            .zip(&portable_row.summary.contributions)
        {
            let expected = match &contribution.progress {
                Some(ProgressValue::Project(report)) => {
                    Some((report.progress.done, report.progress.total))
                }
                Some(ProgressValue::Epic(rollup)) => {
                    Some((rollup.progress.done, rollup.progress.total))
                }
                None => None,
            };
            let actual = portable.value.map(|value| (value.done, value.total));
            assert_eq!(
                actual, expected,
                "the document's value for `{}` is the service's, not a blend",
                portable.source_entity
            );
        }
    }
}

// ---------------------------------------------------------------------------
// NFR-002 — stable ids and idempotence
// ---------------------------------------------------------------------------

#[test]
fn nfr002_a_stable_id_survives_a_round_trip_and_a_rename() {
    let (tmp, config) = parity_fixture();
    let store = store_for(&config);

    // The reference is the stable id, and its associations are intact.
    let (stdout, stderr, ok) = cli(&tmp, &["initiative", "show", "i-alpha"]);
    assert!(ok, "initiative show failed: {stderr}");
    assert!(stdout.contains("id: i-alpha"), "{stdout}");
    assert!(stdout.contains("projects: p-alpha"), "{stdout}");
    assert!(stdout.contains("epics: e-alpha"), "{stdout}");

    // A rename is a label change only: the id is the same one the MCP tool reports.
    let renamed = mcp(
        &config,
        &store,
        "update_initiative",
        json!({ "initiative": "i-alpha", "name": "Alpha renamed" }),
    );
    assert!(!mcp_is_error(&renamed), "update_initiative failed");
    assert_eq!(
        mcp_structured(&renamed)["id"].as_str(),
        Some("i-alpha"),
        "the id is unchanged by a rename"
    );

    // Round trip through disk: the id, its associations and the new label reload.
    let reloaded = Config::load(tmp.path()).unwrap();
    let record = reloaded
        .initiatives
        .get("i-alpha")
        .expect("the id is still the registry key");
    assert_eq!(record.name, "Alpha renamed");
    assert_eq!(record.projects, vec!["p-alpha".to_string()]);
    assert_eq!(record.epics, vec!["e-alpha".to_string()]);
    assert_eq!(record.milestones, vec!["M-live".to_string()]);

    // And the surfaces agree: the listing shows the id, resolving by name lands on
    // the same id.
    let (listing, stderr, ok) = cli(&tmp, &["initiative", "list"]);
    assert!(ok, "initiative list failed: {stderr}");
    assert!(
        listing.contains("i-alpha\tAlpha renamed"),
        "the id is a column of its own: {listing}"
    );
    let (shown, _, ok) = cli(&tmp, &["initiative", "show", "Alpha renamed"]);
    assert!(ok);
    assert!(shown.contains("id: i-alpha"), "{shown}");
}

#[test]
fn nfr002_repeated_associations_and_dereferences_are_idempotent_on_every_surface() {
    let (tmp, config) = parity_fixture();
    let store = store_for(&config);

    // A first associate writes; the second is a no-op that writes no byte.
    let (_, stderr, ok) = cli(
        &tmp,
        &["initiative", "associate", "i-alpha", "--project", "p-beta"],
    );
    assert!(ok, "associate failed: {stderr}");
    let after_first = snapshot(tmp.path());

    let (_, _, ok) = cli(
        &tmp,
        &["initiative", "associate", "i-alpha", "--project", "p-beta"],
    );
    assert!(ok);
    assert_eq!(
        snapshot(tmp.path()),
        after_first,
        "a repeated CLI association writes nothing"
    );

    // MCP: an already-recorded association reports `changed: false` and writes
    // nothing; a dereference of an absent association is the same no-op.
    let repeat = mcp(
        &config,
        &store,
        "initiative_associate",
        json!({ "initiative": "i-alpha", "kind": "project", "target": "p-alpha" }),
    );
    assert!(!mcp_is_error(&repeat));
    assert_eq!(mcp_structured(&repeat)["changed"], json!(false));
    assert_eq!(
        snapshot(tmp.path()),
        after_first,
        "MCP repeat writes nothing"
    );

    let absent = mcp(
        &config,
        &store,
        "initiative_dereference",
        json!({ "initiative": "i-alpha", "kind": "project", "target": "p-gamma" }),
    );
    assert!(!mcp_is_error(&absent));
    assert_eq!(mcp_structured(&absent)["changed"], json!(false));
    assert_eq!(
        snapshot(tmp.path()),
        after_first,
        "a no-op dereference writes nothing"
    );
}

// ---------------------------------------------------------------------------
// NFR-001 — aggregation over 10,000 entities, excluding file I/O
// ---------------------------------------------------------------------------

/// `count` in-memory initiatives, each referencing one project and one epic, with
/// one issue per project/epic so the index build is genuinely O(`count`).
fn large_fixture(count: u32) -> (Config, Vec<Issue>) {
    let mut config = Config::default();
    let mut issues = Vec::with_capacity(count as usize);
    for index in 0..count {
        let project = format!("p-{index:05}");
        let epic = format!("e-{index:05}");
        config.projects.insert(
            project.clone(),
            ProjectConfiguration {
                name: format!("Project {index}"),
                ..ProjectConfiguration::default()
            },
        );
        config.epics.insert(
            epic.clone(),
            EpicConfiguration {
                name: format!("Epic {index}"),
                ..EpicConfiguration::default()
            },
        );
        config.initiatives.insert(
            format!("i-{index:05}"),
            InitiativeConfiguration {
                name: format!("Initiative {index}"),
                target_date: Some(format!(
                    "2026-{:02}-{:02}",
                    (index % 12) + 1,
                    (index % 28) + 1
                )),
                projects: vec![project.clone()],
                epics: vec![epic.clone()],
                ..InitiativeConfiguration::default()
            },
        );
        let number = index + 1;
        let raw = format!(
            "---\nnumber: {number}\ntitle: \"Issue {number}\"\nstatus: \"todo\"\n\
             projects: [\"{project}\"]\nepics: [\"{epic}\"]\n\
             created: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody.\n"
        );
        let mut parsed = Issue::parse(&raw).expect("the fixture parses");
        parsed.filename = format!("issue-{number}.md");
        issues.push(parsed);
    }
    (config, issues)
}

#[test]
fn nfr001_aggregation_over_ten_thousand_entities_is_one_indexed_pass() {
    let _performance = super::serialized_performance_test();
    const COUNT: usize = 10_000;
    let (config, issues) = large_fixture(COUNT as u32);
    let filter = RoadmapFilter::default();

    // (a) The **full in-memory read** the contract bounds: load the registries and
    // their indexes once, join by stable id, sort once. File I/O is excluded — the
    // config and the issues are built in memory.
    let started = Instant::now();
    let sources = RoadmapSources::new(
        &config,
        &issues,
        &HealthPolicy::v1(),
        RoadmapConsumed::default(),
    );
    let projection = tix::roadmap::project(&config, &sources, &filter).expect("the projection");
    let full_read = started.elapsed();

    // Exact structural figures, so a fast-but-wrong join cannot pass.
    assert_eq!(projection.total, COUNT, "every initiative is a row");
    assert_eq!(projection.initiatives.len(), COUNT);
    let contributions: usize = projection
        .initiatives
        .iter()
        .map(|row| row.summary.contributions.len())
        .sum();
    assert_eq!(contributions, COUNT * 2, "one contribution per reference");
    let sources_reported: usize = projection
        .initiatives
        .iter()
        .map(|row| row.summary.source_entities.len())
        .sum();
    assert_eq!(sources_reported, COUNT * 2, "every contribution resolves");
    assert!(
        projection
            .initiatives
            .iter()
            .all(|row| row.summary.state == SummaryState::Complete),
        "every reference resolves to a source with a knowable value"
    );
    assert!(
        projection.diagnostics.is_empty(),
        "no findings in this fixture"
    );

    // (b) The **join alone**, against the snapshot already built: the pass a
    // rebuild-per-call would blow up.
    let started = Instant::now();
    let joined = tix::roadmap::project(&config, &sources, &filter).expect("the projection");
    let join = started.elapsed();
    assert_eq!(joined.total, projection.total);

    // (c) One index build, measured back to back, for the ratio below.
    let started = Instant::now();
    let one_build = ProjectIndex::build(&config, &issues);
    let build = started.elapsed();
    assert_eq!(
        one_build.buckets().len(),
        COUNT,
        "one build over 10,000 projects"
    );

    // **Falsifiable assertion 1 — no rebuild-per-call.** The join must cost a small
    // multiple of *one* index build. Rebuilding the project/epic/health index for
    // every row costs roughly 10,000 builds and cannot satisfy this.
    assert!(
        join < build * 500,
        "the join over {COUNT} entities took {join:?} against one index build in {build:?}; \
         it is rebuilding the index per row rather than joining once"
    );

    // **Falsifiable assertion 2 — no per-row rescan.** One indexed pass is linear, so
    // doubling the entity count roughly doubles the work; an O(N²) per-row rescan
    // roughly quadruples it. The half-size read is measured back to back with the
    // full-size one — the two `project` calls only, not the fixture build — so machine
    // load moves them together and the factor stays meaningful. A factor of 3 sits
    // between linear (~2) and quadratic (~4).
    let (half_config, half_issues) = large_fixture((COUNT / 2) as u32);
    let half_sources = RoadmapSources::new(
        &half_config,
        &half_issues,
        &HealthPolicy::v1(),
        RoadmapConsumed::default(),
    );
    let started = Instant::now();
    let half = tix::roadmap::project(&half_config, &half_sources, &filter).expect("the projection");
    let half_join = started.elapsed();
    assert_eq!(half.total, COUNT / 2, "the half-size read is a full read");
    assert!(
        join < half_join * 3,
        "the join over {COUNT} entities took {join:?} against {half_join:?} over {}; doubling \
         the entity count must roughly double the work, so this is super-linear — a per-row \
         rescan rather than one indexed pass",
        COUNT / 2
    );

    // The contract's budget: the full in-memory read (index load + join + sort) targets
    // 500 ms excluding file I/O. The observed cost is a few hundred milliseconds, so
    // this bounds the whole read and not just the join; the two assertions above are
    // the hard, falsifiable checks.
    assert!(
        full_read.as_millis() < 500,
        "the full 10,000-entity in-memory read (index load + join + sort) took {full_read:?}, \
         past the NFR-001 budget of 500 ms excluding file I/O"
    );
    println!(
        "NFR-001: 10,000 entities ({COUNT} initiatives, {contributions} contributions) — \
         full in-memory read {full_read:?}, join alone {join:?}, half-size join {half_join:?}, \
         one ProjectIndex build {build:?} (budget 500 ms, file I/O excluded)"
    );
}

// ---------------------------------------------------------------------------
// C-005 / C-006 — missing, empty and zero stay distinct and visible
// ---------------------------------------------------------------------------

#[test]
fn c005_a_missing_reference_stays_visible_on_every_surface() {
    let (tmp, config) = parity_fixture();
    let store = store_for(&config);
    let filter = RoadmapFilter::default();

    // CLI: the row is present, its provenance names the missing reference and its
    // resolution is `[missing]` — never dropped and never a zero.
    let (stdout, stderr, ok) = cli_args(&tmp, &cli_filter_args(&filter));
    assert!(ok, "{stderr}");
    assert!(
        stdout.contains("project:p-ghost-initiative") && stdout.contains("[missing]"),
        "the CLI row shows the missing reference: {stdout}"
    );
    let (shown, _, ok) = cli(&tmp, &["roadmap", "show", "i-missing"]);
    assert!(ok);
    assert!(shown.contains("[missing]"), "{shown}");

    // TUI: the projection row and the tab's own detail rendering.
    let tui = tui_projection(&config, &filter);
    let row = tui
        .initiatives
        .iter()
        .find(|row| row.id == "i-missing")
        .expect("the missing-reference row is present");
    assert_eq!(row.summary.state, SummaryState::MissingReference);
    assert!(
        row.references.iter().all(|r| !r.resolution.is_resolved()),
        "every reference is missing, none dropped"
    );
    let detail = tix::commands::roadmap::roadmap_row_lines(row).join("\n");
    assert!(detail.contains("[missing]"), "{detail}");

    // MCP: the structured references and diagnostics preserve it.
    let mcp_rows = views_from_mcp(&config, &store, &filter);
    let mcp_row = mcp_rows.iter().find(|r| r.id == "i-missing").unwrap();
    assert!(
        mcp_row
            .contributions
            .iter()
            .all(|c| c.resolution == "missing"),
        "{mcp_row:?}"
    );
    assert!(
        mcp_row
            .diagnostics
            .iter()
            .any(|d| d.kind == "missing_reference"
                && d.reference.as_deref() == Some("p-ghost-initiative")),
        "{mcp_row:?}"
    );

    // Portable: the document keeps the missing resolution and the finding.
    let document = portable_document(&config, &filter);
    let portable_row = document.rows.iter().find(|r| r.id == "i-missing").unwrap();
    assert_eq!(portable_row.summary.state, "missing_reference");
    assert!(
        portable_row
            .references
            .iter()
            .all(|r| r.resolution == "missing")
    );
    assert!(
        portable_row
            .diagnostics
            .iter()
            .any(|d| d.kind == "missing_reference"
                && d.reference.as_deref() == Some("p-ghost-initiative")),
        "{:?}",
        portable_row.diagnostics
    );

    // And the missing-reference initiative never disappears from the ordered set on
    // any surface.
    for rows in [
        views_from_cli(&stdout),
        views_from_projection(&tui),
        mcp_rows,
        views_from_document(&document),
    ] {
        assert!(ids(&rows).contains(&"i-missing"), "{rows:?}");
    }
}

#[test]
fn c006_empty_unknown_and_zero_are_distinct_states_on_every_surface() {
    let (tmp, config) = parity_fixture();
    let store = store_for(&config);
    let filter = RoadmapFilter::default();

    let (stdout, stderr, ok) = cli_args(&tmp, &cli_filter_args(&filter));
    assert!(ok, "{stderr}");
    let cli_rows = views_from_cli(&stdout);
    let tui_rows = views_from_projection(&tui_projection(&config, &filter));
    let mcp_rows = views_from_mcp(&config, &store, &filter);
    let portable_rows = views_from_document(&portable_document(&config, &filter));
    let projection = projection_for(&config, &filter);

    let state_of = |rows: &[RowView], id: &str| -> String {
        rows.iter().find(|r| r.id == id).unwrap().state.clone()
    };
    for rows in [&cli_rows, &tui_rows, &mcp_rows, &portable_rows] {
        assert_eq!(
            state_of(rows, "i-empty"),
            "empty",
            "the empty state is explicit"
        );
        assert_eq!(state_of(rows, "i-unknown"), "unknown");
        assert_eq!(
            state_of(rows, "i-zero"),
            "complete",
            "zero progress is a value"
        );
    }

    // The explicit empty state is a finding, not a bare header.
    let empty_row = tui_rows.iter().find(|r| r.id == "i-empty").unwrap();
    assert!(empty_row.contributions.is_empty());
    assert!(empty_row.diagnostic_kinds().contains(&"empty_scope"));
    assert!(
        stdout.contains("empty: no source references"),
        "the CLI prints its explicit empty state: {stdout}"
    );
    assert!(
        tui_rows
            .iter()
            .find(|r| r.id == "i-unknown")
            .unwrap()
            .diagnostic_kinds()
            .contains(&"unknown_value"),
        "every reference resolving to nothing knowable is `unknown`"
    );

    // Zero is a **figure**: the zero-progress project reports `0/0`, present on
    // every surface, while the empty and unknown rows report no figure at all.
    let zero_row = projection
        .initiatives
        .iter()
        .find(|row| row.id == "i-zero")
        .unwrap();
    let zero_contribution = &zero_row.summary.contributions[0];
    match &zero_contribution.progress {
        Some(ProgressValue::Project(report)) => {
            assert_eq!((report.progress.done, report.progress.total), (0, 0));
        }
        other => panic!("the zero-progress project carries a value, got {other:?}"),
    }
    assert!(
        stdout.contains("progress=0/0"),
        "the CLI prints the zero figure rather than a dash: {stdout}"
    );
    let mcp_zero = mcp_rows.iter().find(|r| r.id == "i-zero").unwrap();
    assert_eq!(mcp_zero.contributions.len(), 1);
    let document = portable_document(&config, &filter);
    let portable_zero = document.rows.iter().find(|r| r.id == "i-zero").unwrap();
    assert_eq!(
        portable_zero.summary.contributions[0].value,
        Some(tix::roadmap::portable::PortableValue { done: 0, total: 0 }),
        "the document carries the genuine zero, not `None`"
    );
    // `None` is reserved for "no value" (the empty/unknown rows), so zero is never
    // conflated with it.
    let portable_empty = document.rows.iter().find(|r| r.id == "i-empty").unwrap();
    assert!(portable_empty.summary.contributions.is_empty());
}

// ---------------------------------------------------------------------------
// C-008 — a rejected mutation writes nothing, on every verb
// ---------------------------------------------------------------------------

#[test]
fn c008_every_rejected_mutation_leaves_the_tree_byte_identical() {
    let (tmp, config) = parity_fixture();
    let store = store_for(&config);
    let before = snapshot(tmp.path());

    // Each rejection is `(label, args)`; every one must fail and write nothing.
    let cli_rejections: Vec<(&str, Vec<&str>)> = vec![
        (
            "create duplicate name",
            vec!["initiative", "create", "Alpha portfolio"],
        ),
        (
            "create malformed project id",
            vec!["initiative", "create", "New", "--projects", "not an id!"],
        ),
        (
            "edit with no field flag",
            vec!["initiative", "edit", "i-alpha"],
        ),
        (
            "edit malformed target date",
            vec![
                "initiative",
                "edit",
                "i-alpha",
                "--target-date",
                "2026-13-01",
            ],
        ),
        (
            "delete unknown id",
            vec!["initiative", "delete", "nosuch", "--yes"],
        ),
        (
            "associate malformed target",
            vec![
                "initiative",
                "associate",
                "i-alpha",
                "--project",
                "not an id!",
            ],
        ),
        (
            "associate unknown initiative",
            vec!["initiative", "associate", "nosuch", "--project", "p-alpha"],
        ),
        (
            "associate with no kind flag",
            vec!["initiative", "associate", "i-alpha"],
        ),
        (
            "dereference malformed target",
            vec![
                "initiative",
                "dereference",
                "i-alpha",
                "--project",
                "not an id!",
            ],
        ),
    ];
    for (label, args) in cli_rejections {
        let (_, stderr, ok) = cli(&tmp, &args);
        assert!(!ok, "refusal expected: {label}");
        assert!(!stderr.is_empty(), "refusal must say why: {label}");
        assert_eq!(
            snapshot(tmp.path()),
            before,
            "{label}: wrote a byte (tix.toml must stay identical and append nothing)"
        );
    }

    // The same on every MCP mutating tool: each refusal is a tool error, not a write.
    let mcp_rejections: Vec<(&str, &str, Value)> = vec![
        (
            "create_initiative duplicate",
            "create_initiative",
            json!({ "name": "Alpha portfolio" }),
        ),
        (
            "update_initiative with no fields",
            "update_initiative",
            json!({ "initiative": "i-alpha" }),
        ),
        (
            "delete_initiative without confirm",
            "delete_initiative",
            json!({ "initiative": "i-alpha" }),
        ),
        (
            "delete_initiative unknown id",
            "delete_initiative",
            json!({ "initiative": "nosuch", "confirm": true }),
        ),
        (
            "initiative_associate bad kind",
            "initiative_associate",
            json!({ "initiative": "i-alpha", "kind": "label", "target": "x" }),
        ),
        (
            "initiative_associate malformed target",
            "initiative_associate",
            json!({ "initiative": "i-alpha", "kind": "project", "target": "not an id!" }),
        ),
        (
            "initiative_dereference unknown initiative",
            "initiative_dereference",
            json!({ "initiative": "nosuch", "kind": "project", "target": "p-alpha" }),
        ),
    ];
    for (label, tool, args) in mcp_rejections {
        let result = mcp(&config, &store, tool, args);
        assert!(mcp_is_error(&result), "refusal expected: {label}: {result}");
        assert_eq!(snapshot(tmp.path()), before, "{label}: wrote a byte");
    }
}

// ---------------------------------------------------------------------------
// The lint boundary — config-held initiative references are not a lint family
// ---------------------------------------------------------------------------

#[test]
fn boundary_lint_reports_issue_held_references_but_not_initiative_references() {
    let (_tmp, config) = parity_fixture();
    let store = store_for(&config);
    let findings = tix::commands::lint::collect(&config, &store).unwrap();

    // The issue-held dangling project is reported, under the service's own kind.
    assert!(
        findings.iter().any(|finding| {
            finding.kind == tix::projects::MISSING_REFERENCE_KIND
                && finding.value == "p-ghost-issue"
        }),
        "lint reports the issue-held dangling project: {findings:#?}"
    );

    // The initiative's config-held reference is *not* a lint finding: it is
    // diagnosed on the roadmap surfaces (row, detail and the ordered diagnostics).
    assert!(
        !findings
            .iter()
            .any(|finding| finding.value == "p-ghost-initiative"
                || finding.message.contains("p-ghost-initiative")),
        "lint does not report an initiative's config-held reference: {findings:#?}"
    );
    // The roadmap surfaces do, which is the boundary the docs record.
    let row = projection_for(&config, &RoadmapFilter::default())
        .initiatives
        .into_iter()
        .find(|row| row.id == "i-missing")
        .unwrap();
    assert!(row.diagnostics.iter().any(|finding| {
        finding.kind.as_str() == "missing_reference"
            && finding.reference.as_deref() == Some("p-ghost-initiative")
    }));
}