vissue-core 0.6.0

Plain-text issue tracking over per-project orgmode files: model, store, queries, and org projection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
//! Read-only verbs. Every function returns its text instead of printing, so a
//! CLI, an MCP server, and a library caller share one implementation.

use anyhow::anyhow;

use crate::error::{Error, Result};
use chrono::{Local, NaiveDate};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::Write as _;

use crate::catalog::{CatalogService, load_recs};
use crate::config::Layout;
use crate::graph::DependencyGraph;
use crate::model::{IssueHeading, READY_STATES};
pub use crate::related::related;
use crate::store::{IssueDoc, find_by_id, find_org_ids, list_projects, load_all, project_selected};
use crate::views::{IssueRec, IssueRow, ListQuery};

struct GraphIndex<'a> {
    by_id: HashMap<&'a str, &'a IssueHeading>,
    children: HashMap<&'a str, Vec<&'a str>>,
    blockers: HashMap<&'a str, Vec<&'a str>>,
}

impl<'a> GraphIndex<'a> {
    fn new(all: &'a [(String, IssueHeading)]) -> Self {
        let mut index = Self {
            by_id: HashMap::with_capacity(all.len()),
            children: HashMap::new(),
            blockers: HashMap::new(),
        };
        for (_, h) in all {
            index.by_id.insert(h.id.as_str(), h);
        }
        for (_, h) in all {
            if let Some(parent) = h.parent() {
                index
                    .children
                    .entry(parent)
                    .or_default()
                    .push(h.id.as_str());
            }
            let blockers = blocker_ids(h);
            if !blockers.is_empty() {
                index.blockers.insert(h.id.as_str(), blockers);
            }
        }
        for children in index.children.values_mut() {
            children.sort_unstable();
        }
        index
    }
}

fn blocker_ids(h: &IssueHeading) -> Vec<&str> {
    let mut ids = Vec::new();
    if let Some(raw) = crate::props::get(&h.properties, crate::props::BLOCKED_BY) {
        ids.extend(
            raw.split(|c: char| c == ',' || c.is_whitespace())
                .map(str::trim)
                .filter(|id| !id.is_empty()),
        );
    }
    if let Some(raw) = h.properties.get("BLOCKER") {
        if crate::org::is_edna_blocker(raw) {
            ids.extend(crate::org::edna_blocker_id_refs(raw));
        } else {
            ids.extend(
                raw.split(|c: char| c == ',' || c.is_whitespace())
                    .map(str::trim)
                    .filter(|id| !id.is_empty()),
            );
        }
    }
    let mut unique = Vec::new();
    for id in ids {
        if !unique.contains(&id) {
            unique.push(id);
        }
    }
    unique
}

/// One row per issue: id, state, priority cookie, title.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn list(
    layout: &Layout,
    project_filter: Option<&str>,
    state_filter: Option<&str>,
    ready_only: bool,
) -> Result<String> {
    let recs = load_recs(layout)?;
    let rows = CatalogService::from_recs(&recs).issues_rows(ListQuery {
        project: project_filter.map(str::to_string),
        state: state_filter.map(str::to_string),
        ready: ready_only,
        ..ListQuery::default()
    })?;
    Ok(format_issue_rows(&recs, &rows))
}

fn format_issue_rows(recs: &[IssueRec], rows: &[IssueRow]) -> String {
    let mut out = String::new();
    for row in rows {
        let suffix = recs
            .iter()
            .find(|r| r.heading.id == row.id)
            .map(|r| claim_suffix(&r.heading))
            .unwrap_or_default();
        let _ = writeln!(
            out,
            "{:<22} {:<9} [#{}]  {}{}",
            row.id, row.state, row.priority, row.title, suffix
        );
    }
    out
}

/// ` (claimed 3d by <identity>)`, or nothing when no one holds the issue.
/// Only a claimed issue grows the suffix, so an unclaimed corpus renders
/// exactly as it did before claims existed.
pub(crate) fn claim_suffix(h: &IssueHeading) -> String {
    let Some(who) = h.claimed_by() else {
        return String::new();
    };
    match h.claim_age_days(Local::now().date_naive()) {
        Some(days) => format!("  (claimed {days}d by {who})"),
        None => format!("  (claimed by {who})"),
    }
}

/// Actionable issues: TODO or STARTED with no open blocker.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn ready(layout: &Layout, project_filter: Option<&str>) -> Result<String> {
    let recs = load_recs(layout)?;
    let rows = CatalogService::from_recs(&recs).ready(project_filter)?;
    Ok(format_issue_rows(&recs, &rows))
}

/// One issue's metadata, file range, and body text.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read, or `id` is not in it.
pub fn show(layout: &Layout, id: &str) -> Result<String> {
    let (h, path, project) =
        find_by_id(layout, id)?.ok_or_else(|| Error::IssueNotFound { id: id.to_string() })?;
    let mut out = String::new();
    writeln!(out, "ID:       {}", h.id)?;
    writeln!(out, "Project:  {project}")?;
    writeln!(out, "Title:    {}", h.title)?;
    writeln!(out, "State:    {}", h.state)?;
    writeln!(out, "Priority: [#{}]", h.priority)?;
    if let Some(who) = h.claimed_by() {
        match h.claim_age_days(Local::now().date_naive()) {
            Some(days) => writeln!(
                out,
                "Claimed:  {who} since {} ({days}d)",
                h.claimed_at().unwrap_or("?")
            )?,
            None => writeln!(out, "Claimed:  {who}")?,
        }
    }
    let settings = crate::org::tag_settings_from_preamble(
        &IssueDoc::parse_file(&project, &path)
            .map(|d| d.preamble)
            .unwrap_or_default(),
    );
    let tags = settings.all_tags(&h.tags());
    if !tags.is_empty() {
        writeln!(out, "Tags:     {}", tags.join(", "))?;
    }
    if h.properties.iter().any(|(k, _)| k != "ID") {
        writeln!(out, "Properties:")?;
        for (k, v) in &h.properties {
            if k == "ID" {
                continue;
            }
            writeln!(out, "  {k}: {v}")?;
        }
    }
    writeln!(
        out,
        "File:     {}:{}-{}",
        path.display(),
        h.line_start,
        h.line_end
    )?;
    writeln!(out)?;
    // The body is what the issue actually asks for, so printing the file
    // range and stopping leaves every reader to go fetch it by hand.
    let body = h.body.trim_end();
    if body.is_empty() {
        writeln!(out, "(no body; edit the range above to add one)")?;
    } else {
        writeln!(out, "Body:")?;
        writeln!(out, "{body}")?;
    }
    Ok(out)
}

/// Case-insensitive substring scan over id, title, properties, and body. Linear
/// in the corpus, which is the right cost until the issue count climbs.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn search(layout: &Layout, query: &str, limit: usize) -> Result<String> {
    let recs = load_recs(layout)?;
    let hits = CatalogService::from_recs(&recs).search(query, limit)?;
    let mut out = String::new();
    for h in hits {
        let _ = writeln!(
            out,
            "{:<22} {:<9} [#{}]  {}  ({})",
            h.id, h.state, h.priority, h.title, h.project
        );
    }
    Ok(out)
}

/// Issues whose `:PARENT:` points at `parent_id`.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn children(layout: &Layout, parent_id: &str) -> Result<String> {
    let mut rows: Vec<(String, IssueHeading)> = load_all(layout)?
        .into_iter()
        .filter(|(_, h)| h.parent() == Some(parent_id))
        .collect();
    rows.sort_by(|a, b| {
        a.1.priority
            .cmp(&b.1.priority)
            .then_with(|| a.1.state.cmp(&b.1.state))
            .then_with(|| a.1.id.cmp(&b.1.id))
    });
    let mut out = String::new();
    for (project, h) in rows {
        let _ = writeln!(
            out,
            "{:<22} {:<9} [#{}]  {}  ({})",
            h.id, h.state, h.priority, h.title, project
        );
    }
    Ok(out)
}

/// Open issues whose `:CREATED:` is at least `days` old. An issue without a
/// parseable date is never stale, because its age is unknown.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn stale(layout: &Layout, days: i64, project_filter: Option<&str>) -> Result<String> {
    let today = Local::now().date_naive();
    let cutoff = today - chrono::Duration::days(days);
    let mut rows: Vec<(String, IssueHeading, NaiveDate)> = Vec::new();
    for (project, h) in load_all(layout)? {
        if !project_selected(&project, project_filter) {
            continue;
        }
        if !READY_STATES.contains(&h.state.as_str()) {
            continue;
        }
        let Some(created) = h.properties.get("CREATED") else {
            continue;
        };
        let Some(parsed) = parse_org_date(created) else {
            continue;
        };
        if parsed <= cutoff {
            rows.push((project, h, parsed));
        }
    }
    rows.sort_by_key(|r| r.2);
    let mut out = String::new();
    for (project, h, created) in rows {
        let age = (today - created).num_days();
        let _ = writeln!(
            out,
            "{:<22} {:<9} [#{}]  {} ({}d, {})",
            h.id, h.state, h.priority, h.title, age, project
        );
    }
    Ok(out)
}

/// Every live claim, oldest first: the who-holds-what view. A claim is live
/// while its issue is STARTED or BLOCKED (release happens on TODO, DONE, or
/// CANCELLED), so this is the working set, not history.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read, or JSON serialization fails
/// when `json` is set.
pub fn claims(
    layout: &Layout,
    holder_filter: Option<&str>,
    project_filter: Option<&str>,
    json: bool,
) -> Result<String> {
    let recs = load_recs(layout)?;
    let rows = CatalogService::from_recs(&recs).claims(holder_filter, project_filter)?;

    if json {
        return Ok(format!("{}\n", serde_json::to_value(&rows)?));
    }

    let mut out = String::new();
    for row in &rows {
        let age_txt = if row.age_days < 0 {
            "?d".to_string()
        } else {
            format!("{}d", row.age_days)
        };
        let _ = writeln!(
            out,
            "{:<22} {:<9} [#{}]  {:>4}  {}  {} ({})",
            row.id,
            row.state,
            row.priority,
            age_txt,
            row.holder.as_deref().unwrap_or("?"),
            row.title,
            row.project
        );
    }
    if rows.is_empty() {
        out.push_str("no live claims\n");
    }
    Ok(out)
}

/// Dated open work in the next `days` days, plus anything already overdue.
/// One line per (issue, date kind): deadlines first within a day, soonest day
/// first, overdue on top with a negative day count.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn agenda(layout: &Layout, days: i64, project_filter: Option<&str>) -> Result<String> {
    let today = Local::now().date_naive();
    let horizon = today + chrono::Duration::days(days);
    // kind sorts D before S so a same-day deadline outranks a scheduled start.
    let mut rows: Vec<(NaiveDate, char, String, IssueHeading)> = Vec::new();
    for (project, h) in load_all(layout)? {
        if !project_selected(&project, project_filter) {
            continue;
        }
        if !READY_STATES.contains(&h.state.as_str()) && h.state != "BLOCKED" {
            continue;
        }
        for (kind, value) in [('D', h.deadline()), ('S', h.scheduled())] {
            let Some(parsed) = value.and_then(parse_org_date) else {
                continue;
            };
            if parsed <= horizon {
                rows.push((parsed, kind, project.clone(), h.clone()));
            }
        }
    }
    rows.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)).then(a.3.id.cmp(&b.3.id)));

    let mut out = String::new();
    for (date, kind, project, h) in rows {
        let delta = (date - today).num_days();
        let when = match delta {
            d if d < 0 => format!("{}d overdue", -d),
            0 => "today".to_string(),
            d => format!("in {d}d"),
        };
        let label = if kind == 'D' { "deadline" } else { "scheduled" };
        let _ = writeln!(
            out,
            "{date}  {label:<9} {when:<11} {:<22} {:<9} [#{}]  {}  ({})",
            h.id, h.state, h.priority, h.title, project
        );
    }
    if out.is_empty() {
        out.push_str("nothing dated in range\n");
    }
    Ok(out)
}

pub(crate) fn parse_org_date(s: &str) -> Option<NaiveDate> {
    let inner = s
        .trim_start_matches(['<', '['])
        .trim_end_matches(['>', ']']);
    let token = inner.split_whitespace().next()?;
    NaiveDate::parse_from_str(token, "%Y-%m-%d").ok()
}

/// The matching issue count and nothing else, for shell pipelines.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn count(
    layout: &Layout,
    project_filter: Option<&str>,
    state_filter: Option<&str>,
    ready_only: bool,
) -> Result<String> {
    let all = load_all(layout)?;
    let active_blockers: HashSet<String> = if ready_only {
        all.iter()
            .filter(|(_, h)| h.state != "DONE" && h.state != "CANCELLED")
            .map(|(_, h)| h.id.clone())
            .collect()
    } else {
        HashSet::new()
    };
    let n = all
        .iter()
        .filter(|(project, h)| {
            if !project_selected(project, project_filter) {
                return false;
            }
            if let Some(s) = state_filter
                && h.state != s
            {
                return false;
            }
            if ready_only {
                if !READY_STATES.contains(&h.state.as_str()) {
                    return false;
                }
                if blocker_ids(h).iter().any(|b| active_blockers.contains(*b)) {
                    return false;
                }
            }
            true
        })
        .count();
    Ok(format!("{n}\n"))
}

/// One JSON object per line: every property, the logbook, the body, and the
/// file line range. Round-trippable, and the seam other tools consume.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn export(layout: &Layout, project_filter: Option<&str>) -> Result<String> {
    let mut out = String::new();
    for rec in load_recs(layout)? {
        if !project_selected(&rec.project, project_filter) {
            continue;
        }
        let _ = writeln!(
            out,
            "{}",
            export_row(&rec.project, rec.heading, &rec.tag_settings)
        );
    }
    Ok(out)
}

/// The same lines as [`export`], grouped by project, from one read.
///
/// `export` filters a whole-corpus read down to one project, so digesting
/// every project separately re-read the corpus once per project: quadratic
/// in the project count, and six seconds on a tracker with a hundred of
/// them. The rows are built by the same function, so a project's text here
/// is byte for byte what `export(layout, Some(project))` returns, and the
/// digests taken from it do not move.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn export_by_project(layout: &Layout) -> Result<BTreeMap<String, String>> {
    let mut out: BTreeMap<String, String> = BTreeMap::new();
    for rec in load_recs(layout)? {
        let row = export_row(&rec.project, rec.heading, &rec.tag_settings);
        let _ = writeln!(out.entry(rec.project).or_default(), "{row}");
    }
    Ok(out)
}

fn export_row(
    project: &str,
    h: IssueHeading,
    settings: &crate::org::TagSettings,
) -> serde_json::Value {
    let logbook: Vec<serde_json::Value> = h
        .logbook
        .iter()
        .map(|e| {
            let mut row = serde_json::json!({
                "timestamp": e.timestamp,
                "from": e.from_state,
                "to": e.to_state,
                "note": e.note,
            });
            if let Some(raw) = &e.raw {
                row["raw"] = serde_json::Value::String(raw.clone());
            }
            row
        })
        .collect();
    serde_json::json!({
        "id": h.id,
        "project": project,
        "title": h.title,
        "state": h.state,
        "priority": h.priority.to_string(),
        "properties": h.properties,
        "org_tags": h.org_tags,
        "tags": h.tags(),
        "all_tags": settings.all_tags(&h.tags()),
        "logbook": logbook,
        "body": h.body,
        "line_start": h.line_start,
        "line_end": h.line_end,
    })
}

/// Children and blockers below `root_id`, as indented text or Graphviz DOT.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read, `root_id` is not in it, or
/// `format` is not `ascii`, `text`, or `dot`.
pub fn tree(layout: &Layout, root_id: &str, format: &str) -> Result<String> {
    let all = load_all(layout)?;
    let graph = GraphIndex::new(&all);
    let Some(root_heading) = graph.by_id.get(root_id) else {
        return Err(Error::IssueNotFound {
            id: root_id.to_string(),
        });
    };
    let mut out = String::new();
    let root = root_heading.id.as_str();
    match format {
        "ascii" | "text" => tree_ascii(&graph, root, 0, &mut HashSet::new(), &mut out),
        "dot" => tree_dot(&graph, root, &mut out),
        _ => return Err(anyhow!("unknown format {format:?}; allowed: ascii, dot").into()),
    }
    Ok(out)
}

fn tree_ascii<'a>(
    graph: &GraphIndex<'a>,
    id: &'a str,
    depth: usize,
    seen: &mut HashSet<&'a str>,
    out: &mut String,
) {
    if !seen.insert(id) {
        let _ = writeln!(out, "{}{id} (cycle, stopping)", "  ".repeat(depth));
        return;
    }
    let Some(h) = graph.by_id.get(id) else {
        let _ = writeln!(out, "{}{id} (missing)", "  ".repeat(depth));
        return;
    };
    let _ = writeln!(
        out,
        "{}{id} {:<9} [#{}]  {}",
        "  ".repeat(depth),
        h.state,
        h.priority,
        h.title
    );
    if let Some(blockers) = graph.blockers.get(id) {
        for blocker in blockers {
            let _ = writeln!(out, "{}* blocked-by {blocker}", "  ".repeat(depth + 1));
        }
    }
    if let Some(kids) = graph.children.get(id) {
        for k in kids {
            tree_ascii(graph, k, depth + 1, seen, out);
        }
    }
}

/// Escape text for a Graphviz quoted string. Backslash goes first, or the
/// escape introduced for a quote is itself re-escaped; a raw newline would end
/// the statement early. Titles and ids are whatever someone committed to the
/// tracker, so neither is trusted here.
pub(crate) fn dot_quoted(text: &str) -> String {
    text.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "")
}

fn tree_dot<'a>(graph: &GraphIndex<'a>, root_id: &str, out: &mut String) {
    let _ = writeln!(out, "digraph vissue_tree {{");
    let _ = writeln!(out, "  rankdir=LR;");
    let _ = writeln!(
        out,
        "  node [shape=box, fontname=\"Jost\", style=filled, fillcolor=\"#E0F2F1\"];"
    );
    let mut visited: HashSet<&str> = HashSet::new();
    let mut stack = vec![graph.by_id.get(root_id).unwrap().id.as_str()];
    while let Some(id) = stack.pop() {
        if !visited.insert(id) {
            continue;
        }
        if let Some(h) = graph.by_id.get(id) {
            let _ = writeln!(
                out,
                "  \"{}\" [label=\"{}\\n{} [#{}]\"];",
                dot_quoted(&h.id),
                dot_quoted(&h.title),
                dot_quoted(&h.state),
                dot_quoted(&h.priority.to_string())
            );
            if let Some(kids) = graph.children.get(id) {
                for k in kids {
                    let _ = writeln!(
                        out,
                        "  \"{}\" -> \"{}\" [color=\"#00897B\"];",
                        dot_quoted(&h.id),
                        dot_quoted(k)
                    );
                    stack.push(k);
                }
            }
            if let Some(blockers) = graph.blockers.get(id) {
                for b in blockers {
                    let _ = writeln!(
                        out,
                        "  \"{}\" -> \"{}\" [style=dashed, color=\"#FF7043\", label=\"blocks\"];",
                        dot_quoted(b),
                        dot_quoted(&h.id)
                    );
                    stack.push(b);
                }
            }
        }
    }
    let _ = writeln!(out, "}}");
}

/// Cycles in the blocker graph, one per line, or a line saying there are none.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn cycles(layout: &Layout) -> Result<String> {
    let all = load_all(layout)?;
    let graph = GraphIndex::new(&all);

    // Colored depth-first search over BLOCKED_BY edges. Grey marks the
    // current stack, black a finished node, so a shared blocker reached
    // from two branches (a diamond) is never mistaken for a cycle.
    const WHITE: u8 = 0;
    const GREY: u8 = 1;
    const BLACK: u8 = 2;
    let mut color: HashMap<&str, u8> = HashMap::new();
    let mut found: Vec<Vec<String>> = Vec::new();

    fn dfs<'a>(
        id: &'a str,
        graph: &GraphIndex<'a>,
        color: &mut HashMap<&'a str, u8>,
        path: &mut Vec<&'a str>,
        found: &mut Vec<Vec<String>>,
    ) {
        color.insert(id, GREY);
        path.push(id);
        if let Some(blockers) = graph.blockers.get(id) {
            for b in blockers {
                if !graph.by_id.contains_key(b) {
                    continue; // a broken edge cannot close a loop; `check` reports it
                }
                match color.get(b).copied().unwrap_or(WHITE) {
                    GREY => {
                        let start = path.iter().position(|&x| x == *b).unwrap();
                        let mut cycle: Vec<String> =
                            path[start..].iter().map(|s| s.to_string()).collect();
                        // Rotate so the smallest id leads: one canonical form
                        // per cycle no matter where the walk entered it.
                        let min = cycle
                            .iter()
                            .enumerate()
                            .min_by(|a, b| a.1.cmp(b.1))
                            .map(|(i, _)| i)
                            .unwrap();
                        cycle.rotate_left(min);
                        cycle.push(cycle[0].clone());
                        if !found.contains(&cycle) {
                            found.push(cycle);
                        }
                    }
                    WHITE => dfs(b, graph, color, path, found),
                    _ => {}
                }
            }
        }
        path.pop();
        color.insert(id, BLACK);
    }

    for (_, start) in &all {
        if color.get(start.id.as_str()).copied().unwrap_or(WHITE) == WHITE {
            let mut path = Vec::new();
            dfs(start.id.as_str(), &graph, &mut color, &mut path, &mut found);
        }
    }

    let mut out = String::new();
    if found.is_empty() {
        let _ = writeln!(out, "no cycles");
    } else {
        for cycle in found {
            let _ = writeln!(out, "{}", cycle.join(" -> "));
        }
    }
    Ok(out)
}

/// Transitive blocker ancestors, limited to a bounded number of hops.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read, the blocker graph cannot be
/// built, or `id` is not in it.
pub fn ancestors(layout: &Layout, id: &str, depth: usize) -> Result<String> {
    let graph = DependencyGraph::from_issues(&load_all(layout)?)?;
    let mut out = String::new();
    for (distance, ancestor) in graph.ancestors(id, depth)? {
        writeln!(out, "{distance} {ancestor}")?;
    }
    Ok(out)
}

/// Transitive issues waiting on this issue, limited to a bounded number of hops.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read, the blocker graph cannot be
/// built, or `id` is not in it.
pub fn impact(layout: &Layout, id: &str, depth: usize) -> Result<String> {
    let graph = DependencyGraph::from_issues(&load_all(layout)?)?;
    let mut out = String::new();
    for (distance, descendant) in graph.descendants(id, depth)? {
        writeln!(out, "{distance} {descendant}")?;
    }
    Ok(out)
}

/// The whole blocker and parent graph as Graphviz DOT. Node fill encodes state.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn graph(layout: &Layout, project_filter: Option<&str>) -> Result<String> {
    let all = load_all(layout)?;
    let graph = GraphIndex::new(&all);
    let mut out = String::new();
    writeln!(out, "digraph vissue_graph {{")?;
    writeln!(out, "  rankdir=LR;")?;
    writeln!(out, "  node [shape=box, fontname=\"Jost\", style=filled];")?;
    writeln!(out, "  edge [fontname=\"Jost\"];")?;
    for (project, h) in &all {
        if !project_selected(project, project_filter) {
            continue;
        }
        let fill = match h.state.as_str() {
            "DONE" => "#A5D6A7",
            "CANCELLED" => "#CFD8DC",
            "BLOCKED" => "#FFCC80",
            "STARTED" => "#80CBC4",
            _ => "#E0F2F1",
        };
        let _ = writeln!(
            out,
            "  \"{}\" [label=\"{}\\n{} [#{}]\", fillcolor=\"{}\"];",
            dot_quoted(&h.id),
            dot_quoted(&h.title),
            dot_quoted(&h.state),
            dot_quoted(&h.priority.to_string()),
            fill
        );
    }
    for (project, h) in &all {
        if !project_selected(project, project_filter) {
            continue;
        }
        if let Some(blockers) = graph.blockers.get(h.id.as_str()) {
            for b in blockers {
                writeln!(
                    out,
                    "  \"{}\" -> \"{}\" [color=\"#FF7043\"];",
                    dot_quoted(b),
                    dot_quoted(&h.id)
                )?;
            }
        }
        if let Some(parent) = h.parent() {
            writeln!(
                out,
                "  \"{}\" -> \"{}\" [color=\"#00897B\", style=dashed];",
                dot_quoted(parent),
                dot_quoted(&h.id)
            )?;
        }
    }
    writeln!(out, "}}")?;
    Ok(out)
}

/// A markdown roadmap grouped by project and state. Closed items collapse into
/// one section so the document stays about live work.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn roadmap(layout: &Layout, project_filter: Option<&str>) -> Result<String> {
    let all = load_all(layout)?;
    let mut by_project: BTreeMap<String, Vec<&IssueHeading>> = BTreeMap::new();
    for (project, h) in &all {
        if !project_selected(project, project_filter) {
            continue;
        }
        by_project.entry(project.clone()).or_default().push(h);
    }
    let mut out = String::new();
    writeln!(out, "# Roadmap")?;
    writeln!(out)?;
    writeln!(
        out,
        "Generated from `vissue roadmap`. Source of truth lives in the per-project issues.org files."
    )?;
    writeln!(out)?;
    for (project, mut headings) in by_project {
        headings.sort_by(|a, b| {
            a.priority
                .cmp(&b.priority)
                .then_with(|| a.state.cmp(&b.state))
                .then_with(|| a.id.cmp(&b.id))
        });
        let buckets = ["STARTED", "TODO", "BLOCKED"];
        let active: Vec<&&IssueHeading> = headings
            .iter()
            .filter(|h| buckets.contains(&h.state.as_str()))
            .collect();
        let closed: Vec<&&IssueHeading> = headings
            .iter()
            .filter(|h| h.state == "DONE" || h.state == "CANCELLED")
            .collect();
        if active.is_empty() && closed.is_empty() {
            continue;
        }
        writeln!(out, "## {project}")?;
        writeln!(out)?;
        for state in buckets {
            let in_state: Vec<&&IssueHeading> = active
                .iter()
                .copied()
                .filter(|h| h.state == state)
                .collect();
            if in_state.is_empty() {
                continue;
            }
            writeln!(out, "### {state}")?;
            writeln!(out)?;
            for h in in_state {
                let deadline = h
                    .deadline()
                    .map(|d| format!(" :: deadline {d}"))
                    .unwrap_or_default();
                let blockers = blocker_ids(h);
                let blocked_by = if blockers.is_empty() {
                    String::new()
                } else {
                    format!(" :: blocked by {}", blockers.join(", "))
                };
                writeln!(
                    out,
                    "- **{}** [#{}] {}{}{}",
                    h.id, h.priority, h.title, deadline, blocked_by
                )?;
            }
            writeln!(out)?;
        }
        if !closed.is_empty() {
            writeln!(out, "### Closed ({} items)", closed.len())?;
            writeln!(out)?;
            for h in closed.iter().take(10) {
                writeln!(
                    out,
                    "- {} [#{}] {} ({})",
                    h.id, h.priority, h.title, h.state
                )?;
            }
            if closed.len() > 10 {
                writeln!(out, "- ... and {} more", closed.len() - 10)?;
            }
            writeln!(out)?;
        }
    }
    Ok(out)
}

fn looks_like_reject_prose(body: &str) -> bool {
    let lower = body.to_ascii_lowercase();
    lower.contains("rejected") || lower.contains("vissue reject")
}

fn edge_connects(all: &[(String, IssueHeading)], a: &str, b: &str) -> bool {
    all.iter().any(|(_, h)| {
        if h.id == a {
            crate::props::get(&h.properties, crate::props::DISCOVERED_FROM) == Some(b)
                || crate::props::get(&h.properties, crate::props::PIVOTED_TO) == Some(b)
        } else if h.id == b {
            crate::props::get(&h.properties, crate::props::DISCOVERED_FROM) == Some(a)
                || crate::props::get(&h.properties, crate::props::PIVOTED_TO) == Some(a)
        } else {
            false
        }
    })
}

/// Outcome of [`check`]: the findings, and how many were errors.
#[derive(Debug, Clone)]
pub struct CheckReport {
    /// Rendered findings, ending in a summary line.
    pub text: String,
    /// Count of `[err]` findings.
    pub errors: usize,
    /// Count of `[warn]` findings.
    pub warnings: usize,
}

/// Validate the corpus: every parent and blocker id resolves, dates parse, open
/// issues carry a creation date, and ids are unique across projects.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn check(layout: &Layout) -> Result<CheckReport> {
    let all = load_all(layout)?;

    // A parent is usually another issue, and those ids are already in hand.
    // Only the ones that are not send us looking through the rest of the
    // tree, which on a tracker sharing a root with a notes vault is most of
    // the bytes on disk.
    let issue_ids: HashSet<&str> = all.iter().map(|(_, h)| h.id.as_str()).collect();
    let unresolved: HashSet<String> = all
        .iter()
        .filter_map(|(_, h)| h.parent())
        .filter(|p| !issue_ids.contains(p))
        .map(str::to_string)
        .collect();
    let elsewhere = find_org_ids(layout, &unresolved)?;
    let resolves = |id: &str| issue_ids.contains(id) || elsewhere.contains(id);

    let mut out = String::new();

    let mut errors = 0usize;
    let mut warnings = 0usize;

    let mut by_id: HashMap<String, (String, &IssueHeading)> = HashMap::new();
    for (project, h) in &all {
        if let Some(prev) = by_id.insert(h.id.clone(), (project.clone(), h)) {
            // An error, not a note: an id that names two issues makes every
            // blocker and parent edge pointing at it ambiguous.
            writeln!(
                out,
                "[err]  duplicate id: {} appears in {} and {}",
                h.id, prev.0, project
            )?;
            errors += 1;
        }
    }

    for project in list_projects(layout)? {
        let path = layout.project_issues_path(&project);
        let doc = IssueDoc::parse_file(&project, &path)?;
        match crate::org::protocol_from_preamble(&doc.preamble) {
            None => {
                writeln!(
                    out,
                    "[warn] {project}: preamble has no #+VISSUE: protocol stamp"
                )?;
                warnings += 1;
            }
            Some(n) if n < crate::org::PROTOCOL_VERSION => {
                writeln!(
                    out,
                    "[warn] {project}: #+VISSUE: {n} is behind protocol {}",
                    crate::org::PROTOCOL_VERSION
                )?;
                warnings += 1;
            }
            Some(n) if n > crate::org::PROTOCOL_VERSION => {
                writeln!(
                    out,
                    "[err]  {project}: #+VISSUE: {n} is newer than this vissue (protocol {})",
                    crate::org::PROTOCOL_VERSION
                )?;
                errors += 1;
            }
            Some(_) => {}
        }
        if !crate::org::preamble_has_keyword(&doc.preamble, "CATEGORY") {
            writeln!(
                out,
                "[warn] {project}: preamble has no #+CATEGORY: (org-agenda labels every row \"issues\")"
            )?;
            warnings += 1;
        }
        if !crate::org::preamble_has_keyword(&doc.preamble, "FILETAGS") {
            writeln!(out, "[warn] {project}: preamble has no #+FILETAGS:")?;
            warnings += 1;
        } else if !doc
            .tag_settings
            .filetags
            .iter()
            .any(|t| t.eq_ignore_ascii_case("noexport"))
        {
            writeln!(
                out,
                "[warn] {project}: #+FILETAGS: has no noexport; a vault publish will export this tracker"
            )?;
            warnings += 1;
        }
        if !crate::org::preamble_has_keyword(&doc.preamble, "TAGS") {
            writeln!(
                out,
                "[warn] {project}: preamble has no #+TAGS:; Emacs fast tag selection has no type group"
            )?;
            warnings += 1;
        }
        if !crate::org::preamble_has_keyword(
            &crate::org::merge_setupfile_settings(&doc.preamble, path.parent()),
            "PRIORITIES",
        ) {
            writeln!(
                out,
                "[warn] {project}: preamble has no #+PRIORITIES:; cookies default to C and the range is A..C"
            )?;
            warnings += 1;
        }
        let spec = doc.priority_spec();
        let mut type_not_tagged = 0usize;
        let mut exclusive_clash = 0usize;
        let mut priority_out_of_range = 0usize;
        let mut ordered_skip = 0usize;
        let mut done_with_open_children = 0usize;
        let mut gcal_ids = 0usize;
        let mut priority_in_drawer = 0usize;
        let mut blockedby_typo = 0usize;
        let mut blocker_as_ids = 0usize;
        let mut computed_specials = 0usize;
        let mut bad_effort = 0usize;
        for h in &doc.headings {
            if let Some(kind) = crate::props::get(&h.properties, crate::props::TYPE) {
                let kind = kind.trim();
                if !kind.is_empty()
                    && kind.chars().all(crate::model::is_org_tag_char)
                    && !h.org_tags.iter().any(|t| t == kind)
                {
                    type_not_tagged += 1;
                }
            }
            for group in &doc.tag_settings.exclusive {
                let hits = group
                    .iter()
                    .filter(|name| h.org_tags.iter().any(|t| t == *name))
                    .count();
                if hits > 1 {
                    exclusive_clash += 1;
                    break;
                }
            }
            if !spec.contains(h.priority) {
                priority_out_of_range += 1;
            }
            if crate::org::is_gcal_event_id(&h.id) {
                gcal_ids += 1;
            }
            if h.properties.contains_key("PRIORITY") {
                priority_in_drawer += 1;
            }
            if h.properties.contains_key("BLOCKEDBY") {
                blockedby_typo += 1;
            }
            if let Some(raw) = h.properties.get("BLOCKER")
                && !crate::org::is_edna_blocker(raw)
            {
                blocker_as_ids += 1;
            }
            if crate::org::COMPUTED_SPECIALS
                .iter()
                .any(|k| *k != "PRIORITY" && h.properties.contains_key(*k))
            {
                computed_specials += 1;
            }
            if let Some(effort) = h.effort()
                && !crate::org::is_org_effort(effort)
            {
                bad_effort += 1;
            }
            if let Some(pid) = h.parent()
                && let Some(parent) = doc.headings.iter().find(|p| p.id == pid)
                && crate::org::org_property_is_set(&parent.properties, "ORDERED")
                && !crate::org::org_property_is_set(&h.properties, "NOBLOCKING")
            {
                let earlier_open = doc.headings.iter().any(|sib| {
                    sib.parent() == Some(pid)
                        && sib.line_start < h.line_start
                        && sib.state != "DONE"
                        && sib.state != "CANCELLED"
                });
                if earlier_open && (h.state == "STARTED" || h.state == "DONE") {
                    ordered_skip += 1;
                }
            }
            if h.state == "DONE"
                && !crate::org::org_property_is_set(&h.properties, "NOBLOCKING")
                && doc.headings.iter().any(|c| {
                    c.parent() == Some(h.id.as_str()) && c.state != "DONE" && c.state != "CANCELLED"
                })
            {
                done_with_open_children += 1;
            }
        }
        if type_not_tagged > 0 {
            writeln!(
                out,
                "[warn] {project}: {type_not_tagged} heading(s) have :TYPE: that is a legal Org tag but is not on the heading"
            )?;
            warnings += 1;
        }
        if exclusive_clash > 0 {
            writeln!(
                out,
                "[warn] {project}: {exclusive_clash} heading(s) carry more than one tag from a #+TAGS: exclusive group"
            )?;
            warnings += 1;
        }
        if priority_in_drawer > 0 {
            writeln!(
                out,
                "[warn] {project}: {priority_in_drawer} heading(s) put :PRIORITY: in the drawer; Org reads the [#A] cookie"
            )?;
            warnings += 1;
        }
        if blockedby_typo > 0 {
            writeln!(
                out,
                "[warn] {project}: {blockedby_typo} heading(s) use :BLOCKEDBY: instead of :BLOCKED_BY:"
            )?;
            warnings += 1;
        }
        if blocker_as_ids > 0 {
            writeln!(
                out,
                "[warn] {project}: {blocker_as_ids} heading(s) use :BLOCKER: as a bare id list; a rewrite folds them into :BLOCKED_BY:"
            )?;
            warnings += 1;
        }
        if computed_specials > 0 {
            writeln!(
                out,
                "[warn] {project}: {computed_specials} heading(s) set a computed Org special (TODO/ITEM/TAGS/...) in the drawer; Org ignores it"
            )?;
            warnings += 1;
        }
        if bad_effort > 0 {
            writeln!(
                out,
                "[warn] {project}: {bad_effort} heading(s) have an Effort value Org will not parse"
            )?;
            warnings += 1;
        }
        if priority_out_of_range > 0 {
            writeln!(
                out,
                "[warn] {project}: {priority_out_of_range} heading(s) have a [#prio] outside #+PRIORITIES:"
            )?;
            warnings += 1;
        }
        if ordered_skip > 0 {
            writeln!(
                out,
                "[warn] {project}: {ordered_skip} heading(s) started or closed before an earlier ORDERED sibling"
            )?;
            warnings += 1;
        }
        if done_with_open_children > 0 {
            writeln!(
                out,
                "[warn] {project}: {done_with_open_children} DONE heading(s) still have open children (Org ORDERED / todo-dependencies)"
            )?;
            warnings += 1;
        }
        if gcal_ids > 0 {
            writeln!(
                out,
                "[err]  {project}: {gcal_ids} heading(s) use an org-gcal event id as :ID:"
            )?;
            errors += 1;
        }
    }

    for (project, h) in &all {
        if let Some(parent) = h.parent()
            && !resolves(parent)
        {
            writeln!(
                out,
                "[err]  {} (in {}) :PARENT: {} -> not found",
                h.id, project, parent
            )?;
            errors += 1;
        }
        for blk in blocker_ids(h) {
            if !by_id.contains_key(blk) {
                writeln!(
                    out,
                    "[err]  {} (in {}) :BLOCKED_BY: {} -> not found",
                    h.id, project, blk
                )?;
                errors += 1;
            }
        }
        if let Some(d) = h.deadline()
            && parse_org_date(d).is_none()
        {
            writeln!(
                out,
                "[err]  {} (in {}) :DEADLINE: {} -> unparseable",
                h.id, project, d
            )?;
            errors += 1;
        }
        if let Some(s) = h.scheduled()
            && parse_org_date(s).is_none()
        {
            writeln!(
                out,
                "[err]  {} (in {}) :SCHEDULED: {} -> unparseable",
                h.id, project, s
            )?;
            errors += 1;
        }
        if matches!(h.state.as_str(), "TODO" | "STARTED") && !h.properties.contains_key("CREATED") {
            writeln!(
                out,
                "[warn] {} (in {}) state={} but :CREATED: is missing",
                h.id, project, h.state
            )?;
            warnings += 1;
        }
        if h.state == "DONE" && looks_like_reject_prose(&h.body) {
            writeln!(
                out,
                "[warn] {} (in {}) is DONE but the body reads as a reject",
                h.id, project
            )?;
            warnings += 1;
        }
        if crate::props::get(&h.properties, crate::props::SIBLING_TERMINAL).is_some() {
            writeln!(
                out,
                "[warn] {} (in {}) holds {} and sibling {}",
                h.id,
                project,
                h.state,
                crate::props::get(&h.properties, crate::props::SIBLING_TERMINAL).unwrap_or("?")
            )?;
            warnings += 1;
        }
    }

    let known: HashSet<&str> = all.iter().map(|(_, h)| h.id.as_str()).collect();
    for (project, h) in &all {
        for linked in crate::related::org_link_targets(&h.body, &known) {
            if edge_connects(&all, &h.id, &linked) {
                continue;
            }
            writeln!(
                out,
                "[warn] {} (in {}) mentions [[id:{}]] with no DISCOVERED_FROM or PIVOTED_TO either way",
                h.id, project, linked
            )?;
            warnings += 1;
        }
    }

    // A :PARENT: loop passes every edge check, because each id resolves, yet
    // it makes the hierarchy unwalkable: `tree` stops on it and prints
    // "(cycle, stopping)". Naming it here is what keeps a corpus that holds
    // one from reading as clean.
    let mut settled: HashSet<&str> = HashSet::new();
    for (_, h) in &all {
        if settled.contains(h.id.as_str()) {
            continue;
        }
        let mut path: Vec<&str> = Vec::new();
        let mut on_path: HashSet<&str> = HashSet::new();
        let mut cursor = h.id.as_str();
        loop {
            if settled.contains(cursor) {
                break;
            }
            if !on_path.insert(cursor) {
                let start = path.iter().position(|id| *id == cursor).unwrap_or(0);
                let mut loop_ids: Vec<&str> = path[start..].to_vec();
                loop_ids.push(cursor);
                writeln!(out, "[err]  parent cycle: {}", loop_ids.join(" -> "))?;
                errors += 1;
                break;
            }
            path.push(cursor);
            match by_id.get(cursor).and_then(|(_, owner)| owner.parent()) {
                Some(parent) if by_id.contains_key(parent) => cursor = parent,
                _ => break,
            }
        }
        settled.extend(path);
    }

    if errors == 0
        && let Err(err) = DependencyGraph::from_issues(&all)
    {
        writeln!(out, "[err]  blocker graph: {err}")?;
        errors += 1;
    }

    writeln!(out)?;
    writeln!(
        out,
        "checked {} issue(s) across {} project(s): {} error(s), {} warning(s)",
        all.len(),
        list_projects(layout)?.len(),
        errors,
        warnings
    )?;
    Ok(CheckReport {
        text: out,
        errors,
        warnings,
    })
}

/// Every issue referring to `target_id` through a blocker edge, a parent link,
/// a discovered-from or pivoted-to property, or a body mention. The relation
/// is named on the row.
///
/// # Errors
///
/// Returns an error if the corpus cannot be read.
pub fn backlinks(layout: &Layout, target_id: &str) -> Result<String> {
    let all = load_all(layout)?;
    let mut out = String::new();
    for (project, h) in &all {
        if h.id == target_id {
            continue;
        }
        let mut hit = false;
        if blocker_ids(h).contains(&target_id) {
            let _ = writeln!(out, "{:<22} (blocked-by) ({})", h.id, project);
            hit = true;
        }
        if h.parent() == Some(target_id) {
            let _ = writeln!(out, "{:<22} (parent) ({})", h.id, project);
            hit = true;
        }
        if crate::props::get(&h.properties, crate::props::DISCOVERED_FROM) == Some(target_id) {
            let _ = writeln!(out, "{:<22} (discovered-from) ({})", h.id, project);
            hit = true;
        }
        if crate::props::get(&h.properties, crate::props::PIVOTED_TO) == Some(target_id) {
            let _ = writeln!(out, "{:<22} (pivoted-to) ({})", h.id, project);
            hit = true;
        }
        if !hit && h.body.contains(target_id) {
            let _ = writeln!(out, "{:<22} (body mention) ({})", h.id, project);
        }
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dot_labels_escape_untrusted_issue_text() {
        assert_eq!(dot_quoted(r#"a "quoted" title"#), r#"a \"quoted\" title"#);
        // A trailing backslash would otherwise escape the closing quote and
        // let the rest of the title become DOT syntax.
        assert_eq!(dot_quoted(r"ends with\"), r"ends with\\");
        assert_eq!(dot_quoted("two\nlines"), "two\\nlines");
    }
}