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
//! The CLI's typed-relationship surface: `tix link`, `tix unlink`, and
//! `tix chain`.
//!
//! Every relationship *semantic* — direction normalization, cycle detection,
//! blocked derivation, ordering — comes from the domain service in
//! [`crate::relationships`]. This module resolves selectors, parses flags, asks
//! the service for a verdict, and prints. It re-derives nothing, which is what
//! `contracts/surface-parity.md` §3 requires: a surface that re-implements part
//! of the rule set is a parity defect, not an optimization.
//!
//! The one thing this module *does* own is presentation, and the wording is
//! therefore factored into pure functions so it is testable without capturing
//! process stdout from inside its own test.

use std::str::FromStr;

use crate::cli::LinkAction;
use crate::error::{Result, TixError};
use crate::model::Issue;
use crate::relationships::{
    BlockedState, DependencyChain, Diagnostic, IssueView, RelationKind, Relationship,
    RelationshipGraph,
};
use crate::storage::{RelationshipOutcome, Store};

/// The accepted `--type` spellings, as the missing-flag diagnostic lists them.
const KIND_SPELLINGS: &str = "blocks|blocked_by|duplicates|related";

/// The stored bound on one chain traversal, quoted in the truncation note so the
/// number the user sees is the number the service used rather than a copy that
/// can drift.
fn chain_bound_note() -> String {
    format!(
        "note: chain display truncated at {} nodes; the chain may continue",
        crate::relationships::MAX_CHAIN_NODES
    )
}

/// Parse a `--type` value, or name the flag and the accepted spellings.
///
/// An unknown kind is never coerced to a default. The service already produces
/// the authoritative [`DiagnosticKind::UnknownKind`] text, and that text is
/// reproduced verbatim rather than reworded, so a rejection reads identically on
/// the CLI, in `tix lint`, in the TUI, and over MCP
/// (`contracts/surface-parity.md` §2).
/// Out-of-map edit (WP05, parity contract §2): public so MCP's `kind` argument
/// goes through the **same** parser as the CLI's `--type`.
///
/// A second parser here would be a second answer to "is this a valid relation
/// kind", and the two could disagree on a spelling — which is exactly the drift
/// `surface-parity.md` §2 forbids. One parser means an unknown kind produces a
/// byte-identical diagnostic on both surfaces for free, rather than by two
/// careful implementations happening to match.
pub fn parse_kind(raw: &str) -> Result<RelationKind> {
    RelationKind::from_str(raw).map_err(|d: Diagnostic| TixError::InvalidInput(d.to_string()))
}

/// The `--type` value for a mutating command, which has no default (C-001).
///
/// **There is deliberately no fallback kind.** A default would make an untyped
/// relationship reachable by omission, which is the accident the breaking
/// change exists to prevent, so the absence is an error that names the flag and
/// the four spellings rather than a clap usage string the user has to decode.
///
/// **Public so MCP shares the whole rule, not just the parser.** WP05 had MCP
/// call `parse_kind` directly, which left the trim and the blank case on the MCP
/// side — so `" blocks "` was accepted by `tix link --type " blocks "` and
/// rejected by `link_issue`, and `"   "` produced a *different* diagnostic
/// ("unknown relation kind `   `") instead of the "relation type required"
/// one. The mutation was invisible to the suite: trimming in MCP kept all 36
/// `tests/mcp.rs` and all 27 `mcp::tools` tests green.
pub fn require_kind(raw: Option<&str>) -> Result<RelationKind> {
    require_kind_named(raw, &format!("pass --type {KIND_SPELLINGS}"))
}

/// As [`require_kind`], but the caller supplies how to name the argument.
///
/// The *decision* — trim, and reject a blank — is the part that was duplicated and
/// diverged, so that is what stays shared. The advice is a sentence about one
/// surface's own spelling: the CLI says `--type`, MCP says `` `kind` ``.
/// `surface-parity.md` §2 asks for "the same named field/selector", not for the
/// CLI's flag name repeated on the other surface — and a single shared sentence
/// naming `--type` for a caller whose schema says `kind` answers a question they
/// did not ask.
pub fn require_kind_named(raw: Option<&str>, advice: &str) -> Result<RelationKind> {
    match raw.map(str::trim) {
        Some(value) if !value.is_empty() => parse_kind(value),
        // The advice is supplied by the caller — see [`require_kind_named`]. The
        // decision is shared; the sentence about *this* surface's argument name is
        // not, because naming the CLI's flag to an MCP caller answers a question
        // they did not ask.
        _ => Err(TixError::InvalidInput(
            Diagnostic::unknown_kind("kind", format!("relation type required: {advice}"))
                .to_string(),
        )),
    }
}

/// One endpoint of a create, or the reason the invocation was incomplete.
fn require_endpoint(raw: Option<&str>, name: &str) -> Result<String> {
    match raw.map(str::trim) {
        Some(value) if !value.is_empty() => Ok(value.to_string()),
        _ => Err(TixError::InvalidInput(format!(
            "{name} is required: usage is `tix link <from> <to> --type <kind>`"
        ))),
    }
}

/// The line `tix link` prints for a create outcome.
pub fn link_message(outcome: &RelationshipOutcome) -> String {
    let rel = &outcome.relationship;
    if outcome.changed {
        format!(
            "Linked {} {} {} ({})",
            rel.from.human(),
            rel.kind,
            rel.to.human(),
            rel.id
        )
    } else {
        format!(
            "Already linked {} {} {} (no change, {})",
            rel.from.human(),
            rel.kind,
            rel.to.human(),
            rel.id
        )
    }
}

/// The line `tix unlink` prints for an outcome.
///
/// `changed` exists precisely to distinguish a real mutation from a no-op, and
/// it was being discarded — `tix unlink` on a pair that was never linked
/// printed "Unlinked", which is a false statement about the store (F19).
pub fn unlink_message(outcome: &RelationshipOutcome) -> String {
    let rel = &outcome.relationship;
    if outcome.changed {
        format!(
            "Unlinked {} {} {} ({})",
            rel.from.human(),
            rel.kind,
            rel.to.human(),
            rel.id
        )
    } else {
        format!(
            "Not linked {} {} {} (no change)",
            rel.from.human(),
            rel.kind,
            rel.to.human()
        )
    }
}

/// The line `tix link edit` prints for an outcome.
///
/// A rejected edit writes nothing, so this only ever describes a real mutation
/// or the identity no-op.
pub fn edit_message(outcome: &RelationshipOutcome) -> String {
    let rel = &outcome.relationship;
    if outcome.changed {
        format!(
            "Relinked {}: {} {} {}",
            rel.id,
            rel.from.human(),
            rel.kind,
            rel.to.human()
        )
    } else {
        format!("{} unchanged (no change)", rel.id)
    }
}

/// The line `tix link remove` prints for an outcome.
pub fn remove_message(outcome: &RelationshipOutcome) -> String {
    let rel = &outcome.relationship;
    if outcome.changed {
        format!(
            "Removed {}: {} {} {}",
            rel.id,
            rel.from.human(),
            rel.kind,
            rel.to.human()
        )
    } else {
        format!("No relationship {} (no change)", rel.id)
    }
}

/// Dispatch `tix link`, whose create form carries no subcommand.
pub fn run(
    store: &Store,
    action: Option<&LinkAction>,
    from: Option<&str>,
    to: Option<&str>,
    kind: Option<&str>,
) -> Result<()> {
    // One transaction for the whole command (#1580). `link`/`unlink` are a
    // *sequence* of writes at the storage layer — `edit_relation` removes a row
    // from every file holding it and then writes the new owner, and `unlink`
    // writes every file that carried a redundant row — so a failure after the
    // first write would otherwise leave the relationship destroyed while the
    // command reported an error. The layer is command-level: every store method
    // participates through the journal without knowing about this wrapper.
    store.transaction(|| match action {
        Some(LinkAction::Edit { id, to, r#type }) => {
            edit(store, id, to.as_deref(), r#type.as_deref())
        }
        Some(LinkAction::Remove { id }) => remove(store, id),
        Some(LinkAction::List { issue, kind }) => list(store, issue.as_deref(), kind.as_deref()),
        None => {
            let from = require_endpoint(from, "from")?;
            let to = require_endpoint(to, "to")?;
            let kind = require_kind(kind)?;
            let outcome = store.link(&from, &to, kind)?;
            println!("{}", link_message(&outcome));
            Ok(())
        }
    })
}

/// `tix link edit <id> [--to <sel>] [--type <kind>]`: retarget and/or re-kind.
///
/// The stable id survives the edit, so a relationship the user already holds by
/// id does not change identity when its target moves. The edit is re-validated
/// through the service, so a self-link, a missing target, a duplicate edge, or
/// a closed cycle is refused with every file untouched (SC-005).
fn edit(store: &Store, id: &str, to: Option<&str>, kind: Option<&str>) -> Result<()> {
    let new_kind = match kind {
        Some(raw) => Some(parse_kind(raw)?),
        None => None,
    };
    let new_to = match to {
        Some(raw) => Some(
            store
                .get(crate::commands::parse_selector(store, raw)?)
                .map(|i| i.number)?,
        ),
        None => None,
    };
    if new_to.is_none() && new_kind.is_none() {
        return Err(TixError::InvalidInput(format!(
            "nothing to change: pass --to and/or --type to `tix link edit {id}`"
        )));
    }
    let outcome = store.edit_relation(id, new_to, new_kind)?;
    println!("{}", edit_message(&outcome));
    Ok(())
}

/// `tix link remove <id>`: remove one relationship.
///
/// An id that is not stored is an idempotent no-op — no file written, no History
/// event appended — so the command is safe to retry. That is a stronger promise
/// than "prints a friendly message", and the outcome's `changed` flag is what
/// proves it.
fn remove(store: &Store, id: &str) -> Result<()> {
    let outcome = store.remove_relation(id)?;
    println!("{}", remove_message(&outcome));
    Ok(())
}

/// `tix link list [<sel>] [--kind <kind>]`: list relationships, deterministically.
///
/// Ordering is the service's, not this function's: the graph stores its edges
/// sorted by `(kind, target, from, id)`, so both the whole-board listing and a
/// single issue's are byte-comparable across runs and across surfaces. Sorting
/// at the print site is the mistake that would break that, so it is not done.
fn list(store: &Store, issue: Option<&str>, kind: Option<&str>) -> Result<()> {
    let wanted = match kind {
        Some(raw) => Some(canonical_filter(parse_kind(raw)?)),
        None => None,
    };
    let subject = match issue {
        Some(raw) => Some(
            store
                .get(crate::commands::parse_selector(store, raw)?)
                .map(|i| i.number)?,
        ),
        None => None,
    };

    let (issues, done_column) = store.graph_source()?;
    let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
    let graph = RelationshipGraph::new(&views, &done_column);

    let edges: Vec<&Relationship> = match subject {
        Some(number) => graph.relationships_for(number),
        None => graph.all_relationships().iter().collect(),
    };
    let shown: Vec<&Relationship> = edges
        .into_iter()
        .filter(|rel| wanted.is_none_or(|w| rel.kind == w))
        .collect();

    if shown.is_empty() {
        // A named "nothing here" beats an empty blob, and it is the only place
        // a user learns their `--kind` filter matched nothing rather than that
        // the board has no relationships at all.
        println!("{}", empty_listing_text(subject, wanted));
        return Ok(());
    }
    for rel in shown {
        println!("{}", relationship_line(rel));
    }
    Ok(())
}

/// The `link list` report as one string, for surfaces that do not print line by line
/// (MCP today, and the TUI if it ever lists).
///
/// Byte-identical to what [`list`] prints: the same rows from the same
/// [`relationship_line`], joined by newlines, or the same empty-result wording when
/// there is nothing to show. `list` prints row by row because that is what a terminal
/// wants and this joins them because that is what a protocol response wants — but
/// both take the row from the same renderer, so the row itself cannot drift.
///
/// The empty wording used to be a `match (subject, wanted)` written out **twice** —
/// once in `list` and once in `src/mcp/tools.rs`'s `list_relationships`, with the MCP
/// copy commented as being the same. They were byte-identical, but only by
/// coincidence, and the other duplicated format in that same function had genuinely
/// diverged (#1345). One function, two callers.
pub fn listing_text(
    shown: &[&Relationship],
    subject: Option<u32>,
    wanted: Option<RelationKind>,
) -> String {
    if shown.is_empty() {
        return empty_listing_text(subject, wanted);
    }
    shown
        .iter()
        .map(|rel| relationship_line(rel))
        .collect::<Vec<_>>()
        .join("\n")
}

/// What a `link list` says when it has nothing to show.
fn empty_listing_text(subject: Option<u32>, wanted: Option<RelationKind>) -> String {
    match (subject, wanted) {
        (Some(number), Some(kind)) => format!("No {} relationships for #{number}", kind),
        (Some(number), None) => format!("No relationships for #{number}"),
        (None, Some(kind)) => format!("No {kind} relationships"),
        (None, None) => "No relationships".to_string(),
    }
}

/// Translate an input-only kind spelling into the kind a stored edge carries.
///
/// `blocked_by` is accepted on the command line and normalizes into the
/// canonical `blocks` edge, which is what is persisted. Filtering on
/// `BlockedBy` literally would therefore match nothing, and `tix link list
/// --kind blocked_by` is documented as returning the blocking edges. Silently
/// returning an empty list for a documented flag would be the worse failure.
///
/// Public because it is a **spelling and direction rule**, not a presentation choice,
/// and `surface-parity.md` §3 puts those in the service. `list_relationships` in
/// `src/mcp/tools.rs` carried its own copy of this `match`; the two were
/// byte-identical only by coincidence — and the sibling finding from the same review
/// was two surfaces that had in fact *diverged* while a comment claimed otherwise.
pub fn canonical_filter(kind: RelationKind) -> RelationKind {
    match kind {
        RelationKind::BlockedBy => RelationKind::Blocks,
        other => other,
    }
}

/// `tix unlink <from> <to> --type <kind>`: the explicit fully-qualified remove.
///
/// `--type` is required here for the same reason it is required on create: an
/// unqualified remove cannot name which edge it means, and guessing would make
/// a destructive command ambiguous.
pub fn unlink_cli(store: &Store, from: &str, to: &str, kind: Option<&str>) -> Result<()> {
    let kind = require_kind(kind)?;
    // One transaction for the whole removal (#1580): `Store::unlink` writes every
    // file that carries a matching row, so a failure after the first leaves the
    // store half-mutated with the edge destroyed on one endpoint only.
    let outcome = store.transaction(|| store.unlink(from, to, kind))?;
    println!("{}", unlink_message(&outcome));
    Ok(())
}

/// `tix chain <selector>`: print the transitive chain an issue holds up.
///
/// The node order is the service's, verbatim. Re-sorting or re-deriving here
/// would let the CLI and the TUI report different chains for one snapshot, which
/// is the exact drift `contracts/surface-parity.md` §2 forbids.
pub fn chain(store: &Store, raw: &str) -> Result<()> {
    let issue = store.get(crate::commands::parse_selector(store, raw)?)?;
    let (issues, done_column) = store.graph_source()?;
    let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
    let graph = RelationshipGraph::new(&views, &done_column);
    print!("{}", chain_output(&graph.dependency_chain(issue.number)));
    Ok(())
}

/// One relationship as every read surface renders it: the canonical direction,
/// the target's display name, and the stable id.
///
/// The id is included because it is the only handle `tix link edit` and
/// `tix link remove` accept, and a listing that omitted it would leave the user
/// unable to act on what it just showed them.
pub fn relationship_line(rel: &Relationship) -> String {
    format!(
        "{} --{}--> {}  {}  [{}]",
        rel.from.human(),
        rel.kind,
        rel.to.human(),
        display_target(rel),
        rel.id
    )
}

/// The target's display name, without the redundant `#N` and kind the line
/// already carries. A dangling edge has no title, so it renders as `#N`.
fn display_target(rel: &Relationship) -> String {
    // `display` is `"<kind> #<number> <title>"` — see
    // [`display_name`](tix::relationships::display_name) — so the title is
    // **everything after the known prefix**.
    //
    // It used to be found with `rel.display.rfind(' ')`, on the reasoning that "the
    // title may itself contain spaces, so the split is from the right". That
    // reasoning is backwards: splitting from the right takes the **last** word of
    // the title, so a multi-word title lost all but its final word.
    //
    //     title "Second one"  ->  display "blocks #1 Second one"  ->  "one"
    //
    // and `tix link list` rendered `#0 --blocks--> #1  one`, which reads as a
    // different issue's title and silently mislabels the edge. A single-word title
    // masked it, which is why it survived: the existing fixtures all used one word.
    //
    // The prefix is the *left* part, and it is known exactly — the kind and the
    // canonical target — so the title is a `strip_prefix`, not a search.
    let target = rel.to.human();
    let prefix = format!("{} {target}", rel.kind.as_str());
    match rel.display.strip_prefix(&prefix) {
        Some(title) => {
            let title = title.trim();
            if title.is_empty() {
                // `display_name` omits the title when it is blank, so a stored
                // `display` that matches the prefix exactly has none to show.
                target
            } else {
                title.to_string()
            }
        }
        // A hand-edited `display` that does not match the shape. Reporting the raw
        // value is more useful than reporting a fragment of it, and this is
        // unreachable for anything `tix` wrote.
        None => rel.display.clone(),
    }
}

/// The whole `tix chain` report, including the truncation note.
pub fn chain_output(chain: &DependencyChain) -> String {
    let mut out = String::new();
    if chain.paths.is_empty() {
        // Covers "has no outbound `blocks` edges" and, defensively, a root the
        // graph does not hold. Naming the situation is the requirement; an
        // empty blob is not a report.
        out.push_str(&format!("No dependency chain for #{}\n", chain.root));
    } else {
        for path in &chain.paths {
            for (depth, node) in path.iter().enumerate() {
                out.push_str(if depth == 0 { "" } else { "  -> " });
                out.push_str(&node_line(node));
                out.push('\n');
            }
        }
    }
    if chain.truncated {
        // An explicit note, because a partial chain printed as a complete one is
        // a false statement about the graph (T013 step 3).
        out.push_str(&chain_bound_note());
        out.push('\n');
    }
    out
}

/// One chain node: its reference and its display name.
fn node_line(node: &crate::relationships::ChainNode) -> String {
    let title = node.title.trim();
    if title.is_empty() {
        format!("#{}", node.number)
    } else {
        format!("#{} {}", node.number, title)
    }
}

/// The token `--show` accepts on every surface that has relationship
/// information to add.
pub const SHOW_RELATIONSHIPS: &str = "relationships";

/// Whether a `--show` value asks for the relationship block.
///
/// The value is a comma-separated set of requested extras, and an **empty set
/// requests nothing** — so `--show ""` and `--show` behave the same. That is
/// what makes `--show "$SOMETHING"` with an unset shell variable a no-op instead
/// of a usage error.
///
/// One parser, shared by `tix list` and `tix view`, because two surfaces that
/// accept different `--show` values is exactly the drift
/// `contracts/surface-parity.md` §2 exists to prevent. An unrecognised token is
/// rejected rather than ignored: a flag the user typed that silently does
/// nothing is worse than one that says so.
pub fn wants_relationships(show: Option<&str>) -> Result<bool> {
    let Some(raw) = show else {
        return Ok(false);
    };
    let mut requested = false;
    for token in raw.split(',').map(str::trim).filter(|t| !t.is_empty()) {
        if token != SHOW_RELATIONSHIPS {
            return Err(TixError::InvalidInput(format!(
                "unknown --show value `{token}`; this surface understands `{SHOW_RELATIONSHIPS}`"
            )));
        }
        requested = true;
    }
    Ok(requested)
}

/// The `--show relationships` block: every relationship touching `number`, in
/// the service's order.
pub fn relationship_block(graph: &RelationshipGraph, number: u32) -> Vec<String> {
    graph
        .relationships_for(number)
        .into_iter()
        .map(relationship_line)
        .collect()
}

/// The blocked marker for `number`, or `None` when it is not blocked.
///
/// An issue that is merely `related` to a blocker is **not** blocked, and an
/// issue whose blocker has reached the board's configured `done_column` is not
/// blocked either. Both are the service's call, taken from
/// [`RelationshipGraph::blocked_state`] — computing either locally is the
/// boundary breach the parity contract's bypass rule exists to catch.
pub fn blocked_marker(state: &BlockedState) -> Option<String> {
    if !state.is_blocked {
        return None;
    }
    Some(format!("blocked: {}", state.reason))
}

/// The `--show relationships` appendix for `tix view <sel>`: relationships,
/// chain, and blocked reason, in that order.
///
/// A pure function of the graph, so the TUI and MCP can render the same block
/// and the wording cannot drift between them.
pub fn derived_block(graph: &RelationshipGraph, number: u32) -> String {
    let mut out = String::new();
    let relationships = relationship_block(graph, number);
    out.push_str("\n## Relationships\n\n");
    if relationships.is_empty() {
        out.push_str("- none\n");
    } else {
        for line in relationships {
            out.push_str(&format!("- {line}\n"));
        }
    }

    out.push_str("\n## Dependency chain\n\n");
    out.push_str(&chain_output(&graph.dependency_chain(number)));

    let state = graph.blocked_state(number);
    out.push_str("\n## Blocked\n\n");
    match blocked_marker(&state) {
        Some(marker) => out.push_str(&format!("- {marker}\n")),
        None => out.push_str("- not blocked\n"),
    }
    out
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::commands::create::create;
    use crate::error::TixError;
    use crate::storage::IssueSelector;
    use std::fs;
    use tempfile::TempDir;

    fn make_store() -> (TempDir, Store) {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        fs::create_dir_all(&dir).unwrap();
        let config_path = tmp.path().join("tix.toml");
        let config = crate::config::Config {
            issues_dir: dir.clone(),
            ..crate::config::Config::default()
        };
        config.save(&config_path).unwrap();
        let config = crate::config::Config::load_with_warning(&config_path, |_| {}).unwrap();
        (
            tmp,
            Store {
                issues_dir: dir,
                config,
            },
        )
    }

    fn seed(store: &Store, title: &str) -> Issue {
        create(
            &store.config,
            store,
            title,
            Some("body"),
            None,
            None,
            Some(""),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap()
    }

    fn sel(issue: &Issue) -> String {
        issue.number.to_string()
    }

    // ---- T011: typed, required --type -------------------------------

    #[test]
    fn t011_a_missing_type_is_rejected_and_the_message_names_the_flag() {
        let err = require_kind(None).unwrap_err();
        let text = err.to_string();
        assert!(
            text.contains("--type"),
            "the rejection must name the missing flag, got: {text}"
        );
        for spelling in ["blocks", "blocked_by", "duplicates", "related"] {
            assert!(
                text.contains(spelling),
                "the rejection must list the `{spelling}` spelling, got: {text}"
            );
        }
        assert!(
            text.contains("unknown_kind (kind)"),
            "the diagnostic kind and its field are authoritative and must survive: {text}"
        );
    }

    #[test]
    fn t011_an_empty_type_is_rejected_rather_than_defaulted() {
        // The dangerous case: `--type ""` reaching the parser. A `filter`-style
        // "empty means absent" shortcut would let this fall through to a
        // default kind, which is the accident C-001 exists to prevent.
        assert!(require_kind(Some("   ")).is_err());
        assert!(require_kind(Some("")).is_err());
    }

    #[test]
    fn t011_an_unknown_kind_is_rejected_with_the_service_text_verbatim() {
        let err = parse_kind("nonsense").unwrap_err();
        let text = err.to_string();
        assert!(
            text.contains("unknown_kind (kind)"),
            "the service's kind and field must reach the user: {text}"
        );
        assert!(text.contains("`nonsense`"), "got: {text}");
        // Rejection, not coercion: an unknown kind must never become `related`.
        assert!(parse_kind("blocks-2").is_err());
    }

    #[test]
    fn t011_every_documented_spelling_parses() {
        for (raw, expected) in [
            ("blocks", RelationKind::Blocks),
            ("blocked_by", RelationKind::BlockedBy),
            ("duplicates", RelationKind::Duplicates),
            ("related", RelationKind::Related),
        ] {
            assert_eq!(parse_kind(raw).unwrap(), expected, "parsing {raw}");
        }
    }

    #[test]
    fn t011_a_link_without_type_creates_nothing() {
        // The no-partial-write claim for the *usage* case: a rejected
        // invocation must not touch a file, which is a stronger and more
        // useful assertion than "it returned an error".
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        let before = snapshot(&store);

        let err = run(&store, None, Some(&sel(&a)), Some(&sel(&b)), None).unwrap_err();
        assert!(matches!(err, TixError::InvalidInput(_)), "got {err:?}");

        assert_eq!(snapshot(&store), before, "no file may change");
    }

    #[test]
    fn t011_a_typed_link_records_the_canonical_edge() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        run(&store, None, Some(&sel(&a)), Some(&sel(&b)), Some("blocks")).unwrap();

        // Stored once, in the canonical `from`'s file.
        let owner = store.get(IssueSelector::Number(a.number)).unwrap();
        assert_eq!(owner.relationships.len(), 1, "one edge, stored once");
        let edge = &owner.relationships[0];
        assert_eq!(edge.kind, RelationKind::Blocks);
        assert_eq!(edge.from, crate::id::canonical_ref(&a));
        assert_eq!(edge.to, crate::id::canonical_ref(&b));
        assert!(!edge.id.is_empty(), "a stored relationship is addressable");
    }

    #[test]
    fn t011_blocked_by_is_an_input_spelling_that_stores_the_blocks_edge() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        run(
            &store,
            None,
            Some(&sel(&a)),
            Some(&sel(&b)),
            Some("blocked_by"),
        )
        .unwrap();

        let owner = store.get(IssueSelector::Number(b.number)).unwrap();
        assert_eq!(owner.relationships.len(), 1, "stored once, on the blocker");
        let edge = &owner.relationships[0];
        assert_eq!(
            edge.kind,
            RelationKind::Blocks,
            "`blocked_by` is never persisted; it normalizes into `blocks`"
        );
        assert_eq!(edge.from, crate::id::canonical_ref(&b));
        assert_eq!(edge.to, crate::id::canonical_ref(&a));
    }

    #[test]
    fn t011_a_self_link_is_rejected_and_writes_nothing() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let before = snapshot(&store);
        let err = run(&store, None, Some(&sel(&a)), Some(&sel(&a)), Some("blocks")).unwrap_err();
        assert!(err.to_string().contains("self"), "got: {err}");
        assert_eq!(snapshot(&store), before, "no file may change");
    }

    #[test]
    fn t011_an_incomplete_invocation_names_the_missing_endpoint() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let err = run(&store, None, Some(&sel(&a)), None, Some("blocks")).unwrap_err();
        assert!(err.to_string().contains("to is required"), "got: {err}");

        let err = run(&store, None, None, Some(&sel(&a)), Some("blocks")).unwrap_err();
        assert!(err.to_string().contains("from is required"), "got: {err}");
    }

    // ---- T012: edit / remove / list ----------------------------------

    #[test]
    fn t012_an_edit_preserves_the_stable_id() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        let c = seed(&store, "C");
        let created = store
            .link(&sel(&a), &sel(&b), RelationKind::Blocks)
            .unwrap();
        let id = created.relationship.id.clone();

        edit(&store, &id, Some(&sel(&c)), None).unwrap();

        // The id a user already holds must still resolve, and must now name the
        // new target — that pair is the whole justification for persisting it.
        let owner = store.get(IssueSelector::Number(a.number)).unwrap();
        assert_eq!(owner.relationships.len(), 1);
        let edge = &owner.relationships[0];
        assert_eq!(edge.id, id, "identity survives the retarget");
        assert_eq!(
            edge.to,
            crate::id::canonical_ref(&c),
            "the retarget took effect"
        );
        assert_eq!(
            edge.kind,
            RelationKind::Blocks,
            "the kind was not disturbed"
        );
    }

    #[test]
    fn t012_an_edit_records_the_retargeted_history_event() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        let c = seed(&store, "C");
        let created = store
            .link(&sel(&a), &sel(&b), RelationKind::Blocks)
            .unwrap();
        edit(&store, &created.relationship.id, Some(&sel(&c)), None).unwrap();

        let owner = store.get(IssueSelector::Number(a.number)).unwrap();
        let kinds: Vec<String> = owner
            .history
            .events()
            .iter()
            .map(|e| e.kind.as_str().to_string())
            .collect();
        assert!(
            kinds.contains(&"relationship_retargeted".to_string()),
            "an edit must leave a `relationship_retargeted` event, got {kinds:?}"
        );
        assert!(
            !kinds.contains(&"relationship_removed".to_string()),
            "one edit is one mutation, not a remove plus a create: {kinds:?}"
        );
    }

    #[test]
    fn t012_a_rejected_edit_writes_nothing() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        let created = store
            .link(&sel(&a), &sel(&b), RelationKind::Blocks)
            .unwrap();
        let before = snapshot(&store);

        // Retarget onto the source itself: a self-link, refused by the service.
        let err = edit(&store, &created.relationship.id, Some(&sel(&a)), None).unwrap_err();
        assert!(err.to_string().contains("self"), "got: {err}");
        assert_eq!(snapshot(&store), before, "no file may change (SC-005)");
    }

    #[test]
    fn t012_an_edit_with_nothing_to_change_is_refused() {
        // The identity edit would otherwise be a silent no-op that *looks* like
        // a successful mutation, and it would report the no-change wording
        // without the user having asked for one.
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        let created = store
            .link(&sel(&a), &sel(&b), RelationKind::Blocks)
            .unwrap();
        let err = edit(&store, &created.relationship.id, None, None).unwrap_err();
        assert!(err.to_string().contains("nothing to change"), "got: {err}");
    }

    #[test]
    fn t012_removing_an_absent_relationship_is_a_no_op_with_no_history_entry() {
        // T012's own note: "idempotent no-op" must mean *no file write and no
        // History entry*, not merely a friendly message. A count comparison is
        // the only assertion that can tell the two apart.
        let (tmp, store) = make_store();
        let _ = tmp;
        seed(&store, "A");
        // Seeded on purpose: a board that already has an issue is the case
        // where a "no rows matched" bug would be visible. With an empty store
        // the assertion would pass whether or not the path ran.
        let before = snapshot(&store);
        assert!(!before.is_empty(), "precondition: the board has an issue");

        remove(&store, "rel_does_not_exist").unwrap();
        assert_eq!(
            snapshot(&store),
            before,
            "an absent id must not write a file, and must not append History"
        );
    }

    #[test]
    fn t012_repeated_remove_is_idempotent() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        let created = store
            .link(&sel(&a), &sel(&b), RelationKind::Blocks)
            .unwrap();
        let id = created.relationship.id.clone();

        let first = store.remove_relation(&id).unwrap();
        assert!(first.changed, "the first remove is a real mutation");
        let after_first = snapshot(&store);

        let second = store.remove_relation(&id).unwrap();
        assert!(!second.changed, "the second remove is a no-op");
        assert_eq!(snapshot(&store), after_first, "no second write");
    }

    #[test]
    fn t012_an_unknown_id_is_a_named_diagnostic() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let err = store.remove_relation("rel_nope").map(|_| ());
        // Absent is a no-op, not an error; but an *edit* of an absent id is a
        // rejection, because the user asserted something is there.
        assert!(err.is_ok());
        let err = store
            .edit_relation("rel_nope", None, Some(RelationKind::Related))
            .unwrap_err();
        assert!(err.to_string().contains("unknown_relation"), "got: {err}");
        assert!(err.to_string().contains("rel_nope"), "got: {err}");
    }

    #[test]
    fn t012_listing_is_ordered_by_kind_then_target_and_carries_the_id() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        let c = seed(&store, "C");
        let d = seed(&store, "D");
        // Three distinct targets, because one authoritative kind per ordered
        // pair is a service rule: `a` cannot be both `related` and
        // `duplicates` to the same issue. Aiming the test at three targets
        // exercises the ordering, not the conflict rule.
        store
            .link(&sel(&a), &sel(&c), RelationKind::Related)
            .unwrap();
        store
            .link(&sel(&a), &sel(&b), RelationKind::Blocks)
            .unwrap();
        store
            .link(&sel(&a), &sel(&d), RelationKind::Duplicates)
            .unwrap();

        let (issues, done_column) = store.graph_source().unwrap();
        let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
        let graph = RelationshipGraph::new(&views, &done_column);
        let lines: Vec<String> = graph
            .relationships_for(a.number)
            .into_iter()
            .map(relationship_line)
            .collect();

        assert_eq!(lines.len(), 3);
        // `blocks` < `duplicates` < `related` in the enum's declaration order.
        let kinds: Vec<&str> = lines
            .iter()
            .map(|l| l.split("--").nth(1).unwrap())
            .collect();
        assert_eq!(kinds, vec!["blocks", "duplicates", "related"], "{lines:?}");
        assert!(
            lines.iter().all(|l| l.contains("[rel_")),
            "every line carries the id `tix link edit`/`remove` accept: {lines:?}"
        );
    }

    #[test]
    fn t012_kind_filtering_is_exact_and_blocked_by_filters_the_canonical_edge() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        // Stored via the input spelling, so the only persisted kind is `blocks`.
        store
            .link(&sel(&a), &sel(&b), RelationKind::BlockedBy)
            .unwrap();

        let (issues, done_column) = store.graph_source().unwrap();
        let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
        let graph = RelationshipGraph::new(&views, &done_column);

        let all = graph.relationships_for(a.number);
        assert_eq!(all.len(), 1);
        assert_eq!(
            all[0].kind,
            RelationKind::Blocks,
            "precondition: nothing persists as `blocked_by`"
        );

        for spelling in ["blocks", "blocked_by"] {
            let wanted = canonical_filter(parse_kind(spelling).unwrap());
            let matched: Vec<_> = all.iter().copied().filter(|r| r.kind == wanted).collect();
            assert_eq!(
                matched.len(),
                1,
                "`--kind {spelling}` must find the canonical blocking edge, not nothing"
            );
        }
        for spelling in ["duplicates", "related"] {
            let wanted = canonical_filter(parse_kind(spelling).unwrap());
            let matched: Vec<_> = all.iter().copied().filter(|r| r.kind == wanted).collect();
            assert!(
                matched.is_empty(),
                "`--kind {spelling}` must not match a block"
            );
        }
    }

    #[test]
    fn t012_unlink_without_type_is_rejected_and_names_the_flag() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        let before = snapshot(&store);
        let err = unlink_cli(&store, &sel(&a), &sel(&b), None).unwrap_err();
        assert!(err.to_string().contains("--type"), "got: {err}");
        assert_eq!(snapshot(&store), before, "a rejected remove writes nothing");
    }

    #[test]
    fn t012_unlink_with_type_removes_the_edge() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        store
            .link(&sel(&a), &sel(&b), RelationKind::Blocks)
            .unwrap();
        unlink_cli(&store, &sel(&a), &sel(&b), Some("blocks")).unwrap();
        let owner = store.get(IssueSelector::Number(a.number)).unwrap();
        assert!(
            owner.relationships.is_empty(),
            "the fully-qualified spelling removes the same edge"
        );
    }

    // ---- T013: chain -------------------------------------------------

    #[test]
    fn t013_a_three_node_chain_prints_in_service_order() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        let c = seed(&store, "C");
        store
            .link(&sel(&a), &sel(&b), RelationKind::Blocks)
            .unwrap();
        store
            .link(&sel(&b), &sel(&c), RelationKind::Blocks)
            .unwrap();

        let (issues, done_column) = store.graph_source().unwrap();
        let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
        let graph = RelationshipGraph::new(&views, &done_column);
        let out = chain_output(&graph.dependency_chain(a.number));

        let root = out.find("#").unwrap();
        let b_at = out.find(&format!("#{} ", b.number)).unwrap();
        let c_at = out.find(&format!("#{} ", c.number)).unwrap();
        assert!(root < b_at && b_at < c_at, "order must be A, B, C:\n{out}");
        assert!(out.contains("B"), "display names appear:\n{out}");
        assert!(out.contains("C"), "display names appear:\n{out}");
        assert!(
            !out.contains("truncated"),
            "a three-node chain is not truncated:\n{out}"
        );
    }

    #[test]
    fn t013_an_issue_with_no_outbound_blocks_says_so() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        // Inbound only: #1 is blocked *by* #2, it does not block anything.
        store
            .link(&sel(&b), &sel(&a), RelationKind::Blocks)
            .unwrap();

        let (issues, done_column) = store.graph_source().unwrap();
        let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
        let graph = RelationshipGraph::new(&views, &done_column);
        let out = chain_output(&graph.dependency_chain(a.number));
        assert!(
            out.contains("No dependency chain"),
            "the empty case is named, not printed as an empty blob:\n{out}"
        );
    }

    #[test]
    fn t013_the_truncated_flag_produces_an_explicit_note() {
        // The note is asserted against a chain object with the flag forced,
        // because `MAX_CHAIN_NODES` is 1,000 and a 1,000-node fixture would
        // make this test slow for no extra assurance — but the *rendering* is
        // exactly what the contract pins, so the render path is driven
        // directly.
        let chain = DependencyChain {
            root: 1,
            paths: vec![],
            truncated: true,
        };
        let out = chain_output(&chain);
        assert!(out.contains("truncated"), "{out}");
        assert!(
            out.contains("may continue"),
            "the note must say the chain continues, not that it ends: {out}"
        );
    }

    #[test]
    fn t013_a_cyclic_hand_edited_file_terminates_and_reports_the_cycle() {
        // Write-time rejection makes a cycle unreachable through the CLI, so a
        // cycle is only reachable by hand-editing — which is exactly when the
        // traversal's termination guarantee matters.
        let (tmp, store) = make_store();
        let _ = tmp;
        let a = seed(&store, "A");
        let b = seed(&store, "B");
        let mut owner = store.get(IssueSelector::Number(a.number)).unwrap();
        let root = a.number;
        owner
            .relationships
            .push(crate::relationships::Relationship::new(
                a.number,
                b.number,
                RelationKind::Blocks,
                "B",
            ));
        store.update(&owner.filename, &owner).unwrap();
        let mut owner = store.get(IssueSelector::Number(b.number)).unwrap();
        owner
            .relationships
            .push(crate::relationships::Relationship::new(
                b.number,
                a.number,
                RelationKind::Blocks,
                "A",
            ));
        store.update(&owner.filename, &owner).unwrap();

        let err = store
            .link(&sel(&a), &sel(&b), RelationKind::Blocks)
            .unwrap_err();
        assert!(err.to_string().contains("cycle"), "got: {err}");

        // And the traversal itself still terminates on the cyclic snapshot.
        let (issues, done_column) = store.graph_source().unwrap();
        let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
        let graph = RelationshipGraph::new(&views, &done_column);
        let out = chain_output(&graph.dependency_chain(root));
        assert_ne!(out, "");
    }

    #[test]
    fn t013_an_unresolvable_selector_is_a_not_found() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let err = chain(&store, "999").unwrap_err();
        assert!(matches!(err, TixError::NotFound(_)), "got {err:?}");
    }

    // ---- the shared `--show` parser ----------------------------------
    //
    // `tix list` and `tix view` both delegate to this one parser, so these
    // tests are the contract for *both* surfaces. If it were duplicated per
    // surface, the two could accept different tokens, which is the drift
    // `contracts/surface-parity.md` §2 exists to prevent.

    #[test]
    fn show_absent_or_empty_requests_nothing() {
        assert!(!wants_relationships(None).unwrap());
        // `--show "$UNSET_VAR"` is a shell artefact, not a usage error, and it
        // must behave exactly like omitting the flag.
        assert!(!wants_relationships(Some("")).unwrap());
        assert!(!wants_relationships(Some("  ")).unwrap());
        assert!(!wants_relationships(Some(",,")).unwrap());
    }

    #[test]
    fn show_accepts_the_documented_token_in_any_spacing() {
        assert!(wants_relationships(Some("relationships")).unwrap());
        assert!(wants_relationships(Some("  relationships  ")).unwrap());
        assert!(wants_relationships(Some("relationships,relationships")).unwrap());
    }

    #[test]
    fn an_unknown_show_value_is_rejected_rather_than_ignored() {
        // A flag the user typed that silently does nothing is a worse failure
        // than one that says so, and the message has to name both what was
        // typed and what is valid.
        let err = wants_relationships(Some("relatinships")).unwrap_err();
        let text = err.to_string();
        assert!(
            text.contains("relatinships"),
            "names what was typed: {text}"
        );
        assert!(
            text.contains("relationships"),
            "names what is valid: {text}"
        );

        // A valid token alongside an invalid one is still a rejection: silently
        // honouring the valid half is how "why did my flag not work" happens.
        assert!(wants_relationships(Some("relationships,blocks")).is_err());
    }

    // ---- T014: blocked state ----------------------------------------

    #[test]
    fn t014_an_inbound_open_blocks_edge_marks_the_issue_blocked_with_a_reason() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let blocker = seed(&store, "Blocker");
        let subject = seed(&store, "Subject");
        store
            .link(&sel(&blocker), &sel(&subject), RelationKind::Blocks)
            .unwrap();

        let (issues, done_column) = store.graph_source().unwrap();
        let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
        let graph = RelationshipGraph::new(&views, &done_column);

        let marker = blocked_marker(&graph.blocked_state(subject.number)).expect("blocked");
        assert!(marker.contains("blocked:"), "{marker}");
        assert!(
            marker.contains(&blocker.number.to_string()),
            "the reason names the blocker: {marker}"
        );
    }

    #[test]
    fn t014_related_only_is_not_blocked() {
        // The distinction the typed model exists to make. If `related` implied
        // blocked, the four kinds would collapse into two.
        let (tmp, store) = make_store();
        let _ = tmp;
        let other = seed(&store, "Other");
        let subject = seed(&store, "Subject");
        store
            .link(&sel(&other), &sel(&subject), RelationKind::Related)
            .unwrap();

        let (issues, done_column) = store.graph_source().unwrap();
        let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
        let graph = RelationshipGraph::new(&views, &done_column);

        assert_eq!(
            graph.relationships_for(subject.number).len(),
            1,
            "precondition: the edge exists and is visible"
        );
        assert!(
            blocked_marker(&graph.blocked_state(subject.number)).is_none(),
            "an issue that is only `related` must not render as blocked"
        );
    }

    #[test]
    fn t014_a_blocker_in_the_configured_done_column_is_not_blocked() {
        // "Toward completion" resolves through configuration, never the literal
        // string `done` (research R7) — the same helper WP04 uses.
        let (tmp, store) = make_store();
        let _ = tmp;
        let blocker = seed(&store, "Blocker");
        let subject = seed(&store, "Subject");
        store
            .link(&sel(&blocker), &sel(&subject), RelationKind::Blocks)
            .unwrap();
        store
            .set_status(
                &store
                    .get(IssueSelector::Number(blocker.number))
                    .unwrap()
                    .filename,
                crate::storage::StatusChange::to("done"),
            )
            .unwrap();

        let (issues, done_column) = store.graph_source().unwrap();
        let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
        let graph = RelationshipGraph::new(&views, &done_column);
        assert!(
            blocked_marker(&graph.blocked_state(subject.number)).is_none(),
            "a finished blocker does not block"
        );
    }

    #[test]
    fn t014_the_derived_block_names_every_section() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let blocker = seed(&store, "Blocker");
        let subject = seed(&store, "Subject");
        store
            .link(&sel(&blocker), &sel(&subject), RelationKind::Blocks)
            .unwrap();

        let (issues, done_column) = store.graph_source().unwrap();
        let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
        let graph = RelationshipGraph::new(&views, &done_column);
        let out = derived_block(&graph, subject.number);

        assert!(out.contains("## Relationships"), "{out}");
        assert!(out.contains("## Dependency chain"), "{out}");
        assert!(out.contains("## Blocked"), "{out}");
        assert!(
            out.contains("not blocked") || out.contains("blocked:"),
            "{out}"
        );
    }

    /// Every issue file's bytes, as a name→content map. The only honest way to
    /// prove "no file changed": an exit code is not evidence, and neither is a
    /// re-read through the same parser that might have dropped the line.
    fn snapshot(store: &Store) -> std::collections::BTreeMap<String, String> {
        let mut out = std::collections::BTreeMap::new();
        for issue in store.list().unwrap() {
            out.insert(
                issue.filename.clone(),
                fs::read_to_string(store.issues_dir.join(&issue.filename)).unwrap(),
            );
        }
        out
    }
}