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
#[allow(clippy::wildcard_imports)]
use super::*;

#[test]
fn target_parsing_accepts_only_the_two_contract_targets() {
    assert_eq!(Tool::from_target("gitlab").unwrap(), Tool::GitLab);
    assert_eq!(Tool::from_target("linear").unwrap(), Tool::Linear);
    assert!(Tool::from_target("github").is_err());
    assert_eq!(Tool::GitLab.token_var(), "GITLAB_TOKEN");
    assert_eq!(Tool::Linear.token_var(), "LINEAR_TOKEN");
    assert_eq!(Tool::GitLab.binary(), "glab");
    assert_eq!(Tool::Linear.binary(), "linear-cli");
}

#[test]
fn gitlab_status_mapping() {
    let config = Config::default();
    assert_eq!(
        local_to_remote_status(Tool::GitLab, "todo", &config),
        "opened"
    );
    assert_eq!(
        local_to_remote_status(Tool::GitLab, "done", &config),
        "closed"
    );
    assert_eq!(
        remote_to_local_status(Tool::GitLab, "opened", &config),
        "todo"
    );
    assert_eq!(
        remote_to_local_status(Tool::GitLab, "closed", &config),
        "done"
    );
    assert_eq!(
        remote_to_local_status(Tool::GitLab, "anything-else", &config),
        "todo"
    );
}

#[test]
fn linear_status_mapping() {
    let config = Config::default();
    assert_eq!(
        local_to_remote_status(Tool::Linear, "todo", &config),
        "todo"
    );
    assert_eq!(
        local_to_remote_status(Tool::Linear, "in review", &config),
        "todo"
    );
    assert_eq!(
        local_to_remote_status(Tool::Linear, "done", &config),
        "Done"
    );
    assert_eq!(
        remote_to_local_status(Tool::Linear, "In Progress", &config),
        "in progress"
    );
    assert_eq!(
        remote_to_local_status(Tool::Linear, "Done", &config),
        "done"
    );
    assert_eq!(
        remote_to_local_status(Tool::Linear, "Unknown", &config),
        "todo"
    );
}

#[test]
fn days_from_civil_roundtrips_civil_from_days() {
    // spot-check independent epoch anchors (known values)
    assert_eq!(days_from_civil(1970, 1, 1), 0);
    assert_eq!(days_from_civil(2000, 1, 1), 10957);
    assert_eq!(days_from_civil(1970, 1, 2), 1);
    assert_eq!(days_from_civil(2026, 5, 11), 20584);
}

#[test]
fn date_to_epoch_days_parses_only_yyyymmdd() {
    assert_eq!(date_to_epoch_days("1970-01-01"), Some(0));
    assert_eq!(date_to_epoch_days("2026-05-11"), Some(20_584));
    assert_eq!(date_to_epoch_days("not-a-date"), None);
    assert_eq!(date_to_epoch_days("2026-13-01"), None);
    assert_eq!(date_to_epoch_days("2026-05-11T10:00:00"), None);
}

#[test]
fn iso_to_epoch_secs_accepts_contract_timestamp_shapes() {
    let day = days_from_civil(2026, 5, 11) * 86_400;
    assert_eq!(iso_to_epoch_secs("2026-05-11T00:00:00Z"), Some(day));
    assert_eq!(iso_to_epoch_secs("2026-05-11 00:00:00"), Some(day));
    assert_eq!(iso_to_epoch_secs("2026-05-11T00:00:00.123Z"), Some(day));
    assert_eq!(
        iso_to_epoch_secs("2026-05-11T00:00:00+02:00"),
        Some(day - 7200)
    );
    assert_eq!(
        iso_to_epoch_secs("2026-05-11T00:00:00-05:30"),
        Some(day + 19_800)
    );
    assert_eq!(
        iso_to_epoch_secs("2026-05-11T10:30:00Z"),
        Some(day + 37_800)
    );
    assert_eq!(iso_to_epoch_secs("garbage"), None);
}

#[test]
fn remote_newer_wins_only_when_strictly_after_local_end_of_day() {
    // local `updated` = 2026-05-11 is interpreted as end of day.
    assert!(is_remote_newer("2026-05-12T00:00:00Z", "2026-05-11"));
    assert!(!is_remote_newer("2026-05-11 13:00:00", "2026-05-11"));
    assert!(!is_remote_newer("2026-05-11T23:59:59Z", "2026-05-11"));
    assert!(!is_remote_newer("2026-05-10T23:59:59Z", "2026-05-11"));
    // unparseable remote timestamp keeps the local issue
    assert!(!is_remote_newer("not-a-time", "2026-05-11"));
}

#[test]
fn scrub_replaces_secret_everywhere_and_preserves_text() {
    assert_eq!(
        scrub_secret("token=sekrit end", "sekrit"),
        "token=<token> end"
    );
    assert_eq!(
        scrub_secret("token=sekrit token=sekrit", "sekrit"),
        "token=<token> token=<token>"
    );
    assert_eq!(scrub_secret("no secret here", "sekrit"), "no secret here");
    assert_eq!(scrub_secret("empty secret", ""), "empty secret");
}

// ---- WP07 T029: the relationship mapping seam ----

fn rel(kind: crate::relationships::RelationKind) -> crate::relationships::Relationship {
    let mut r = crate::relationships::Relationship::new(1, 2, kind, "Ship it");
    r.id = "rel_TEST".to_string();
    r
}

/// Every relationship either maps or diagnoses, and the diagnostic
/// distinguishes the reasons (T029 step 5, re-pointed once Linear's
/// `relations add` was verified).
///
/// - `blocks`/`blocked_by` for **Linear** — expressible in the model and
///   drivable from the CLI, so they **map**, carrying the target's remote
///   identifier.
/// - `blocks`/`blocked_by` for **GitLab** — expressible in the model but the
///   CLI is **verified to have no relation command at all** (tix #1354), so it
///   diagnoses and says *that*, never "not verified".
/// - `related`/`duplicates` — no remote field at all.
#[test]
fn every_relationship_maps_only_where_the_wire_is_verified_and_otherwise_diagnoses() {
    for tool in [Tool::GitLab, Tool::Linear] {
        for kind in [
            crate::relationships::RelationKind::Blocks,
            crate::relationships::RelationKind::BlockedBy,
            crate::relationships::RelationKind::Related,
            crate::relationships::RelationKind::Duplicates,
        ] {
            let model_supports = matches!(
                kind,
                crate::relationships::RelationKind::Blocks
                    | crate::relationships::RelationKind::BlockedBy
            );
            match map_relation_to_remote(tool, &rel(kind), Some("ENG-42")) {
                MappedRelation::Remote { field, value } => {
                    assert!(
                        model_supports && RELATION_WIRE_VERIFIED.contains(&tool),
                        "{tool}/{kind} mapped, so the tool must model the kind and \
                         be on the verified wire"
                    );
                    assert_ne!(field, "");
                    if tool == Tool::Linear {
                        assert_eq!(
                            value, "ENG-42",
                            "Linear sends the target's remote identifier"
                        );
                    } else {
                        assert!(value.contains('#'));
                    }
                }
                MappedRelation::Unsupported(d) => {
                    assert!(
                        !RELATION_WIRE_VERIFIED.contains(&tool) || !model_supports,
                        "{tool}/{kind} is on the verified wire and modelled, so it \
                         must map, not diagnose"
                    );
                    assert_eq!(d.tool, tool, "the diagnostic names the tool");
                    assert_eq!(d.relation_id, "rel_TEST");
                    assert!(
                        !d.field.is_empty(),
                        "the diagnostic must name the specific field: {d}"
                    );
                    assert!(d.to_string().contains(&d.field), "and print it: {d}");
                    if model_supports {
                        assert!(
                            RELATION_CLI_ABSENT.contains(&tool)
                                && d.message.contains("exposes no issue-relation command")
                                && !d.message.contains("not verified"),
                            "{tool}/{kind}: a model-supported kind on an unverified \
                             tool must name the real reason; a CLI verified to have \
                             no relation command must say so, not 'not verified': {d}"
                        );
                    } else {
                        assert!(
                            !d.message.contains("not verified"),
                            "{tool}/{kind}: a kind with no remote field must not \
                             blame an unverified verb: {d}"
                        );
                    }
                }
            }
        }
    }
}

/// A blocking edge whose target has no remote reference is **reported, never
/// guessed** (C-005): Linear's `relations add` needs the target's remote
/// identifier, and inventing one would be worse than a diagnostic.
#[test]
fn a_relation_without_a_remote_target_is_reported_not_guessed() {
    let MappedRelation::Unsupported(d) = map_relation_to_remote(
        Tool::Linear,
        &rel(crate::relationships::RelationKind::Blocks),
        None,
    ) else {
        panic!("a missing target must not map");
    };
    assert_eq!(d.tool, Tool::Linear);
    assert_eq!(d.field, "blocks");
    assert!(
        d.message.contains("#2") && d.message.contains("not been exported"),
        "the diagnostic names the target and why: {d}"
    );
}

/// The forward and reverse directions agree about the verified list.
///
/// The reverse direction must **not** invent an edge from a payload the forward
/// direction would never have written — otherwise an import could create a
/// relationship the export never made, which is the mirror image of the silent
/// drop the contract forbids. So it maps exactly when the wire is verified.
#[test]
fn the_reverse_direction_maps_exactly_when_the_wire_is_verified() {
    for tool in [Tool::GitLab, Tool::Linear] {
        let field = match tool {
            Tool::GitLab => "blocking",
            Tool::Linear => "blocks",
        };
        match map_relation_from_remote(tool, field, "blocks #2", "rel_TEST") {
            MappedRelation::Remote { .. } => assert!(
                RELATION_WIRE_VERIFIED.contains(&tool),
                "{tool}: the reverse direction mapped, so the wire must be verified"
            ),
            MappedRelation::Unsupported(d) => {
                assert!(
                    !RELATION_WIRE_VERIFIED.contains(&tool),
                    "{tool}: the wire is verified, so the reverse direction must map"
                );
                assert_eq!(d.tool, tool);
                assert_ne!(d.relation_id, "");
            }
        }
    }
}

/// A remote payload the export could not have written is **ignored with a
/// diagnostic**, never turned into a local edge.
///
/// The alternative — coercing an unrecognised field to a default kind — would
/// let an import invent a relationship the export never made, which is the
/// mirror image of silently dropping a local one.
#[test]
fn an_unrecognised_remote_relation_field_never_becomes_a_local_edge() {
    for tool in [Tool::GitLab, Tool::Linear] {
        for (field, value) in [
            ("parent", "#2"),
            ("blocks", "not-a-number"),
            ("whatever", ""),
        ] {
            match map_relation_from_remote(tool, field, value, "rel_X") {
                MappedRelation::Remote { .. } => {
                    panic!("{tool}: `{field}={value}` must not become a local edge")
                }
                MappedRelation::Unsupported(d) => {
                    assert_eq!(d.tool, tool);
                    assert_eq!(d.field, field, "the diagnostic names the field");
                }
            }
        }
    }
}

/// The two adapters cannot drift: the seam is one function, keyed on `Tool`
/// (T033 step 5, and T029's note).
///
/// Asserted by construction — a single `map_relation_to_remote` serves both —
/// and pinned here so adding a tracker-specific branch to one of them is a
/// red test rather than a silent divergence.
#[test]
fn both_trackers_share_one_mapping_seam() {
    let source = concat!(include_str!("../mod.rs"), include_str!("../adapters.rs"));
    let fns = [
        "pub fn map_relation_to_remote",
        "pub fn map_relation_from_remote",
    ];
    for f in fns {
        assert_eq!(
            source.matches(&format!("{f}(")).count(),
            1,
            "{f} must be *defined* exactly once, in this module, for both \
             trackers — a doc comment naming it is not a second implementation"
        );
    }
    // And neither adapter file may define its own copy. `include_str!` needs a
    // literal, so the pair is spelled out rather than looped over.
    for (name, text) in [
        ("glab.rs", include_str!("../glab.rs")),
        ("linear.rs", include_str!("../linear.rs")),
    ] {
        assert!(
            !text.contains("fn map_relation_to_remote")
                && !text.contains("fn map_relation_from_remote"),
            "{name} must not define its own mapping seam; the shared one is \\
             keyed on `Tool` precisely so the two cannot diverge"
        );
    }
}

/// A `SyncReport` records the count and the diagnostics together, so a caller
/// cannot report success while quietly dropping a relationship.
#[test]
fn a_sync_report_carries_both_the_count_and_the_diagnostics() {
    let mut report = SyncReport::default().diagnostics_in_report();
    let mut sink: Vec<u8> = Vec::new();
    report
        .note(
            map_relation_to_remote(
                Tool::GitLab,
                &rel(crate::relationships::RelationKind::Related),
                None,
            ),
            &mut sink,
        )
        .unwrap();
    report
        .note(
            map_relation_to_remote(
                Tool::GitLab,
                &rel(crate::relationships::RelationKind::Blocks),
                None,
            ),
            &mut sink,
        )
        .unwrap();
    // Both are diagnostics: GitLab is not wire-verified, so the mapped
    // branch is unreachable and the count cannot be 1.
    let expected = if RELATION_WIRE_VERIFIED.contains(&Tool::GitLab) {
        1
    } else {
        2
    };
    assert_eq!(
        report.diagnostics.len(),
        expected,
        "the report records every relation the tool cannot carry"
    );
    assert_eq!(report.handled, 0, "no issues were handled here");
    // It is on the human stream too, so the count and the output agree.
    let text = String::from_utf8(sink).unwrap();
    assert!(
        text.contains("cannot represent"),
        "the stream says so: {text}"
    );
}
// ---- WP07 T032/T033: completion comes from the service, nowhere else ----

/// A board whose `category_map` puts `completed` on `shipped` while
/// `done_column` is `done` — so the two disagree, and a name comparison picks the
/// wrong one. Every assertion below is vacuous on the default board, which is why
/// this fixture exists rather than `Config::default()`.
fn split_completion_config() -> Config {
    Config {
        kanban: crate::config::KanbanSection {
            configurations: indexmap::IndexMap::from([(
                "default".to_string(),
                crate::config::BoardConfiguration {
                    columns: vec!["todo".into(), "shipped".into(), "done".into()],
                    done_column: Some("done".to_string()),
                    category_map: indexmap::IndexMap::from([
                        ("todo".to_string(), "unstarted".to_string()),
                        ("shipped".to_string(), "completed".to_string()),
                        ("done".to_string(), "active".to_string()),
                    ]),
                    ..Default::default()
                },
            )]),
        },
        ..Config::default()
    }
}

#[test]
fn t032_a_remote_closed_state_maps_to_the_services_completion_column() {
    // Not to `done_column`. The remote's `closed` must round-trip to the column
    // the *service* calls complete, or export and import disagree with each other
    // and with the board.
    let config = split_completion_config();
    assert_eq!(
        remote_to_local_status(Tool::GitLab, "closed", &config),
        "shipped",
        "a closed GitLab issue belongs in the column that is actually complete"
    );
    assert_eq!(
        remote_to_local_status(Tool::Linear, "Done", &config),
        "shipped"
    );
}

#[test]
fn t032_export_closes_the_column_the_service_calls_complete() {
    // The other direction. A name comparison exported `shipped` as *open* and
    // closed `done` instead — the tracker and the board disagreeing about the same
    // issue in both directions at once.
    let config = split_completion_config();
    assert_eq!(
        local_to_remote_status(Tool::GitLab, "shipped", &config),
        "closed"
    );
    assert_eq!(
        local_to_remote_status(Tool::GitLab, "done", &config),
        "opened"
    );
    assert_eq!(
        local_to_remote_status(Tool::Linear, "shipped", &config),
        "Done"
    );
}

#[test]
fn t032_a_closed_remote_state_mapped_to_a_canceled_column_is_not_complete() {
    // T033 step 4. `canceled` is terminal but **not** complete (contract §4), so
    // an export that sends a `canceled` column as closed would be claiming the
    // work is finished when it was abandoned. The local side is the service's
    // answer, so it says no.
    let mut config = split_completion_config();
    config
        .kanban
        .configurations
        .get_mut("default")
        .unwrap()
        .category_map
        .insert("done".to_string(), "canceled".to_string());
    let board = config.default_config();
    // `shipped` is still `completed`, so it still exports as closed…
    assert_eq!(
        local_to_remote_status(Tool::GitLab, "shipped", &config),
        "closed"
    );
    // …and `done` is now `canceled`, which is terminal and not complete, so it does
    // not. The remote has only two states, so the honest outcome is that `canceled`
    // cannot be represented distinctly — and the local definition is what decides,
    // not the remote's vocabulary.
    assert!(
        !is_done_column(board, "done", &config),
        "a canceled column is not locally complete"
    );
}

#[test]
fn t032_the_existing_round_trips_are_unchanged() {
    // T032 step 5: this is a refactor of *where the decision comes from*, not a
    // protocol change. The default board's behaviour must be identical.
    let config = Config::default();
    assert_eq!(
        local_to_remote_status(Tool::GitLab, "done", &config),
        "closed"
    );
    assert_eq!(
        local_to_remote_status(Tool::GitLab, "todo", &config),
        "opened"
    );
    assert_eq!(
        remote_to_local_status(Tool::GitLab, "closed", &config),
        "done"
    );
    assert_eq!(
        remote_to_local_status(Tool::Linear, "Done", &config),
        "done"
    );
    // "In Progress" case-insensitively matches the board's `in progress` column,
    // and a name match wins over the first column. The first draft of this
    // assertion expected `todo` — which is the *first* column, and therefore the
    // answer when no name matches. It was asserting the opposite rule to the one
    // it claimed to pin.
    assert_eq!(
        remote_to_local_status(Tool::Linear, "In Progress", &config),
        "in progress",
        "a name match wins over the first column"
    );
    assert_eq!(
        remote_to_local_status(Tool::Linear, "No Such State", &config),
        "todo",
        "and with no match at all, the first column"
    );
}

#[test]
fn t032_the_sync_seam_holds_no_local_completion_definition() {
    // T032 step 4, as a structural guard. The module header says a second local
    // definition is a C-004 defect, and this is what keeps that from being
    // "improved" back in: the seam may only *translate* a remote state word, and
    // the completion test may only come from the service.
    let source = concat!(include_str!("../mod.rs"), include_str!("../adapters.rs"));
    // Assembled from fragments so this assertion does not match **itself**: the
    // first version spelled the forbidden name out in full, so the very line
    // asserting its absence satisfied the check. That is the grep equivalent of a
    // test that proves itself, and it was found because the test went red while
    // the function was, in fact, absent.
    let forbidden = ["fn remote", "status_is_done"].concat();
    assert!(
        !source.contains(&forbidden),
        "the dead second definition is removed and must not come back"
    );
    // The only local completion question in the module is the service call.
    let uses_service = source.matches("WorkflowCategory::is_complete").count()
        + source.matches("completion_column_or_default").count();
    assert!(
        uses_service >= 2,
        "both `is_done_column` and `completion_column` must ask the service, found \
         {uses_service} uses"
    );
}

// ------------------------------------------------------------------
// WP08 (mission first-class-projects-01M3BYBW) — project associations
// ------------------------------------------------------------------

/// A representable association maps, and the reverse direction is
/// **local**-shaped: the frontmatter key and the id, not a copy of the tool's
/// field name (T035 step 1).
#[test]
fn t035_a_project_association_maps_back_to_its_local_id() {
    for tool in [Tool::GitLab, Tool::Linear] {
        let remote = RemoteProject {
            id: "p-1".to_string(),
            name: Some("One".to_string()),
        };
        match map_project_from_remote(tool, &remote) {
            MappedProject::Remote { field, value } => {
                assert_eq!(field, crate::projects::PROJECTS_KEY);
                assert_eq!(value, "p-1", "the id, never the remote's name");
            }
            MappedProject::Unsupported(d) => {
                panic!("{tool}: a reported id must map back: {d}")
            }
        }
    }
}

/// Every association diagnoses on both trackers, and the diagnostic names the
/// **field**, the **tool** and the issue — the three things that make it
/// actionable rather than a shrug (T035 step 6, C-005).
///
/// Written so it still holds if a tracker joins `PROJECT_WIRE_VERIFIED`: the
/// mapped branch is then the assertion, not the diagnostic's.
#[test]
fn t035_every_project_association_diagnoses_with_its_field_its_tool_and_its_reason() {
    for tool in [Tool::GitLab, Tool::Linear] {
        match map_project_to_remote(tool, 3, "p-7") {
            MappedProject::Remote { field, value } => {
                assert!(
                    PROJECT_WIRE_VERIFIED.contains(&tool),
                    "{tool}: an association mapped without a verified membership field"
                );
                assert_eq!(field, project_field(tool));
                assert_eq!(value, "p-7");
            }
            MappedProject::Unsupported(d) => {
                assert_eq!(d.tool, tool, "the diagnostic names the tool");
                assert_eq!(d.field, project_field(tool), "and the field");
                assert_eq!(
                    d.relation_id, "3->p-7",
                    "and the issue and the association it is about"
                );
                let text = d.to_string();
                for needle in [d.field.as_str(), "p-7", "#3"] {
                    assert!(text.contains(needle), "`{needle}` missing from: {text}");
                }
                // Neither CLI has a membership verb to wait for, so the message
                // must not promise one — the same distinction
                // `RELATION_CLI_ABSENT` draws.
                assert!(
                    !d.message.contains("not verified"),
                    "{tool}: there is no membership verb to verify: {text}"
                );
            }
        }
    }
    // The reasons are per tool because the two CLIs differ, and they say which.
    assert!(project_absence_reason(Tool::GitLab).contains("--project"));
    assert!(project_absence_reason(Tool::Linear).contains("one `project`"));
    assert_ne!(
        project_absence_reason(Tool::GitLab),
        project_absence_reason(Tool::Linear)
    );
}

/// An association with no id is a repair job, not a remote capability gap, and
/// the local entry is not quietly sent as somebody else's project.
#[test]
fn t035_an_association_with_no_id_is_diagnosed_and_kept() {
    for tool in [Tool::GitLab, Tool::Linear] {
        match map_project_to_remote(tool, 4, "   ") {
            MappedProject::Remote { .. } => panic!("{tool}: nothing to send"),
            MappedProject::Unsupported(d) => {
                assert_eq!(d.tool, tool);
                assert_eq!(d.field, project_field(tool));
                assert!(d.message.contains("no id"), "{}", d.message);
                assert!(
                    d.message.contains("kept locally"),
                    "and says the entry survives: {}",
                    d.message
                );
            }
        }
    }
}

/// A payload's references are read **in order**, in every shape the two trackers
/// are known to use, and an entry that cannot yield an id is still reported by
/// name instead of being dropped (T035 step 1, NFR-002 for the order).
#[test]
fn t035_remote_project_reading_keeps_order_and_accepts_every_known_shape() {
    let list: serde_json::Value =
        serde_json::from_str(r#"["p-1", {"id": "p-2", "name": "Two"}, 3]"#).unwrap();
    assert_eq!(
        remote_projects(Some(&list)),
        vec![
            RemoteProject {
                id: "p-1".into(),
                name: None
            },
            RemoteProject {
                id: "p-2".into(),
                name: Some("Two".into())
            },
            RemoteProject {
                id: "3".into(),
                name: None
            },
        ],
        "the payload's order is the list's order"
    );
    // Linear's single `project`, under any of the id spellings.
    for raw in [
        r#"{"identifier": "p-9"}"#,
        r#"{"project_id": "p-9"}"#,
        r#""p-9""#,
    ] {
        let value: serde_json::Value = serde_json::from_str(raw).unwrap();
        assert_eq!(
            remote_projects(Some(&value)),
            vec![RemoteProject {
                id: "p-9".into(),
                name: None
            }],
            "{raw}"
        );
    }
    // A named entry with no id survives, so the import can report it.
    let named: serde_json::Value = serde_json::from_str(r#"[{"name": "Unidentified"}]"#).unwrap();
    assert_eq!(
        remote_projects(Some(&named)),
        vec![RemoteProject {
            id: String::new(),
            name: Some("Unidentified".into())
        }]
    );
    // Absent, null, and shapes carrying nothing at all yield no references.
    assert_eq!(remote_projects(None), [] as [crate::sync::RemoteProject; 0]);
    assert_eq!(
        remote_projects(Some(&serde_json::Value::Null)),
        [] as [crate::sync::RemoteProject; 0]
    );
    assert_eq!(
        remote_projects(Some(&serde_json::json!([true, false]))),
        [] as [crate::sync::RemoteProject; 0]
    );
}

/// An entry the remote named but did not identify cannot be matched on, and the
/// diagnostic quotes the name so a reader can see which project it meant.
#[test]
fn t035_a_remote_project_with_no_id_is_diagnosed_never_guessed_at() {
    for tool in [Tool::GitLab, Tool::Linear] {
        let remote = RemoteProject {
            id: "  ".to_string(),
            name: Some("Named but unidentified".to_string()),
        };
        match map_project_from_remote(tool, &remote) {
            MappedProject::Remote { .. } => {
                panic!("{tool}: an absent id cannot become a local association")
            }
            MappedProject::Unsupported(d) => {
                assert_eq!(d.tool, tool);
                assert_eq!(d.field, project_field(tool));
                assert!(d.message.contains("Named but unidentified"));
                assert!(d.message.contains("no id"));
            }
        }
    }
}

/// A diagnostic built from **remote output** is scrubbed before it is reported
/// (T036 step 6). The project name is the remote text this seam quotes, which is
/// exactly how a credential could reach a report.
#[test]
fn t036_a_project_diagnostic_built_from_remote_output_is_scrubbed() {
    let mut diagnostic = RemoteMappingDiagnostic {
        relation_id: "1->lin-secret".to_string(),
        field: LINEAR_PROJECT_FIELD.to_string(),
        tool: Tool::Linear,
        message: "the remote reports #1 in project `p-1` (`lin-secret`)".to_string(),
    };
    scrub_diagnostic(&mut diagnostic, Some("lin-secret"));
    assert!(
        diagnostic.message.contains("<token>"),
        "{}",
        diagnostic.message
    );
    assert!(!diagnostic.message.contains("lin-secret"));
    assert!(!diagnostic.relation_id.contains("lin-secret"));

    // With no secret configured there is nothing to redact, and the diagnostic is
    // reported unchanged rather than withheld.
    let mut untouched = RemoteMappingDiagnostic {
        relation_id: "1->p-1".to_string(),
        field: LINEAR_PROJECT_FIELD.to_string(),
        tool: Tool::Linear,
        message: "no secret here".to_string(),
    };
    let expected = untouched.clone();
    scrub_diagnostic(&mut untouched, None);
    assert_eq!(untouched, expected);
}

/// Neither tracker sends a membership, both adapters implement the same seam,
/// and the seam itself is defined once (T036 steps 3 and 5, T038 step 6).
///
/// Structural assertions on purpose: the compiler already requires `set_projects`
/// on both adapters (it is a required trait method), and these keep a
/// tracker-specific mapping from being added to one adapter file later.
#[test]
fn t036_no_tracker_sends_a_membership_and_both_adapters_share_the_seam() {
    for tool in [Tool::GitLab, Tool::Linear] {
        assert!(!PROJECT_WIRE_VERIFIED.contains(&tool));
        assert!(matches!(
            map_project_to_remote(tool, 1, "p-1"),
            MappedProject::Unsupported(_)
        ));
    }
    let source = concat!(include_str!("../mod.rs"), include_str!("../adapters.rs"));
    for f in [
        "pub fn map_project_to_remote",
        "pub fn map_project_from_remote",
    ] {
        assert_eq!(
            source.matches(&format!("{f}(")).count(),
            1,
            "{f} must be *defined* exactly once, in this module, for both trackers"
        );
    }
    for (name, text) in [
        ("glab.rs", include_str!("../glab.rs")),
        ("linear.rs", include_str!("../linear.rs")),
    ] {
        assert!(
            !text.contains("fn map_project_to_remote")
                && !text.contains("fn map_project_from_remote"),
            "{name} must not define its own mapping seam"
        );
        assert!(
            text.contains("fn set_projects"),
            "{name} must implement the shared membership seam"
        );
    }
}

/// The report carries a project diagnostic with the count, on the stream and in
/// the returned value, so a caller cannot report success while dropping one.
#[test]
fn t037_a_report_records_a_project_diagnostic_and_prints_the_field() {
    let mut report = SyncReport::default().diagnostics_in_report();
    let mut sink: Vec<u8> = Vec::new();
    report
        .note_project(map_project_to_remote(Tool::GitLab, 2, "p-1"), &mut sink)
        .unwrap();
    assert_eq!(report.diagnostics.len(), 1);
    assert_eq!(report.handled, 0);
    let text = String::from_utf8(sink).unwrap();
    assert!(text.contains("gitlab: projects"), "{text}");
    assert!(text.contains("p-1"), "{text}");
    assert_eq!(report.diagnostics[0].field, GITLAB_PROJECT_FIELD);
}

// ---- WP08 T037–T040: the epic-reference mapping seam ----------------

/// A reported epic id maps back to the local reference key and id, on both
/// trackers (T037 step 1, C-003).
#[test]
fn t037_an_epic_reference_maps_back_to_its_local_id() {
    for tool in [Tool::GitLab, Tool::Linear] {
        let remote = RemoteEpic {
            id: "e-1".to_string(),
            name: Some("One".to_string()),
        };
        match map_epic_from_remote(tool, &remote) {
            MappedEpic::Remote { field, value } => {
                assert_eq!(field, crate::epics::EPICS_KEY);
                assert_eq!(value, "e-1", "the id, never the remote's name");
            }
            MappedEpic::Unsupported(d) => {
                panic!("{tool}: a reported id must map back: {d}")
            }
        }
    }
}

/// Every epic reference diagnoses on both trackers, and the diagnostic names the
/// **field**, the **tool** and the issue — the three things that make it
/// actionable rather than a shrug (T037 step 6, C-007).
///
/// Written so it still holds if a tracker joins `EPIC_WIRE_VERIFIED`: the mapped
/// branch is then the assertion, not the diagnostic's.
#[test]
fn t037_every_epic_reference_diagnoses_with_its_field_its_tool_and_its_reason() {
    for tool in [Tool::GitLab, Tool::Linear] {
        match map_epic_to_remote(tool, 3, "e-7") {
            MappedEpic::Remote { field, value } => {
                assert!(
                    EPIC_WIRE_VERIFIED.contains(&tool),
                    "{tool}: a reference mapped without a verified epic field"
                );
                assert_eq!(field, EPIC_FIELD);
                assert_eq!(value, "e-7");
            }
            MappedEpic::Unsupported(d) => {
                assert_eq!(d.tool, tool, "the diagnostic names the tool");
                assert_eq!(d.field, EPIC_FIELD, "and the field");
                assert_eq!(
                    d.relation_id, "3->e-7",
                    "and the issue and the reference it is about"
                );
                let text = d.to_string();
                for needle in [d.field.as_str(), "e-7", "#3"] {
                    assert!(text.contains(needle), "`{needle}` missing from: {text}");
                }
                // Neither CLI has an epic verb to wait for, so the message must
                // not promise one.
                assert!(
                    !d.message.contains("not verified"),
                    "{tool}: there is no epic verb to verify: {text}"
                );
            }
        }
    }
    // The reasons are per tool because the two CLIs differ, and they say which.
    assert!(epic_absence_reason(Tool::GitLab).contains("epic_iid"));
    assert!(epic_absence_reason(Tool::Linear).contains("project"));
    assert_ne!(
        epic_absence_reason(Tool::GitLab),
        epic_absence_reason(Tool::Linear)
    );
}

/// A reference with no id is a repair job, not a remote capability gap, and the
/// local entry is not quietly sent as somebody else's epic.
#[test]
fn t037_an_epic_reference_with_no_id_is_diagnosed_and_kept() {
    for tool in [Tool::GitLab, Tool::Linear] {
        match map_epic_to_remote(tool, 4, "   ") {
            MappedEpic::Remote { .. } => panic!("{tool}: nothing to send"),
            MappedEpic::Unsupported(d) => {
                assert_eq!(d.tool, tool);
                assert_eq!(d.field, EPIC_FIELD);
                assert!(d.message.contains("no id"), "{}", d.message);
                assert!(
                    d.message.contains("kept locally"),
                    "and says the entry survives: {}",
                    d.message
                );
            }
        }
    }
}

/// A payload's references are read **in order**, in every shape the two trackers
/// are known to use, and an entry that cannot yield an id is still reported by
/// name instead of being dropped (T037 step 1, NFR-002 for the order).
#[test]
fn t037_remote_epic_reading_keeps_order_and_accepts_every_known_shape() {
    let list: serde_json::Value =
        serde_json::from_str(r#"["e-1", {"id": "e-2", "name": "Two"}, 3]"#).unwrap();
    assert_eq!(
        remote_epics(Some(&list)),
        vec![
            RemoteEpic {
                id: "e-1".into(),
                name: None
            },
            RemoteEpic {
                id: "e-2".into(),
                name: Some("Two".into())
            },
            RemoteEpic {
                id: "3".into(),
                name: None
            },
        ],
        "the payload's order is the list's order"
    );
    // A single reference, under any of the id spellings.
    for raw in [
        r#"{"identifier": "e-9"}"#,
        r#"{"epic_id": "e-9"}"#,
        r#""e-9""#,
    ] {
        let value: serde_json::Value = serde_json::from_str(raw).unwrap();
        assert_eq!(
            remote_epics(Some(&value)),
            vec![RemoteEpic {
                id: "e-9".into(),
                name: None
            }],
            "{raw}"
        );
    }
    // A named entry with no id survives, so the import can report it.
    let named: serde_json::Value = serde_json::from_str(r#"[{"name": "Unidentified"}]"#).unwrap();
    assert_eq!(
        remote_epics(Some(&named)),
        vec![RemoteEpic {
            id: String::new(),
            name: Some("Unidentified".into())
        }]
    );
    // Absent, null, and shapes carrying nothing at all yield no references.
    assert_eq!(remote_epics(None), [] as [crate::sync::RemoteEpic; 0]);
    assert_eq!(
        remote_epics(Some(&serde_json::Value::Null)),
        [] as [crate::sync::RemoteEpic; 0]
    );
    assert_eq!(
        remote_epics(Some(&serde_json::json!([true, false]))),
        [] as [crate::sync::RemoteEpic; 0]
    );
}

/// An entry the remote named but did not identify cannot be matched on, and the
/// diagnostic quotes the name so a reader can see which epic it meant.
#[test]
fn t037_a_remote_epic_with_no_id_is_diagnosed_never_guessed_at() {
    for tool in [Tool::GitLab, Tool::Linear] {
        let remote = RemoteEpic {
            id: "  ".to_string(),
            name: Some("Named but unidentified".to_string()),
        };
        match map_epic_from_remote(tool, &remote) {
            MappedEpic::Remote { .. } => {
                panic!("{tool}: an absent id cannot become a local reference")
            }
            MappedEpic::Unsupported(d) => {
                assert_eq!(d.tool, tool);
                assert_eq!(d.field, EPIC_FIELD);
                assert!(d.message.contains("Named but unidentified"));
                assert!(d.message.contains("no id"));
            }
        }
    }
}

/// A diagnostic built from **remote output** is scrubbed before it is reported
/// (T038 step 6). The epic name is the remote text this seam quotes, which is
/// exactly how a credential could reach a report.
#[test]
fn t038_a_remote_epic_diagnostic_is_scrubbed() {
    let mut diagnostic = RemoteMappingDiagnostic {
        relation_id: "1->lin-secret".to_string(),
        field: EPIC_FIELD.to_string(),
        tool: Tool::Linear,
        message: "the remote reports #1 in epic `e-1` (`lin-secret`)".to_string(),
    };
    scrub_diagnostic(&mut diagnostic, Some("lin-secret"));
    assert!(
        diagnostic.message.contains("<token>"),
        "{}",
        diagnostic.message
    );
    assert!(!diagnostic.message.contains("lin-secret"));
    assert!(!diagnostic.relation_id.contains("lin-secret"));
}

/// Neither tracker sends an epic reference, both adapters implement the same
/// seam, and the seam itself is defined once (T038 step 6).
///
/// Structural assertions on purpose: the compiler already requires `set_epics` on
/// both adapters (it is a required trait method), and these keep a
/// tracker-specific mapping from being added to one adapter file later.
#[test]
fn t038_no_tracker_sends_an_epic_reference_and_both_adapters_share_the_seam() {
    for tool in [Tool::GitLab, Tool::Linear] {
        assert!(!EPIC_WIRE_VERIFIED.contains(&tool));
        assert!(matches!(
            map_epic_to_remote(tool, 1, "e-1"),
            MappedEpic::Unsupported(_)
        ));
    }
    let source = concat!(include_str!("../mod.rs"), include_str!("../adapters.rs"));
    for f in ["pub fn map_epic_to_remote", "pub fn map_epic_from_remote"] {
        assert_eq!(
            source.matches(&format!("{f}(")).count(),
            1,
            "{f} must be *defined* exactly once, in this module, for both trackers"
        );
    }
    for (name, text) in [
        ("glab.rs", include_str!("../glab.rs")),
        ("linear.rs", include_str!("../linear.rs")),
    ] {
        assert!(
            !text.contains("fn map_epic_to_remote") && !text.contains("fn map_epic_from_remote"),
            "{name} must not define its own mapping seam"
        );
        assert!(
            text.contains("fn set_epics"),
            "{name} must implement the shared epic seam"
        );
    }
}

/// The report carries an epic diagnostic with the count, on the stream and in the
/// returned value, so a caller cannot report success while dropping one.
#[test]
fn t038_a_report_records_an_epic_diagnostic_and_prints_the_field() {
    let mut report = SyncReport::default().diagnostics_in_report();
    let mut sink: Vec<u8> = Vec::new();
    report
        .note_epic(map_epic_to_remote(Tool::GitLab, 2, "e-1"), &mut sink)
        .unwrap();
    assert_eq!(report.diagnostics.len(), 1);
    assert_eq!(report.handled, 0);
    let text = String::from_utf8(sink).unwrap();
    assert!(text.contains("gitlab: epics"), "{text}");
    assert!(text.contains("e-1"), "{text}");
    assert_eq!(report.diagnostics[0].field, EPIC_FIELD);
}