tix-tracker 0.12.0

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

use crate::assignee::{AuthorIdentity, git_identity, resolve_me};
use crate::commands::{parse_csv_list, parse_priority};
use crate::config::Config;
use crate::editor::read_tty_line;
use crate::error::{Result, TixError};
use crate::hierarchy;
use crate::model::{HistoryEventKind, Issue, Priority, Status, today};
use crate::planning::Planner;
use crate::storage::Store;

/// `tix create`: write a new issue file. When `--title` is omitted on a
/// TTY the user is prompted interactively; on a pipe the absence is a hard
/// usage error (exit 1, never blocks on stdin).
#[allow(clippy::too_many_arguments)]
pub fn run(
    config: &Config,
    store: &Store,
    title: Option<&str>,
    body: Option<&str>,
    status: Option<&str>,
    priority: Option<&str>,
    assignee: Option<&str>,
    labels: Option<&str>,
    files: Option<&str>,
    estimate: Option<&str>,
    cycles: Option<&str>,
    milestones: Option<&str>,
    projects: Option<&str>,
    epics: Option<&str>,
    reviewer: Option<&str>,
    start_date: Option<&str>,
    due_date: Option<&str>,
    parent: Option<&str>,
    related_issues: Option<&str>,
    type_: Option<&str>,
) -> Result<()> {
    let title = match title {
        Some(t) => {
            let trimmed = t.trim().to_string();
            if trimmed.is_empty() {
                return Err(TixError::InvalidInput("--title must not be empty".into()));
            }
            trimmed
        }
        None => {
            if !std::io::stdin().is_terminal() {
                return Err(TixError::InvalidInput(
                    "title is required (stdin is not a TTY); pass --title".into(),
                ));
            }
            let t = read_tty_line("Title: ")?;
            if t.is_empty() {
                return Err(TixError::InvalidInput("title must not be empty".into()));
            }
            t
        }
    };
    let status = match status {
        None => None,
        Some(s) if s.trim().is_empty() => {
            return Err(TixError::InvalidInput("--status must not be empty".into()));
        }
        Some(s) => Some(Status::new(s.to_string())),
    };
    let priority = match priority {
        Some(p) => Some(parse_priority(p)?),
        None => None,
    };
    // `--projects` is resolved and validated through the project service **before**
    // the issue is written, so an unknown id refuses the whole create rather than
    // leaving a half-associated issue (T022 step 3). Duplicates collapse to one id.
    //
    // The flag lives on this shared create path rather than in a bespoke command
    // because a future **template** surface (source issue #174, research R7) will
    // populate the same field; a second create path would be a second set of
    // defaults that drift. A template surface today refuses the flag explicitly
    // rather than dropping it.
    let project_ids = match projects {
        None => Vec::new(),
        Some(raw) => crate::commands::project::resolve_projects(config, raw)?,
    };
    // `--epics` is resolved and validated through the epic service **before** the
    // issue is written, so an unknown epic refuses the whole create rather than
    // leaving a half-referenced issue (FR-004). Duplicates collapse to one id.
    //
    // Referencing an epic does **not** turn the issue into a task entity: it stays
    // an ordinary issue that carries an id (C-001), and direct navigation
    // (`tix show <n>`) is unchanged. `--labels task --epics <id>` is exactly this
    // path plus a label.
    let epic_ids = match epics {
        None => Vec::new(),
        Some(raw) => crate::commands::epic::resolve_epics(config, raw)?,
    };
    let issue = create(
        config,
        store,
        &title,
        body,
        status,
        priority,
        assignee,
        labels,
        files,
        estimate,
        cycles,
        milestones,
        reviewer,
        start_date,
        due_date,
        parent,
        related_issues,
        type_,
    )?;
    // Each accepted association appends exactly one `## History` entry, through the
    // store's service-backed `associate`; the create core itself stays free of
    // project rules (T022 step 4).
    crate::commands::project::associate_created(store, &issue, &project_ids)?;
    // Each accepted reference appends exactly one `## History` entry, through the
    // store's service-backed `reference_epic`; the create core stays free of epic
    // rules (T024 step 4).
    crate::commands::epic::reference_created(store, &issue, &epic_ids)?;
    println!("Created {}", issue.filename);
    Ok(())
}

/// The create core (WP02): build and persist a new issue from explicit
/// arguments, returning the created [`Issue`] (its `filename` is the
/// relative path, already set by [`Store::create`]).
///
/// This is what MCP's `create_issue` tool (WP04) calls with normalized
/// arguments, so defaults and validation live here once and the CLI and the
/// protocol share them (NFR-005). Side-effect policy: the interactive
/// `--title` prompt stays in [`run`] (C-005); this core never reads
/// `stdin`/writes `stdout` and only touches the store. A trimmed-but-empty
/// title is rejected here exactly as the CLI rejects it.
#[allow(clippy::too_many_arguments)]
#[allow(clippy::too_many_lines)]
pub fn create(
    config: &Config,
    store: &Store,
    title: &str,
    body: Option<&str>,
    status: Option<Status>,
    priority: Option<Priority>,
    assignee: Option<&str>,
    labels: Option<&str>,
    files: Option<&str>,
    estimate: Option<&str>,
    cycles: Option<&str>,
    milestones: Option<&str>,
    reviewer: Option<&str>,
    start_date: Option<&str>,
    due_date: Option<&str>,
    parent: Option<&str>,
    related_issues: Option<&str>,
    type_: Option<&str>,
) -> Result<Issue> {
    let title = title.trim().to_string();
    if title.is_empty() {
        return Err(TixError::InvalidInput("--title must not be empty".into()));
    }
    let status = match status {
        None => Status::new(
            config
                .default_config()
                .columns
                .first()
                .cloned()
                .unwrap_or_else(|| "todo".to_string()),
        ),
        Some(s) if s.0.trim().is_empty() => {
            return Err(TixError::InvalidInput("--status must not be empty".into()));
        }
        Some(s) => {
            // WP05: a **column check**, and only that.
            //
            // This was the recorded WP04 decision — "create gets a column check
            // only; import is exempt" — and the check itself was never implemented.
            // WP05 found it by typing a status into the TUI's free-text form: the
            // create succeeded and wrote a column the board does not configure, so
            // every category-derived surface then reported the issue as `(unmapped)`
            // and no transition could ever move it anywhere.
            //
            // A column check, deliberately, and **not** a transition evaluation. There
            // is no `from` to judge: a new issue is not leaving anywhere, so the
            // terminal lock and adjacency have nothing to say about it. Creating an
            // issue directly in a terminal column is legitimate — that is how a
            // triaged or cancelled backlog item arrives.
            //
            // Reported through the service so the diagnostic is the shared
            // `unknown_column` (contract §6) and the message carries the
            // valid-column list, rather than a third spelling of "no such column".
            let (_, resolution) = crate::workflow::active_resolution(config);
            if resolution.resolve(s.0.trim()).is_none() {
                return Err(TixError::Workflow(crate::workflow::WorkflowDiagnostic {
                    kind: crate::workflow::DiagnosticKind::UnknownColumn,
                    subject: format!("create -> {}", s.0.trim()),
                    message: format!(
                        "`{}` is not a column on board `{}`; valid columns: {}",
                        s.0.trim(),
                        resolution.board,
                        resolution.column_list()
                    ),
                }));
            }
            s
        }
    };
    let priority = priority.unwrap_or_default();
    let assignee = resolve_assignee(assignee, git_identity().as_ref());
    let labels: Vec<String> = match labels {
        None => vec![],
        Some(l) => l
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect(),
    };
    let files: Vec<String> = match files {
        None => vec![],
        Some(f) => crate::commands::parse_csv_list(f),
    };
    let related_issues: Vec<String> = match related_issues {
        None => vec![],
        Some(r) => crate::commands::parse_csv_list(r),
    };
    let type_ = type_
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(String::from);
    let cycles = parse_planning(cycles).or_else(|| Some(vec![default_cycle_name(config)]));
    let milestones = parse_planning(milestones);
    let reviewer = reviewer
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string);
    let start = parse_date(start_date);
    let due = parse_date(due_date);
    validate_planning_inputs(config, cycles.as_deref(), milestones.as_deref())?;

    // `--parent` is resolved and validated through the hierarchy service **before**
    // the issue is built, so a bad parent creates nothing at all — not a file, not a
    // number, not a History entry.
    //
    // This flag lives in the shared create core rather than in a bespoke command
    // because a **template** surface (issue #174, research R1) will populate the
    // same field. A separate `tix child create` would have a second create path, and
    // two create paths are two sets of defaults that drift.
    let (parent_ref, parent_number) = match parent.map(str::trim).filter(|p| !p.is_empty()) {
        None => (None, None),
        Some(raw) => {
            let target = store.resolve_issue(raw)?;
            let (index, _) = store.hierarchy_index()?;
            // `validate_new_parent`, not `set_parent`: the child does not exist yet,
            // so it cannot be its own parent and cannot close a cycle. Only
            // `unknown_parent` can bite, and the service is what names it.
            hierarchy::validate_new_parent(&index, target.number)?;
            (Some(crate::id::canonical_ref(&target)), Some(target.number))
        }
    };

    let mut issue = Issue {
        projects: None,
        id: None,
        number: 0,
        type_,
        title,
        status,
        labels,
        priority,
        assignee,
        estimate: estimate.map(String::from),
        commit: None,
        gitlab_id: None,
        linear_id: None,
        mission: None,
        task: None,
        // Relationships are set after the issue is written, so the canonical
        // edge lands in the right file (see `Store::set_relationships`).
        relationships: vec![],
        related_issues,
        files,
        cycles,
        milestones,
        reviewer,
        start_date: None,
        due_date: None,
        created: today(),
        updated: today(),
        filename: String::new(),
        body: String::new(),
        history: crate::model::History::new(),
        has_retired_links_key: false,
        time_entries: vec![],
        parent: parent_ref,
        series: None,
        health: None,
        epics: None,
        extra_frontmatter: std::collections::BTreeMap::new(),
        archived: false,
        entered_at: None,
        source: None,
    };
    issue.set_dates(start, due)?;
    // Exactly one History entry, naming the parent (C-004). Appended to the
    // in-memory issue so `store.create` writes it with the first content — an
    // entry that only appeared on a later `tix edit` would describe a create that
    // did not happen this way.
    if let Some(number) = parent_number {
        issue.history.append_now(
            &crate::storage::actor_identity(),
            HistoryEventKind::ParentSet,
            &hierarchy::change_detail(None::<u32>, Some(number)),
        );
    }
    // A new issue that lands in the inbox has *entered triage*, so it records an entry
    // stamp exactly as an import does — data-model §2's `new` origin. The rule lives in
    // `triage::record_entry_if_inbox` so no create path can be the one that forgets it,
    // and so `--status todo` still gains nothing — stamping it would claim a wait that
    // never started.
    crate::triage::record_entry_if_inbox(config, &mut issue, "new")?;
    store.create(&mut issue, body.unwrap_or(""), None)?;
    Ok(issue)
}

/// The cycle a new issue joins when the caller names none (tui-cycle-mode).
///
/// The single cycle **running today** when exactly one runs (see
/// [`Planner::running_cycle`]); otherwise the configured
/// `[planning].default_cycle` when it names a cycle that actually exists;
/// otherwise the implicit `Default` cycle — which every project has, file or no
/// file. Ambiguity (zero or several running cycles) falls back rather than
/// guesses. The CLI core and the TUI form both route through this one function,
/// so "no explicit selection" has a single answer.
pub fn default_cycle_name(config: &Config) -> String {
    let planner = planner_for(config);
    if let Some(running) = planner.running_cycle(&crate::model::today()) {
        return running;
    }
    config
        .planning
        .default_cycle
        .clone()
        .filter(|name| planner.cycle(name).is_some())
        .unwrap_or_else(|| crate::cycle_store::DEFAULT_CYCLE_NAME.to_string())
}

/// Split a `--cycles`/`--milestones` value into an ordered, deduplicated list
/// (first-seen order preserved — the same collapse rule the model serializers
/// apply on write). `None` when the flag is absent; a blank or all-empty CSV
/// normalizes to `None` too (`--cycles ""` on create means "no cycles" — and a
/// create with no cycles joins the default cycle, see [`default_cycle_name`]).
pub(crate) fn parse_planning(raw: Option<&str>) -> Option<Vec<String>> {
    let items: Vec<String> = parse_csv_list(raw.unwrap_or(""))
        .into_iter()
        .fold((Vec::new(), HashSet::new()), |(mut out, mut seen), item| {
            if seen.insert(item.clone()) {
                out.push(item);
            }
            (out, seen)
        })
        .0;
    if items.is_empty() { None } else { Some(items) }
}

/// Trim a `--start-date`/`--due-date` value; a blank value means "no date"
/// (`None`), a non-blank one is passed through verbatim for validation.
pub(crate) fn parse_date(raw: Option<&str>) -> Option<String> {
    let trimmed = raw.map(str::trim).unwrap_or("");
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// A [`Planner`] snapshot for the config at hand.
///
/// The CLI and MCP surfaces absolutize `milestones_dir` against the repo root
/// before reaching the cores; unit tests configure it absolutely. A still
/// relative value (direct core calls) resolves against the current working
/// directory — the same repo-root assumption `Planner::load` documents.
///
/// Shared with `lint` so reference checking resolves the registry exactly as
/// the create/edit validators do.
pub(crate) fn planner_for(config: &Config) -> Planner {
    let root = if config.milestones_dir().is_absolute() {
        std::path::PathBuf::new()
    } else {
        std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))
    };
    Planner::from_config(config.clone(), root)
}

/// Validate user-supplied planning references (FR-005): every `cycles` name
/// must name a `[cycles.<name>]` config entry and every `milestones` name a
/// milestone file in the configured `milestones_dir`. Both lookups go through
/// the WP01 `Planner` — no copied rules. Empty/absent lists are `None`.
///
/// This is the shared validation path T009–T012 all route through, so the CLI
/// and the MCP tools reject identical input with the identical `TixError`
/// message (`InvalidInput`, surfaced verbatim by both).
pub fn validate_planning_inputs(
    config: &Config,
    cycles: Option<&[String]>,
    milestones: Option<&[String]>,
) -> Result<()> {
    let planner = planner_for(config);
    if let Some(cycles) = cycles {
        for name in cycles {
            if planner.cycle(name).is_none() {
                let known = planner.cycle_names();
                let list = if known.is_empty() {
                    "none configured".to_string()
                } else {
                    known.join(", ")
                };
                return Err(TixError::InvalidInput(format!(
                    "unknown cycle `{name}` — valid cycles: {list}"
                )));
            }
        }
    }
    if let Some(milestones) = milestones {
        for name in milestones {
            if planner.milestone(name).is_err() {
                let known = planner.milestone_names().unwrap_or_default();
                let list = if known.is_empty() {
                    "none configured".to_string()
                } else {
                    known.join(", ")
                };
                return Err(TixError::InvalidInput(format!(
                    "unknown milestone `{name}` — valid milestones: {list}"
                )));
            }
        }
    }
    Ok(())
}

/// Resolve the effective assignee for a new issue (FR-028):
/// - an explicit `--assignee` value always wins (`parse_assignee` normalizes
///   `@alice` to `alice` for storage and lets full identities pass through
///   verbatim; `@me` resolves to the git identity; an empty value means
///   unassigned),
/// - otherwise the git author identity is used when one can be resolved,
/// - with neither, the issue stays unassigned (`unassigned/` segment) — a
///   missing/unconfigured git is never a hard error (spec §unassigned).
fn resolve_assignee(explicit: Option<&str>, identity: Option<&AuthorIdentity>) -> Option<String> {
    match explicit {
        Some(value) => resolve_me(value, identity),
        None => identity.map(|id| id.to_string()),
    }
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    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(),
            milestones_dir: Some(tmp.path().join("docs/milestones")),
            ..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,
            },
        )
    }

    /// Seed one milestone file into the store's configured milestones dir.
    fn seed_milestone(store: &Store, name: &str) {
        crate::planning::Planner::from_config(store.config.clone(), std::path::PathBuf::new())
            .create_milestone_file(name, None, None)
            .unwrap();
    }

    #[test]
    fn explicit_assignee_wins_over_identity() {
        let identity = AuthorIdentity {
            name: "Herb".into(),
            email: Some("herb@example.com".into()),
        };
        assert_eq!(
            resolve_assignee(Some("@alice"), Some(&identity)),
            Some("alice".into())
        );
        assert_eq!(
            resolve_assignee(Some(""), Some(&identity)),
            None,
            "an explicit empty assignee means unassigned"
        );
    }

    #[test]
    fn me_assignee_resolves_to_git_identity() {
        let identity = AuthorIdentity {
            name: "Herb".into(),
            email: Some("herb@example.com".into()),
        };
        assert_eq!(
            resolve_assignee(Some("@me"), Some(&identity)),
            Some("Herb <herb@example.com>".into())
        );
        assert_eq!(
            resolve_assignee(Some("me"), Some(&identity)),
            Some("Herb <herb@example.com>".into())
        );
    }

    #[test]
    fn no_explicit_assignee_uses_full_identity_verbatim() {
        let identity = AuthorIdentity {
            name: "Herb".into(),
            email: Some("herb@example.com".into()),
        };
        assert_eq!(
            resolve_assignee(None, Some(&identity)),
            Some("Herb <herb@example.com>".into())
        );
        let name_only = AuthorIdentity {
            name: "Herb".into(),
            email: None,
        };
        assert_eq!(
            resolve_assignee(None, Some(&name_only)),
            Some("Herb".into())
        );
    }

    #[test]
    fn no_explicit_and_no_identity_means_unassigned() {
        assert_eq!(resolve_assignee(None, None), None);
    }

    #[test]
    fn create_defaults_status_priority_labels_and_assignee() {
        let (_tmp, store) = make_store();
        let issue = create(
            &store.config,
            &store,
            "  Hello World  ",
            None,
            None,
            None,
            Some(""),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(issue.title, "Hello World", "title is trimmed");
        assert_eq!(issue.status.display(), "todo", "default = first column");
        assert_eq!(issue.priority, Priority::Medium, "default priority");
        assert_eq!(issue.labels, [] as [std::string::String; 0]);
        assert_eq!(issue.assignee, None, "empty assignee → unassigned");
        assert_eq!(issue.estimate, None);
        assert!(
            issue.filename.starts_with("unassigned/"),
            "no assignee segment"
        );
        assert!(issue.filename.ends_with(".md"));
        // Persisted: number assigned from [state] counter, readable back.
        let reloaded = store
            .get(crate::storage::IssueSelector::Number(issue.number))
            .unwrap();
        assert_eq!(reloaded.title, "Hello World");
    }

    #[test]
    fn create_passes_explicit_arguments_through() {
        let (_tmp, mut store) = make_store();
        store
            .config
            .cycles
            .insert("Cycle 1".into(), crate::config::PlanningCycle::default());
        store
            .config
            .cycles
            .insert("Sprint 9".into(), crate::config::PlanningCycle::default());
        seed_milestone(&store, "v1.0");
        let issue = create(
            &store.config,
            &store,
            "Explicit",
            Some("the body"),
            Some(Status::new("in progress")),
            Some(Priority::High),
            Some("@alice"),
            Some("bug, docs, "),
            Some("specs/a.md, specs/b.md"),
            Some("3d"),
            Some("Cycle 1, Sprint 9"),
            Some("v1.0"),
            Some("Bob <bob@example.com>"),
            Some("2026-09-07"),
            Some("2026-09-18"),
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(issue.title, "Explicit");
        assert_eq!(issue.body, "the body");
        assert_eq!(issue.status.display(), "in progress");
        assert_eq!(issue.priority, Priority::High);
        assert_eq!(issue.assignee.as_deref(), Some("alice"));
        assert_eq!(issue.estimate.as_deref(), Some("3d"));
        assert_eq!(
            issue.labels,
            vec!["bug".to_string(), "docs".to_string()],
            "label list is split on commas and empty entries dropped"
        );
        assert_eq!(
            issue.files,
            vec!["specs/a.md".to_string(), "specs/b.md".to_string()]
        );
        assert_eq!(
            issue.cycles,
            Some(vec!["Cycle 1".to_string(), "Sprint 9".to_string()]),
            "cycle CSV parsed into a deduplicated list"
        );
        assert_eq!(issue.milestones, Some(vec!["v1.0".to_string()]));
        assert_eq!(issue.reviewer.as_deref(), Some("Bob <bob@example.com>"));
        assert_eq!(issue.start_date.as_deref(), Some("2026-09-07"));
        assert_eq!(issue.due_date.as_deref(), Some("2026-09-18"));
    }

    #[test]
    fn create_rejects_blank_title_and_blank_status() {
        let (_tmp, store) = make_store();
        assert!(
            create(
                &store.config,
                &store,
                "   ",
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .is_err()
        );
        assert!(
            create(
                &store.config,
                &store,
                "T",
                None,
                Some(Status::new("")),
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .is_err(),
            "a caller-supplied blank status is rejected like --status ''"
        );
    }

    #[test]
    fn parse_planning_dedupes_and_normalizes() {
        assert_eq!(
            parse_planning(Some("Cycle 1, Sprint 9, Cycle 1")),
            Some(vec!["Cycle 1".to_string(), "Sprint 9".to_string()]),
            "first-seen order preserved, duplicates collapsed"
        );
        assert_eq!(parse_planning(Some("")), None);
        assert_eq!(parse_planning(Some(", , ,")), None);
        assert_eq!(parse_planning(None), None);
        assert_eq!(
            parse_date(Some("2026-09-07")),
            Some("2026-09-07".to_string())
        );
        assert_eq!(
            parse_date(Some(" 2026-09-07  ")),
            Some("2026-09-07".to_string())
        );
        assert_eq!(parse_date(Some("")), None);
        assert_eq!(parse_date(None), None);
    }

    #[test]
    fn create_rejects_unknown_cycle_with_valid_list() {
        let (_tmp, mut store) = make_store();
        store
            .config
            .cycles
            .insert("Cycle 1".into(), crate::config::PlanningCycle::default());
        let err = create(
            &store.config,
            &store,
            "T",
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            Some("Nope, Cycle 1"),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap_err();
        assert!(matches!(err, TixError::InvalidInput(_)), "got {err:?}");
        assert!(
            err.to_string().contains("unknown cycle `Nope`"),
            "got {err}"
        );
        assert!(
            err.to_string().contains("valid cycles: Cycle 1"),
            "must name the valid set, got {err}"
        );
    }

    #[test]
    fn create_rejects_unknown_milestone_with_valid_list() {
        let (_tmp, store) = make_store();
        seed_milestone(&store, "v1.0");
        let err = create(
            &store.config,
            &store,
            "T",
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            Some("v1.0, nope-milestone"),
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap_err();
        assert!(matches!(err, TixError::InvalidInput(_)), "got {err:?}");
        assert!(
            err.to_string()
                .contains("unknown milestone `nope-milestone`"),
            "got {err}"
        );
        assert!(
            err.to_string().contains("valid milestones: v1.0"),
            "must name the valid set, got {err}"
        );
        assert!(
            store.list().unwrap().is_empty(),
            "a rejected create must not write an issue file"
        );
    }

    #[test]
    fn create_rejects_due_before_start() {
        let (_tmp, store) = make_store();
        let err = create(
            &store.config,
            &store,
            "T",
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            Some("2026-09-18"),
            Some("2026-09-07"),
            None,
            None,
            None,
        )
        .unwrap_err();
        assert_eq!(
            err.to_string(),
            "config error: due_date \"2026-09-07\" must be `>= start_date` \"2026-09-18\""
        );
        assert_eq!(store.list().unwrap(), [] as [crate::model::Issue; 0]);
    }

    #[test]
    fn create_rejects_malformed_date() {
        let (_tmp, store) = make_store();
        let err = create(
            &store.config,
            &store,
            "T",
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            Some("2026-13-99"),
            None,
            None,
            None,
            None,
        )
        .unwrap_err();
        assert!(
            err.to_string()
                .contains("start_date \"2026-13-99\" must be a `YYYY-MM-DD` calendar date"),
            "got {err}"
        );
        assert_eq!(store.list().unwrap(), [] as [crate::model::Issue; 0]);
    }

    #[test]
    fn create_without_a_cycle_selection_joins_the_default_cycle() {
        let (_tmp, store) = make_store();
        let issue = create(
            &store.config,
            &store,
            "Plain",
            None,
            None,
            None,
            Some(""),
            None,
            None,
            None,
            Some(""),
            Some(""),
            Some(""),
            Some(""),
            Some(""),
            None,
            None,
            None,
        )
        .unwrap();
        // No explicit `--cycles` (and even a blank one) joins the default
        // cycle; the other empty planning values stay absent.
        assert_eq!(issue.cycles, Some(vec!["Default".to_string()]));
        assert_eq!(issue.milestones, None);
        assert_eq!(issue.reviewer, None);
        assert_eq!(issue.start_date, None);
        assert_eq!(issue.due_date, None);
        let reloaded = store
            .get(crate::storage::IssueSelector::Number(issue.number))
            .unwrap();
        assert_eq!(reloaded.cycles, Some(vec!["Default".to_string()]));
    }

    #[test]
    fn create_uses_the_configured_default_cycle_when_it_exists() {
        let (_tmp, mut store) = make_store();
        store
            .config
            .cycles
            .insert("Sprint 1".into(), crate::config::PlanningCycle::default());
        store.config.planning.default_cycle = Some("Sprint 1".into());
        let issue = create(
            &store.config,
            &store,
            "Configured",
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(issue.cycles, Some(vec!["Sprint 1".to_string()]));
    }

    fn cycle_with(start: Option<&str>, due: Option<&str>) -> crate::config::PlanningCycle {
        crate::config::PlanningCycle {
            description: None,
            start_date: start.map(str::to_string),
            due_date: due.map(str::to_string),
        }
    }

    #[test]
    fn create_without_a_selection_assigns_the_single_running_cycle() {
        let (_tmp, mut store) = make_store();
        // A window that certainly contains today; no configured default cycle.
        store.config.cycles.insert(
            "October 2026".into(),
            cycle_with(Some("2020-01-01"), Some("2999-12-31")),
        );
        let issue = create(
            &store.config,
            &store,
            "Runs",
            None,
            None,
            None,
            Some(""),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(
            issue.cycles,
            Some(vec!["October 2026".to_string()]),
            "exactly one running cycle is assigned automatically"
        );
    }

    #[test]
    fn default_cycle_selection_falls_back_when_running_is_ambiguous() {
        let mut config = crate::config::Config::default();

        // Zero running cycles: the implicit Default.
        config.cycles.insert(
            "Future".into(),
            cycle_with(Some("2999-01-01"), Some("2999-12-31")),
        );
        assert_eq!(default_cycle_name(&config), "Default");

        // An open-ended (start-only) cycle counts as running.
        config.cycles.clear();
        config
            .cycles
            .insert("Ongoing".into(), cycle_with(Some("2020-01-01"), None));
        assert_eq!(default_cycle_name(&config), "Ongoing");

        // Two overlapping windows → ambiguous → the implicit Default.
        config.cycles.clear();
        config.cycles.insert(
            "A".into(),
            cycle_with(Some("2020-01-01"), Some("2999-12-31")),
        );
        config
            .cycles
            .insert("B".into(), cycle_with(Some("2020-01-01"), None));
        assert_eq!(default_cycle_name(&config), "Default");

        // ... unless a configured default names a real cycle, which still wins.
        config.planning.default_cycle = Some("B".into());
        assert_eq!(default_cycle_name(&config), "B");
    }

    #[test]
    fn create_planning_fields_round_trip_through_frontmatter() {
        let (_tmp, mut store) = make_store();
        store
            .config
            .cycles
            .insert("Cycle 1".into(), crate::config::PlanningCycle::default());
        seed_milestone(&store, "v1.0");
        let issue = create(
            &store.config,
            &store,
            "Planned",
            None,
            None,
            None,
            Some(""),
            None,
            None,
            None,
            Some("Cycle 1"),
            Some("v1.0"),
            Some("Alice"),
            Some("2026-09-07"),
            Some("2026-09-18"),
            None,
            None,
            None,
        )
        .unwrap();
        let reloaded = store
            .get(crate::storage::IssueSelector::Number(issue.number))
            .unwrap();
        assert_eq!(reloaded.cycles, Some(vec!["Cycle 1".to_string()]));
        assert_eq!(reloaded.milestones, Some(vec!["v1.0".to_string()]));
        assert_eq!(reloaded.reviewer.as_deref(), Some("Alice"));
        assert_eq!(reloaded.start_date.as_deref(), Some("2026-09-07"));
        assert_eq!(reloaded.due_date.as_deref(), Some("2026-09-18"));
        let raw = std::fs::read_to_string(store.issues_dir.join(&reloaded.filename)).unwrap();
        assert!(raw.contains("cycles:\n- Cycle 1"), "{raw}");
        assert!(raw.contains("milestones:\n- v1.0"), "{raw}");
        assert!(raw.contains("reviewer: Alice"), "{raw}");
    }

    // -----------------------------------------------------------------------
    // WP03 / T010 — `--parent` on the shared create core
    // -----------------------------------------------------------------------

    /// The create core with every optional argument absent except the ones a test
    /// states. Sixteen positional arguments is the price of a flat signature, and
    /// getting one wrong is silent, so it is spelled out once.
    fn create_bare(store: &Store, title: &str) -> crate::error::Result<Issue> {
        create(
            &store.config,
            store,
            title,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
    }

    fn create_with_parent(store: &Store, title: &str, parent: &str) -> crate::error::Result<Issue> {
        create(
            &store.config,
            store,
            title,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            Some(parent),
            None,
            None,
        )
    }

    /// Every issue file's bytes, for the no-partial-write property.
    fn snapshot(store: &Store) -> Vec<(String, String)> {
        let mut out: Vec<(String, String)> = fs::read_dir(&store.issues_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .map(|e| (e.file_name().to_string_lossy().into_owned(), e.path()))
            .filter(|(_, p)| p.extension().is_some_and(|x| x == "md"))
            .map(|(n, p)| (n, fs::read_to_string(p).unwrap()))
            .collect();
        out.sort();
        out
    }

    #[test]
    fn t010_create_with_a_valid_parent_stores_the_number_and_one_history_entry() {
        let (_tmp, store) = make_store();
        let parent = create_bare(&store, "Epic").unwrap();
        let child = create_with_parent(&store, "Task", &parent.number.to_string()).unwrap();

        assert_eq!(
            child.parent,
            Some(crate::id::canonical_ref(&parent)),
            "the parent is stored as a resolved number, never the selector text"
        );
        assert_eq!(child.history.len(), 1, "C-004: exactly one entry");
        let events = child.history.events();
        assert_eq!(events[0].kind, HistoryEventKind::ParentSet);
        assert!(
            events[0].detail.contains(&format!("#{}", parent.number)),
            "the entry must name the parent, got {:?}",
            events[0].detail
        );
        assert!(
            !events[0].actor.is_empty(),
            "an entry with no actor is not an audit record"
        );

        // And it survives the file round trip, History included.
        let written = fs::read_to_string(store.issues_dir.join(&child.filename)).unwrap();
        let reparsed = Issue::parse(&written).unwrap();
        assert_eq!(reparsed.parent, Some(crate::id::canonical_ref(&parent)));
        assert_eq!(reparsed.to_file_contents(), written);
    }

    #[test]
    fn t010_create_with_a_title_fragment_parent_stores_the_number() {
        let (_tmp, store) = make_store();
        let parent = create_bare(&store, "Epic").unwrap();
        // A title fragment, not a number: the selector resolves, the file keeps the
        // number, because a title is not stable and a retitle would orphan the child.
        let child = create_with_parent(&store, "Task", "Epic").unwrap();
        assert_eq!(child.parent, Some(crate::id::canonical_ref(&parent)));
        let written = fs::read_to_string(store.issues_dir.join(&child.filename)).unwrap();
        assert!(
            !written.contains("parent: Epic"),
            "the selector text must not reach the file:\n{written}"
        );
    }

    #[test]
    fn t010_create_with_an_unknown_parent_creates_nothing() {
        let (_tmp, store) = make_store();
        let before = snapshot(&store);
        let err = create_with_parent(&store, "Orphan", "999")
            .expect_err("a parent that resolves to nothing must be refused");
        assert!(
            err.to_string().contains("999"),
            "the refusal must name what was not found: {err}"
        );
        assert_eq!(snapshot(&store), before, "SC-004: no file was created");
    }

    #[test]
    fn t010_the_unknown_parent_refusal_comes_from_the_resolver_not_the_service() {
        // **Measured, and it is not the path T010 step 3 describes.** T010 asks for
        // "the service's named diagnostic", but a parent number that does not exist
        // is caught by `Store::resolve_issue` first, with the CLI's own
        // `not found: issue #999`. The service's `unknown_parent` is unreachable
        // through `tix create`: if a selector resolves, the issue is in `list()`,
        // so it is in the index.
        //
        // The first version of `t010_create_with_an_unknown_parent_creates_nothing`
        // looked like it covered the service path. Reverting the service call left
        // it **green** — the resolver was doing all the work. Asserted here so the
        // distinction is recorded rather than assumed, and the service's own entry
        // point is tested at its own level in
        // `hierarchy::tests::a_new_issues_parent_must_exist`.
        let (_tmp, store) = make_store();
        let err = create_with_parent(&store, "Orphan", "999").unwrap_err();
        let msg = err.to_string();
        assert!(
            !msg.contains("unknown_parent"),
            "the service is not consulted for a non-resolving selector: {msg}"
        );
        assert!(msg.contains("not found"), "{msg}");
    }

    #[test]
    fn t010_a_refused_create_does_not_burn_an_issue_number() {
        // A create that fails after the number is allocated leaves a gap in the
        // sequence. Validated *before* the issue is built, so the number is never
        // allocated at all — asserted because "a gap is harmless" is exactly the
        // reasoning that makes a silent skip acceptable.
        let (_tmp, store) = make_store();
        assert!(create_with_parent(&store, "Orphan", "999").is_err());
        let real = create_bare(&store, "Real").unwrap();
        let another = create_bare(&store, "Another").unwrap();
        assert!(
            another.number > real.number,
            "numbers must still advance monotonically: {} then {}",
            real.number,
            another.number
        );
    }

    #[test]
    fn t010_create_without_the_flag_leaves_the_field_absent() {
        let (_tmp, store) = make_store();
        let issue = create_bare(&store, "Plain").unwrap();
        assert_eq!(issue.parent, None);
        assert_eq!(issue.history.len(), 0, "no parent, no History entry");
        let written = fs::read_to_string(store.issues_dir.join(&issue.filename)).unwrap();
        assert!(
            !written.contains("parent:"),
            "a file that never had a parent must not grow the key:\n{written}"
        );
    }

    #[test]
    fn t010_the_parent_is_not_stored_on_the_parents_file() {
        // C-003. Byte-compared rather than read back through the model, so a child
        // list written under any key would be caught.
        let (_tmp, store) = make_store();
        let parent = create_bare(&store, "Epic").unwrap();
        let parent_file = parent.filename.clone();
        let before = fs::read_to_string(store.issues_dir.join(&parent_file)).unwrap();
        create_with_parent(&store, "Task", &parent.number.to_string()).unwrap();
        assert_eq!(
            fs::read_to_string(store.issues_dir.join(&parent_file)).unwrap(),
            before,
            "the parent's file must be byte-identical after a child is created"
        );
    }

    #[test]
    fn t010_a_blank_parent_flag_is_the_same_as_omitting_it() {
        // `tix create --parent ""` must not create a reference to the empty string.
        // An empty string reaching the resolver would either fail confusingly or,
        // worse, be coerced to "no parent" while looking like a successful set.
        let (_tmp, store) = make_store();
        let issue = create_with_parent(&store, "Plain", "  ").unwrap();
        assert_eq!(issue.parent, None);
        assert_eq!(issue.history.len(), 0);
    }
}

#[cfg(test)]
mod project_tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::config::ProjectConfiguration;
    use std::fs;
    use tempfile::TempDir;

    /// A store whose registry declares `p-1`/`Platform` and `p-2`/`Infra`.
    fn store_with_projects() -> (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 mut config = crate::config::Config {
            issues_dir: dir.clone(),
            milestones_dir: Some(tmp.path().join("docs/milestones")),
            ..crate::config::Config::default()
        };
        for (id, name) in [("p-1", "Platform"), ("p-2", "Infra")] {
            config.projects.insert(
                id.to_string(),
                ProjectConfiguration {
                    name: name.to_string(),
                    ..ProjectConfiguration::default()
                },
            );
        }
        config.save(&config_path).unwrap();
        let config = crate::config::Config::load_with_warning(&config_path, |_| {}).unwrap();
        (
            tmp,
            Store {
                issues_dir: dir,
                config,
            },
        )
    }

    /// `tix create --title <title> [--projects <projects>]` through the CLI path.
    fn create_with(store: &Store, title: &str, projects: Option<&str>) -> Result<()> {
        run(
            &store.config,
            store,
            Some(title),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            projects,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
    }

    #[test]
    fn a_multi_value_projects_flag_associates_every_project() {
        let (_tmp, store) = store_with_projects();
        create_with(&store, "Fix login", Some("p-1,Infra")).unwrap();
        let issue = store.resolve_issue("1").unwrap();
        assert_eq!(
            issue.projects,
            Some(vec!["p-1".to_string(), "p-2".to_string()])
        );
        assert_eq!(
            issue.history.events().len(),
            2,
            "one History entry per association"
        );
    }

    #[test]
    fn an_unknown_project_id_refuses_the_whole_create() {
        let (_tmp, store) = store_with_projects();
        let error = create_with(&store, "Fix login", Some("p-1,bogus")).unwrap_err();
        assert!(error.to_string().contains("unknown_project"), "{error}");
        assert!(
            store.list_all().unwrap().is_empty(),
            "a half-associated issue is worse than a failed command"
        );
    }

    #[test]
    fn a_duplicate_project_id_collapses_to_one_association() {
        let (_tmp, store) = store_with_projects();
        create_with(&store, "Fix login", Some("p-1,p-1,Platform")).unwrap();
        let issue = store.resolve_issue("1").unwrap();
        assert_eq!(issue.projects, Some(vec!["p-1".to_string()]));
        assert_eq!(issue.history.events().len(), 1);
    }

    #[test]
    fn a_create_without_the_flag_writes_no_association() {
        let (_tmp, store) = store_with_projects();
        create_with(&store, "Fix login", None).unwrap();
        let issue = store.resolve_issue("1").unwrap();
        assert_eq!(issue.projects, None);
        assert_eq!(
            issue.history.events(),
            [] as [&crate::model::HistoryEvent; 0]
        );
    }
}