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
//! `tix project`: the project lifecycle and association surface (mission
//! `first-class-projects-01M3BYBW`, WP05; FR-001, FR-002, C-002–C-005).
//!
//! This module is a **thin adapter**. Every rule it appears to enforce is one
//! [`crate::projects`] already owns and [`crate::storage`] already applies:
//!
//! | concern | owner | how this module reaches it |
//! |---|---|---|
//! | identity, uniqueness, dates | `crate::projects` | [`projects::create_project`], [`projects::edit_project`] |
//! | resolution (id first, name second) | `crate::projects` | [`projects::resolve`], [`projects::resolve_project_id`] |
//! | membership and member counts | `crate::projects` | [`projects::list_projects`], [`projects::resolve`] |
//! | registry removal without a cascade | `crate::projects` | [`projects::delete_project`] |
//! | association mutations + History | `crate::storage` | [`Store::associate`], [`Store::dissociate`], [`Store::bulk_associate`] |
//! | the wording of a refusal | `crate::projects` | [`ProjectError`] rendered through `TixError` |
//!
//! Three properties are deliberate and are the ones a surface loses most easily:
//!
//! - **Every listing shows the id.** [`projects::project_display`] is the one
//!   formatter, and `list` prints the id and the name in separate columns, so a
//!   rename can never be mistaken for a new project (C-002).
//! - **Delete never deletes an issue.** [`projects::delete_project`] removes the
//!   registry entry and *reports* the affected issues; this module prints that
//!   report and adds no cascade and no `--cascade` flag (C-004, C-005).
//! - **Bulk is per-issue.** `add`, `remove` and `bulk-add` report one outcome per
//!   selector, and a rejection on one neither aborts nor rolls back the rest
//!   (FR-002, `contracts/project-service.md` §3). There is no bulk-edit engine
//!   here: the scope is project association only, riding the existing
//!   create/edit/service seams.
//!
//! `tix project` mutates `tix.toml` for its lifecycle verbs, so it is routed by
//! [`crate::cli::run`] — the process boundary that owns the mutable config —
//! exactly as `tix wip` and `tix view <subcommand>` are. The batch verbs return a
//! **status** rather than an error, so a partly-successful batch exits non-zero
//! while every outcome stays reported.

use std::io::IsTerminal;

use crate::cli::{ExitCode, ProjectCommand};
use crate::config::Config;
use crate::error::{Result, TixError};
use crate::model::Issue;
use crate::projects::{self, NewProject, Patch, Project, ProjectEdit, ProjectError};
use crate::storage::{BulkAssociationOutcome, Store};
/// Run one `tix project` subcommand.
///
/// Returns an [`ExitCode`] rather than `()` because the batch verbs (`add`,
/// `remove`, `bulk-add`) carry a **status**: each selector is independent, so a
/// run where one selector failed is a completed command reporting non-zero, not
/// an error that discarded the rest (the convention `tix archive` and `tix bulk`
/// already follow).
pub fn run(config: &mut Config, store: &Store, command: &ProjectCommand) -> Result<ExitCode> {
    match command {
        ProjectCommand::Create {
            name,
            description,
            status,
            lead,
            start_date,
            due_date,
        } => create(
            config,
            store,
            name,
            description.as_deref(),
            status.as_deref(),
            lead.as_deref(),
            start_date.as_deref(),
            due_date.as_deref(),
        ),
        ProjectCommand::Edit {
            reference,
            name,
            description,
            status,
            lead,
            start_date,
            due_date,
        } => edit(
            config,
            store,
            reference,
            name.as_deref(),
            description.as_deref(),
            status.as_deref(),
            lead.as_deref(),
            start_date.as_deref(),
            due_date.as_deref(),
        ),
        ProjectCommand::List => list(config, store),
        ProjectCommand::Show { reference } => show(config, store, reference),
        ProjectCommand::Delete { reference, yes } => delete(config, store, reference, *yes),
        // `add` and `bulk-add` are the same operation under two spellings: the
        // single-issue form and the explicitly batch form process every selector
        // independently, and separating their behaviour would give one of them a
        // second set of rules.
        ProjectCommand::Add { reference, issues }
        | ProjectCommand::BulkAdd { reference, issues } => {
            associate(config, store, reference, issues)
        }
        ProjectCommand::Remove { reference, issues } => {
            dissociate(config, store, reference, issues)
        }
    }
}

// ---------------------------------------------------------------------------
// Lifecycle (T020, T021)
// ---------------------------------------------------------------------------

/// Persist the registry after an accepted lifecycle change.
///
/// `Config::validate` runs first, so a change that would make `tix.toml`
/// unloadable is refused before it is written rather than discovered by the next
/// command — the same ordering `tix wip` uses. The path is the shared
/// [`crate::commands::views::config_path`], so registry writes go through the one
/// atomic-save path rather than a second copy of it.
fn save(config: &mut Config, store: &Store) -> Result<()> {
    config.validate()?;
    let path = crate::commands::views::config_path(store);
    config
        .save(&path)
        .map_err(|error| TixError::Config(format!("could not save `{}`: {error}", path.display())))
}

/// `tix project create <name> [flags]`.
#[allow(clippy::too_many_arguments)]
fn create(
    config: &mut Config,
    store: &Store,
    name: &str,
    description: Option<&str>,
    status: Option<&str>,
    lead: Option<&str>,
    start_date: Option<&str>,
    due_date: Option<&str>,
) -> Result<ExitCode> {
    let new = NewProject {
        name: name.to_string(),
        description: description.map(String::from),
        status: status.map(String::from),
        lead: lead.map(String::from),
        start_date: trim_optional(start_date),
        due_date: trim_optional(due_date),
    };
    // The service allocates the id and validates name and dates, so an invalid
    // request refuses here with the registry untouched (nothing to persist).
    let project = projects::create_project(config, &new)?;
    save(config, store)?;
    println!(
        "Created {}",
        projects::project_display(&project.id, &project.name)
    );
    Ok(ExitCode::Success)
}

/// `tix project edit <id> [--field …]`.
///
/// A `--name` change is a **label change only**: [`projects::edit_project`]
/// touches the record, never the registry key, so nothing is re-keyed and every
/// association and derived figure survives (C-002, SC-005).
#[allow(clippy::too_many_arguments)]
fn edit(
    config: &mut Config,
    store: &Store,
    reference: &str,
    name: Option<&str>,
    description: Option<&str>,
    status: Option<&str>,
    lead: Option<&str>,
    start_date: Option<&str>,
    due_date: Option<&str>,
) -> Result<ExitCode> {
    let edit = ProjectEdit {
        name: name.map_or(Patch::Unchanged, |value| Patch::Set(value.to_string())),
        description: text_patch(description),
        status: text_patch(status),
        lead: text_patch(lead),
        start_date: date_patch(start_date),
        due_date: date_patch(due_date),
    };
    if edit.name.is_unchanged()
        && edit.description.is_unchanged()
        && edit.status.is_unchanged()
        && edit.lead.is_unchanged()
        && edit.start_date.is_unchanged()
        && edit.due_date.is_unchanged()
    {
        return Err(crate::commands::project_edit_requires_a_field());
    }
    let project = projects::edit_project(config, reference, &edit)?;
    save(config, store)?;
    println!(
        "Updated {}",
        projects::project_display(&project.id, &project.name)
    );
    Ok(ExitCode::Success)
}

/// `tix project list` — declaration order, `id<TAB>name<TAB>member count`.
///
/// The id is a column of its own rather than a decoration, because selecting by
/// id is the contract and a listing that hides the id makes a rename look like a
/// new project (C-002). One tab-separated row per project is greppable and
/// deterministic.
fn list(config: &Config, store: &Store) -> Result<ExitCode> {
    for line in listing_lines(config, &store.list_all()?) {
        println!("{line}");
    }
    Ok(ExitCode::Success)
}

/// One tab-separated row per project: `id<TAB>name<TAB>member count`.
///
/// A pure function so the id-alongside-name property (C-002) is assertable
/// without capturing a process's stdout.
fn listing_lines(config: &Config, issues: &[Issue]) -> Vec<String> {
    projects::list_projects(config, issues)
        .iter()
        .map(|project| format!("{}\t{}\t{}", project.id, project.name, project.member_count))
        .collect()
}

/// `tix project show <id>` — the record, its figures, its member count, and its
/// members.
///
/// A member is printed through [`crate::projects::MemberRef::display`]
/// (`#<number> <title>`), the shared renderer, so a member never shows a stale
/// title: the label is derived on read and never stored.
///
/// The progress and health figures are the **service's typed value**
/// ([`crate::commands::view::project_reports`]) — one call, no second computation
/// (C-006, `contracts/cli-surface.md` §1: "Progress, lead, dates, and the
/// completed/overdue/blocked/unassigned health counts"). WP05 left this unwired
/// because `ProjectProgress`/`ProjectHealth` landed later in a parallel work
/// package; wiring it here is the integration step, not a second progress
/// implementation.
fn show(config: &Config, store: &Store, reference: &str) -> Result<ExitCode> {
    let issues = store.list_all()?;
    let project = projects::resolve(config, &issues, reference)?;
    let (_index, reports) = crate::commands::view::project_reports(store, &issues)?;
    for line in record_lines(&project, reports.get(&project.id)) {
        println!("{line}");
    }
    Ok(ExitCode::Success)
}

/// One `key: value` line per record field, then the derived figures, then one line
/// per member.
///
/// Pure, so the record/member rendering is assertable without capturing stdout. The
/// figure lines are emitted only when the service's report is supplied: a caller
/// with no snapshot (and the TUI before it has one) renders the record alone rather
/// than inventing zeros, which is the same distinction the `-`-for-absent spelling
/// draws for the optional fields.
pub fn record_lines(
    project: &Project,
    report: Option<&crate::projects::ProjectHealthReport>,
) -> Vec<String> {
    let mut lines = vec![
        format!("id: {}", project.id),
        format!("name: {}", project.name),
        format!(
            "description: {}",
            project.description.as_deref().unwrap_or("-")
        ),
        format!("status: {}", project.status.as_deref().unwrap_or("-")),
        format!("lead: {}", project.lead.as_deref().unwrap_or("-")),
        format!(
            "start-date: {}",
            project.start_date.as_deref().unwrap_or("-")
        ),
        format!("due-date: {}", project.due_date.as_deref().unwrap_or("-")),
        format!("members: {}", project.member_count),
    ];
    if let Some(report) = report {
        lines.push(format!(
            "progress: {}/{}",
            report.progress.done, report.progress.total
        ));
        lines.push(format!("overdue: {}", report.health.overdue));
        lines.push(format!("blocked: {}", report.health.blocked));
        lines.push(format!("unassigned: {}", report.health.unassigned));
        lines.push(format!(
            "missing-references: {}",
            report.health.missing_references.len()
        ));
    }
    lines.extend(
        project
            .members
            .iter()
            .map(|member| format!("  {}", member.display)),
    );
    lines
}

/// `tix project delete <id> [--yes]`.
///
/// Removes the registry entry **only**. The affected issues are reported — number
/// and title — and their associations are retained as diagnosable missing
/// references, so `tix lint` keeps naming each one until it is repaired. There is
/// no cascade and no `--cascade` flag: deleting a project must never delete an
/// issue (C-004, C-005).
///
/// Confirmation follows [`crate::commands::delete`]: `--yes` skips the prompt and
/// a non-TTY stdin deletes immediately, so the command is scriptable and
/// TTY-free.
fn delete(config: &mut Config, store: &Store, reference: &str, yes: bool) -> Result<ExitCode> {
    let issues = store.list_all()?;
    // Resolved before the prompt so an unknown id refuses with nothing written
    // and nothing asked.
    let project = projects::resolve(config, &issues, reference)?;

    let mut confirmed = yes || !std::io::stdin().is_terminal();
    if !confirmed {
        eprint!(
            "Delete project '{}'? [y/N] ",
            projects::project_display(&project.id, &project.name)
        );
        let mut line = String::new();
        std::io::stdin()
            .read_line(&mut line)
            .map_err(TixError::Io)?;
        confirmed = line.trim().eq_ignore_ascii_case("y");
        if !confirmed {
            eprintln!("aborted");
        }
    }
    if !confirmed {
        return Ok(ExitCode::Success);
    }

    // The impact notice, printed **before** the deletion so it is on screen
    // alongside the confirmation — the convention `tix delete` follows. `eprint!`
    // because it is a warning about what is about to happen, not data.
    eprint!("{}", impact_notice(&project));

    let deletion = projects::delete_project(config, reference, &issues)?;
    save(config, store)?;
    println!(
        "Deleted project {}",
        projects::project_display(&deletion.id, &deletion.name)
    );
    Ok(ExitCode::Success)
}

/// The delete-time impact notice, or the empty string when nothing references the
/// project.
///
/// One `tix project delete` removes **exactly one registry entry**. The issues
/// that referenced the project keep their references, which then read as missing
/// references — a diagnosed, repairable state, and not a reason to refuse
/// (mirroring [`crate::commands::delete::impact_notice`]).
fn impact_notice(project: &Project) -> String {
    if project.members.is_empty() {
        return String::new();
    }
    let plural = if project.members.len() == 1 {
        "issue"
    } else {
        "issues"
    };
    let mut out = format!(
        "Note: {} {plural} still reference this project and keep the reference as a \
         missing project reference.\nThey are not deleted or modified; `tix lint` reports \
         the dangling reference until it is repaired.\n",
        project.members.len()
    );
    for member in &project.members {
        out.push_str(&format!("  {}\n", member.display));
    }
    out
}

// ---------------------------------------------------------------------------
// Association from the project side (T024)
// ---------------------------------------------------------------------------

/// `tix project add|bulk-add <id> <sel…>`.
///
/// Each selector is processed independently through [`Store::bulk_associate`],
/// which is the service-backed batch seam: one rejection is reported beside the
/// rest rather than aborting them, and each accepted change appends exactly one
/// History entry (contract §3). The project reference is resolved **once**, up
/// front, so an unknown project refuses before any write.
fn associate(
    config: &Config,
    store: &Store,
    reference: &str,
    selectors: &[String],
) -> Result<ExitCode> {
    let id = projects::resolve_project_id(config, reference)?;
    let display = display_for(config, &id);
    let outcomes = store.bulk_associate(id.as_str(), selectors)?;
    report(&display, "associated", "with", outcomes)
}

/// `tix project remove <id> <sel…>`.
///
/// Drops only the association (never the issue). The reference is resolved when it
/// names a live project and otherwise used **verbatim**, which is the repair path
/// C-005 promises: a stale stored id can still be removed. Each selector is
/// independent.
fn dissociate(
    config: &Config,
    store: &Store,
    reference: &str,
    selectors: &[String],
) -> Result<ExitCode> {
    let resolved = projects::resolve_project_id(config, reference).ok();
    let needle = resolved
        .as_ref()
        .map_or_else(|| reference.to_string(), |id| id.to_string());
    let display = resolved
        .as_ref()
        .map_or_else(|| format!("`{reference}`"), |id| display_for(config, id));
    let mut code = ExitCode::Success;
    let mut changed = 0usize;
    let mut unchanged = 0usize;
    let mut failed = 0usize;
    for selector in selectors {
        match store.dissociate(selector, &needle) {
            Ok(applied) if applied.changed => {
                changed += 1;
                println!("dissociated {selector}");
            }
            Ok(_) => {
                unchanged += 1;
                println!("dissociated {selector} (was not associated)");
            }
            Err(error) => {
                failed += 1;
                eprintln!("{}", crate::error::render_error(&error));
                if code == ExitCode::Success {
                    code = crate::cli::exit_code_for(&error);
                }
            }
        }
    }
    println!(
        "dissociated {changed} of {} issue(s) from {display}{}{}",
        selectors.len(),
        unchanged_note(unchanged),
        failure_note(failed)
    );
    Ok(code)
}

/// Report a batch of association outcomes: one line per issue, then a summary.
///
/// Successes and idempotent no-ops go to stdout (they are the data the user asked
/// about); a refusal goes to stderr, because a consumer redirecting stdout must
/// not find a diagnostic in it. The returned code is the **first** failure's
/// mapped code, so a partly-successful batch exits non-zero while every outcome
/// stays reported — the convention [`crate::commands::archive`] follows.
fn report(
    display: &str,
    verb: &str,
    preposition: &str,
    outcomes: Vec<BulkAssociationOutcome>,
) -> Result<ExitCode> {
    let total = outcomes.len();
    let mut code = ExitCode::Success;
    let mut changed = 0usize;
    let mut unchanged = 0usize;
    let mut failed = 0usize;
    for outcome in outcomes {
        match outcome.outcome {
            Ok(applied) if applied.changed => {
                changed += 1;
                println!("{verb} {}", outcome.selector);
            }
            Ok(_) => {
                unchanged += 1;
                println!("{verb} {} (already {verb})", outcome.selector);
            }
            Err(error) => {
                failed += 1;
                eprintln!("{}", crate::error::render_error(&error));
                if code == ExitCode::Success {
                    code = crate::cli::exit_code_for(&error);
                }
            }
        }
    }
    println!(
        "{verb} {changed} of {total} issue(s) {preposition} {display}{}{}",
        unchanged_note(unchanged),
        failure_note(failed)
    );
    Ok(code)
}

/// ` (N unchanged)`, or nothing when every outcome changed something.
fn unchanged_note(unchanged: usize) -> String {
    if unchanged == 0 {
        String::new()
    } else {
        format!(" ({unchanged} unchanged)")
    }
}

/// `; N failed`, or nothing when the batch had no failure.
fn failure_note(failed: usize) -> String {
    if failed == 0 {
        String::new()
    } else {
        format!("; {failed} failed")
    }
}

/// The display form for a resolved id: the registry name beside the id.
fn display_for(config: &Config, id: &crate::config::ProjectId) -> String {
    match config.projects.get(id.as_str()) {
        Some(record) => projects::project_display(id, &record.name),
        None => format!("`{id}`"),
    }
}

// ---------------------------------------------------------------------------
// Shared helpers for the create/edit cores (T022, T023)
// ---------------------------------------------------------------------------

/// Resolve and validate a comma-separated `--projects` value, in first-seen order.
///
/// Every reference is resolved through the service **before** the caller writes
/// anything, so an unknown id refuses the whole operation rather than leaving a
/// half-associated issue. Resolution also collapses duplicates: `p-1,p-1` and
/// `Platform,p-1` both name one project, and one association is what gets written.
pub fn resolve_projects(config: &Config, raw: &str) -> Result<Vec<String>> {
    let mut out: Vec<String> = Vec::new();
    for reference in crate::commands::parse_csv_list(raw) {
        let id = projects::resolve_project_id(config, &reference)?.to_string();
        if !out.contains(&id) {
            out.push(id);
        }
    }
    Ok(out)
}

/// Associate a freshly created issue with the resolved project ids.
///
/// One [`Store::associate`] per id, so the History entry and the idempotence rule
/// are the service's, not a second implementation here. The ids were resolved
/// before the issue existed, so a refusal cannot leave a half-associated create.
pub fn associate_created(store: &Store, issue: &Issue, ids: &[String]) -> Result<()> {
    for id in ids {
        store.associate(&issue.number.to_string(), id)?;
    }
    Ok(())
}

/// A `--remove-project` reference, resolved when it names a live project.
///
/// `needle` is what is compared **verbatim** against the stored list: the resolved
/// id when there is one, otherwise the reference as typed, which keeps a stale
/// stored id removable (C-005's repair path). `resolved` distinguishes a live
/// project from a reference this registry does not know.
#[derive(Debug)]
struct RemoveRef {
    needle: String,
    resolved: bool,
}

/// The validated association inputs of one `tix edit`, ready to apply.
///
/// Produced by [`plan_edit_associations`] **before** any write, so a refusal
/// leaves every file byte-identical (T023 step 5).
#[derive(Debug)]
pub struct EditAssociationPlan {
    add_ids: Vec<String>,
    remove_refs: Vec<RemoveRef>,
    clear: bool,
}

/// Resolve the `tix edit` association inputs without writing anything.
///
/// `clear` is `--projects ""`; an absent flag is an empty plan that changes
/// nothing. An unresolvable `--remove-project` reference is refused as
/// `unknown_project` **unless** the issue still carries it verbatim — removing a
/// stale id is the repair path, and refusing it would strand the reference.
pub fn plan_edit_associations(
    config: &Config,
    store: &Store,
    selector: &str,
    add: &[String],
    remove: &[String],
    clear: bool,
) -> Result<EditAssociationPlan> {
    let mut add_ids: Vec<String> = Vec::new();
    for reference in add {
        let id = projects::resolve_project_id(config, reference)?.to_string();
        if !add_ids.contains(&id) {
            add_ids.push(id);
        }
    }
    let remove_refs: Vec<RemoveRef> = remove
        .iter()
        .map(
            |reference| match projects::resolve_project_id(config, reference) {
                Ok(id) => RemoveRef {
                    needle: id.to_string(),
                    resolved: true,
                },
                Err(_) => RemoveRef {
                    needle: reference.clone(),
                    resolved: false,
                },
            },
        )
        .collect();
    let stored = store.resolve_issue(selector)?.projects.unwrap_or_default();
    for reference in remove_refs.iter().filter(|reference| !reference.resolved) {
        if !stored.iter().any(|id| id == &reference.needle) {
            return Err(ProjectError::UnknownProject {
                reference: reference.needle.clone(),
            }
            .into());
        }
    }
    Ok(EditAssociationPlan {
        add_ids,
        remove_refs,
        clear,
    })
}

/// Apply a validated association plan through the store, reporting whether
/// anything was actually applied.
///
/// Order is clear → remove → add, so `tix edit <n> --projects "" --add-project p-1`
/// ends with exactly the added association. Every mutation goes through
/// [`Store::associate`]/[`Store::dissociate`], so `updated` is bumped and the
/// History entry appended in the one place that owns both.
///
/// The `bool` is `true` when at least one mutation changed something. It exists
/// so the caller's success line does not claim a write that never happened: a
/// no-op `--add-project` of an already-present association, or `--projects ""`
/// on an issue with no associations, writes nothing and bumps no date, and
/// saying `Updated <file>` would misreport that.
pub fn apply_edit_associations(
    store: &Store,
    selector: &str,
    plan: &EditAssociationPlan,
) -> Result<bool> {
    let mut changed = false;
    if plan.clear {
        let stored = store.resolve_issue(selector)?.projects.unwrap_or_default();
        for id in &stored {
            changed |= store.dissociate(selector, id)?.changed;
        }
    }
    for reference in &plan.remove_refs {
        changed |= store.dissociate(selector, &reference.needle)?.changed;
    }
    for id in &plan.add_ids {
        changed |= store.associate(selector, id)?.changed;
    }
    Ok(changed)
}

/// A blank value clears an optional text field; a written one sets it.
fn text_patch(value: Option<&str>) -> Patch<String> {
    match value {
        None => Patch::Unchanged,
        Some(text) if text.trim().is_empty() => Patch::Clear,
        Some(text) => Patch::Set(text.to_string()),
    }
}

/// A blank value clears a date field; a written one is passed through trimmed.
fn date_patch(value: Option<&str>) -> Patch<String> {
    match value {
        None => Patch::Unchanged,
        Some(text) if text.trim().is_empty() => Patch::Clear,
        Some(text) => Patch::Set(text.trim().to_string()),
    }
}

/// A trimmed, non-blank optional string, or `None`.
fn trim_optional(value: Option<&str>) -> Option<String> {
    value
        .map(str::trim)
        .filter(|text| !text.is_empty())
        .map(String::from)
}

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

    /// A store over a temp dir whose persisted registry declares `projects`, with
    /// `issues` issues (numbers `1..=issues`) titled `Issue N`.
    ///
    /// The registry is written to `tix.toml`, not merely held in memory, so a test
    /// that removes a project can compare a real registry file before and after.
    fn store_with(projects: &[(&str, &str)], issues: usize) -> (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 = Config {
            issues_dir: dir.clone(),
            ..Config::default()
        };
        config.layout.directory = "{assignee}".to_string();
        config.layout.move_on_change = false;
        for (id, name) in projects {
            config.projects.insert(
                (*id).to_string(),
                ProjectConfiguration {
                    name: (*name).to_string(),
                    ..ProjectConfiguration::default()
                },
            );
        }
        config.save(&config_path).unwrap();
        let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
        let store = Store {
            issues_dir: dir.clone(),
            config,
        };
        for number in 1..=issues {
            write_issue(
                &store,
                u32::try_from(number).unwrap(),
                &format!("Issue {number}"),
                &[],
            );
        }
        (tmp, store)
    }

    /// Write one issue file with an optional `projects` list.
    fn write_issue(store: &Store, number: u32, title: &str, projects: &[&str]) {
        let mut frontmatter =
            format!("---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"todo\"\nlabels: []\n");
        if !projects.is_empty() {
            frontmatter.push_str("projects:\n");
            for id in projects {
                frontmatter.push_str(&format!("- {id}\n"));
            }
        }
        frontmatter.push_str("---\n");
        fs::write(
            store
                .issues_dir
                .join(format!("2026-01-{number:02}-issue-{number}.md")),
            frontmatter,
        )
        .unwrap();
    }

    /// The registry file's bytes, for a "nothing else changed" assertion.
    fn registry(config_path: &std::path::Path) -> String {
        fs::read_to_string(config_path).unwrap()
    }

    /// The registry file beside the store's issues dir.
    fn registry_path(store: &Store) -> std::path::PathBuf {
        Config::project_root(&store.issues_dir)
            .unwrap()
            .join("tix.toml")
    }

    fn issue_bytes(store: &Store, number: u32) -> String {
        fs::read_to_string(
            store
                .issues_dir
                .join(format!("2026-01-{number:02}-issue-{number}.md")),
        )
        .unwrap()
    }

    // -- T020 — lifecycle ---------------------------------------------------

    #[test]
    fn the_listing_shows_each_project_id_and_name_alongside_its_member_count() {
        let (_tmp, store) = store_with(&[("p-1", "Platform"), ("p-2", "Infra")], 1);
        write_issue(&store, 1, "Issue 1", &["p-1"]);
        let lines = listing_lines(&store.config, &store.list_all().unwrap());
        assert_eq!(
            lines[0], "p-1\tPlatform\t1",
            "id, name and count: {lines:?}"
        );
        assert_eq!(lines[1], "p-2\tInfra\t0");
        // The id is present as a field of its own, not decoration (C-002).
        assert!(lines[0].contains("p-1"));
        assert!(lines[0].contains("Platform"));
    }

    #[test]
    fn show_prints_the_record_and_its_members_with_ids() {
        let (_tmp, store) = store_with(&[("p-1", "Platform")], 2);
        write_issue(&store, 1, "Issue 1", &["p-1"]);
        let project = projects::resolve(&store.config, &store.list_all().unwrap(), "p-1").unwrap();
        let lines = record_lines(&project, None);
        assert!(lines.contains(&"id: p-1".to_string()), "{lines:?}");
        assert!(lines.contains(&"name: Platform".to_string()), "{lines:?}");
        assert!(lines.contains(&"members: 1".to_string()), "{lines:?}");
        assert!(
            lines
                .iter()
                .any(|line| line.contains("#1") && line.contains("Issue 1")),
            "a member names its issue: {lines:?}"
        );
    }

    #[test]
    fn create_allocates_an_id_and_refuses_a_duplicate_name() {
        let (_tmp, store) = store_with(&[], 0);
        let mut config = store.config.clone();
        create(
            &mut config,
            &store,
            "Platform",
            None,
            None,
            Some("alice"),
            None,
            None,
        )
        .unwrap();
        assert_eq!(config.projects.len(), 1);
        let (id, record) = config.projects.iter().next().unwrap();
        assert_eq!(record.name, "Platform");
        assert_eq!(record.lead.as_deref(), Some("alice"));
        assert!(id.starts_with("p-"), "an allocated id: {id}");

        // The same name (case-folded) is refused, and the registry is unchanged.
        let before = registry(&registry_path(&store));
        let error = create(
            &mut config,
            &store,
            "platform",
            None,
            None,
            None,
            None,
            None,
        )
        .expect_err("a duplicate name is refused");
        assert!(
            error.to_string().contains("duplicate_name"),
            "the named diagnostic: {error}"
        );
        assert_eq!(config.projects.len(), 1);
        assert_eq!(registry(&registry_path(&store)), before, "nothing written");
    }

    #[test]
    fn edit_renames_the_label_and_keeps_the_id() {
        let (_tmp, store) = store_with(&[("p-1", "Platform")], 1);
        write_issue(&store, 1, "Issue 1", &["p-1"]);
        let mut config = store.config.clone();
        edit(
            &mut config,
            &store,
            "p-1",
            Some("Platform hardening"),
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap();
        // The registry key is untouched — nothing is re-keyed (C-002, SC-005).
        assert!(config.projects.contains_key("p-1"));
        assert_eq!(config.projects["p-1"].name, "Platform hardening");
        // The association resolves through the same id after the rename.
        let project = projects::resolve(&config, &store.list_all().unwrap(), "p-1").unwrap();
        assert_eq!(project.name, "Platform hardening");
        assert_eq!(project.member_count, 1);
    }

    #[test]
    fn edit_with_no_fields_is_a_usage_error() {
        let (_tmp, store) = store_with(&[("p-1", "Platform")], 0);
        let mut config = store.config.clone();
        let error = edit(
            &mut config,
            &store,
            "p-1",
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .expect_err("a fieldless edit is refused");
        assert!(error.to_string().contains("no fields to change"), "{error}");
    }

    // -- T021 — delete retains the issues -----------------------------------

    #[test]
    fn delete_removes_only_the_registry_entry_and_reports_the_members() {
        let (_tmp, store) = store_with(&[("p-1", "Platform"), ("p-2", "Infra")], 1);
        write_issue(&store, 1, "Issue 1", &["p-1"]);
        let mut config = store.config.clone();
        let issues = store.list_all().unwrap();
        let before = issue_bytes(&store, 1);
        let notice = impact_notice(&projects::resolve(&config, &issues, "p-1").unwrap());
        assert!(
            notice.contains("Issue 1"),
            "the notice names the issue: {notice}"
        );
        assert!(notice.contains("not deleted"));

        delete(&mut config, &store, "p-1", true).unwrap();

        // The registry entry is gone; the sibling project survives.
        assert!(!config.projects.contains_key("p-1"));
        assert!(config.projects.contains_key("p-2"));
        assert!(!registry(&registry_path(&store)).contains("p-1"));
        // The issue is untouched: still present, still carrying its reference.
        assert_eq!(
            issue_bytes(&store, 1),
            before,
            "the issue file is unchanged"
        );
        assert!(issue_bytes(&store, 1).contains("p-1"));
        // And the reference now reads as a missing reference (C-005).
        let missing = projects::validate_references(&config, &store.list_all().unwrap());
        assert_eq!(missing.len(), 1, "{missing:?}");
        assert_eq!(missing[0].project_id, "p-1");
    }

    #[test]
    fn delete_refuses_an_unknown_id_and_writes_nothing() {
        let (_tmp, store) = store_with(&[("p-1", "Platform")], 0);
        let mut config = store.config.clone();
        let before = registry(&registry_path(&store));
        let error = delete(&mut config, &store, "bogus", true).expect_err("unknown id");
        assert!(error.to_string().contains("unknown_project"), "{error}");
        assert!(config.projects.contains_key("p-1"));
        assert_eq!(registry(&registry_path(&store)), before);
    }

    // -- T024 — association from the project side ---------------------------

    #[test]
    fn associate_reports_each_selector_independently() {
        let (_tmp, store) = store_with(&[("p-1", "Platform")], 2);
        let code = associate(
            &store.config,
            &store,
            "p-1",
            &["1".to_string(), "99".to_string()],
        )
        .unwrap();
        assert_ne!(code, ExitCode::Success, "a partial batch exits non-zero");
        // The good selector was written and the bad one did not abort it.
        assert!(issue_bytes(&store, 1).contains("p-1"));
        let events = store.resolve_issue("1").unwrap().history.events().len();
        assert_eq!(
            events, 1,
            "exactly one History entry for the accepted change"
        );
    }

    #[test]
    fn associate_refuses_an_unknown_project_before_writing_anything() {
        let (_tmp, store) = store_with(&[("p-1", "Platform")], 1);
        let before = issue_bytes(&store, 1);
        let error = associate(&store.config, &store, "bogus", &["1".to_string()])
            .expect_err("an unknown project refuses up front");
        assert!(error.to_string().contains("unknown_project"), "{error}");
        assert_eq!(issue_bytes(&store, 1), before, "nothing written");
    }

    #[test]
    fn associating_twice_appends_one_history_entry() {
        let (_tmp, store) = store_with(&[("p-1", "Platform")], 1);
        associate(&store.config, &store, "p-1", &["1".to_string()]).unwrap();
        let after_first = issue_bytes(&store, 1);
        let code = associate(&store.config, &store, "p-1", &["1".to_string()]).unwrap();
        assert_eq!(
            code,
            ExitCode::Success,
            "an idempotent no-op is not a failure"
        );
        assert_eq!(
            store.resolve_issue("1").unwrap().history.events().len(),
            1,
            "no second entry for a duplicate association"
        );
        assert_eq!(
            issue_bytes(&store, 1),
            after_first,
            "a no-op writes nothing"
        );
    }

    #[test]
    fn dissociate_drops_only_the_association() {
        let (_tmp, store) = store_with(&[("p-1", "Platform")], 1);
        write_issue(&store, 1, "Issue 1", &["p-1"]);
        let code = dissociate(&store.config, &store, "p-1", &["1".to_string()]).unwrap();
        assert_eq!(code, ExitCode::Success);
        let issue = store.resolve_issue("1").unwrap();
        assert_eq!(issue.projects, None, "the association is dropped");
        assert!(
            store.issues_dir.join(&issue.filename).is_file(),
            "the issue itself is kept at {}",
            issue.filename
        );
        // Removing it again is an idempotent no-op, not an error.
        let code = dissociate(&store.config, &store, "p-1", &["1".to_string()]).unwrap();
        assert_eq!(code, ExitCode::Success);
    }

    #[test]
    fn dissociate_can_still_remove_a_stale_id_by_name_reference() {
        let (_tmp, store) = store_with(&[], 1);
        // A stale reference: no registry entry, but the issue carries the id.
        write_issue(&store, 1, "Issue 1", &["p-gone"]);
        let code = dissociate(&store.config, &store, "p-gone", &["1".to_string()]).unwrap();
        assert_eq!(code, ExitCode::Success);
        assert_eq!(store.resolve_issue("1").unwrap().projects, None);
    }

    // -- T022/T023 — the shared create/edit inputs ---------------------------

    #[test]
    fn resolve_projects_collapses_duplicates_and_refuses_an_unknown_id() {
        let (_tmp, store) = store_with(&[("p-1", "Platform")], 0);
        let ids = resolve_projects(&store.config, "Platform,p-1").unwrap();
        assert_eq!(
            ids,
            vec!["p-1".to_string()],
            "a name and an id are one project"
        );
        let error = resolve_projects(&store.config, "p-1,bogus").expect_err("unknown id");
        assert!(error.to_string().contains("unknown_project"), "{error}");
    }

    #[test]
    fn associate_created_writes_one_entry_per_project() {
        let (_tmp, store) = store_with(&[("p-1", "Platform"), ("p-2", "Infra")], 1);
        let issue = store.resolve_issue("1").unwrap();
        associate_created(&store, &issue, &["p-1".to_string(), "p-2".to_string()]).unwrap();
        let after = store.resolve_issue("1").unwrap();
        assert_eq!(
            after.projects,
            Some(vec!["p-1".to_string(), "p-2".to_string()])
        );
        assert_eq!(after.history.events().len(), 2, "one entry per association");
    }

    #[test]
    fn a_plan_refuses_an_unknown_remove_reference_that_is_not_stored() {
        let (_tmp, store) = store_with(&[("p-1", "Platform")], 1);
        let error = plan_edit_associations(
            &store.config,
            &store,
            "1",
            &[],
            &["bogus".to_string()],
            false,
        )
        .expect_err("an unresolvable, unstored reference is a typo");
        assert!(error.to_string().contains("unknown_project"), "{error}");
    }

    #[test]
    fn a_plan_accepts_removing_a_stale_stored_id() {
        let (_tmp, store) = store_with(&[], 1);
        write_issue(&store, 1, "Issue 1", &["p-gone"]);
        let plan = plan_edit_associations(
            &store.config,
            &store,
            "1",
            &[],
            &["p-gone".to_string()],
            false,
        )
        .unwrap();
        assert!(
            apply_edit_associations(&store, "1", &plan).unwrap(),
            "removing a stored id changed the issue"
        );
        assert_eq!(store.resolve_issue("1").unwrap().projects, None);
    }

    #[test]
    fn clearing_removes_every_association_and_keeps_the_issue() {
        let (_tmp, store) = store_with(&[("p-1", "Platform"), ("p-2", "Infra")], 1);
        write_issue(&store, 1, "Issue 1", &["p-1", "p-2"]);
        let plan = plan_edit_associations(&store.config, &store, "1", &[], &[], true).unwrap();
        assert!(apply_edit_associations(&store, "1", &plan).unwrap());
        let issue = store.resolve_issue("1").unwrap();
        assert_eq!(issue.projects, None);
        assert_eq!(issue.history.events().len(), 2, "one entry per removal");
    }

    // -- the change flag the success line depends on -------------------------

    #[test]
    fn a_noop_association_plan_reports_no_change() {
        let (_tmp, store) = store_with(&[("p-1", "Platform")], 1);
        write_issue(&store, 1, "Issue 1", &["p-1"]);

        // An already-present association.
        let plan =
            plan_edit_associations(&store.config, &store, "1", &["p-1".to_string()], &[], false)
                .unwrap();
        assert!(
            !apply_edit_associations(&store, "1", &plan).unwrap(),
            "adding an existing association is a no-op"
        );

        // Clearing an issue that has no associations.
        let (_tmp2, store2) = store_with(&[("p-1", "Platform")], 1);
        write_issue(&store2, 1, "Issue 1", &[]);
        let plan = plan_edit_associations(&store2.config, &store2, "1", &[], &[], true).unwrap();
        assert!(
            !apply_edit_associations(&store2, "1", &plan).unwrap(),
            "clearing nothing is a no-op"
        );
    }

    #[test]
    fn an_applied_association_plan_reports_a_change() {
        let (_tmp, store) = store_with(&[("p-1", "Platform")], 1);
        let plan =
            plan_edit_associations(&store.config, &store, "1", &["p-1".to_string()], &[], false)
                .unwrap();
        assert!(apply_edit_associations(&store, "1", &plan).unwrap());
    }
}