omni-dev 0.39.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, and Datadog.
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
//! CLI commands for JIRA project versions (release versions).

use anyhow::Result;
use clap::{Parser, Subcommand};

use crate::atlassian::client::AtlassianClient;
use crate::atlassian::jira_types::JiraProjectVersionList;
use crate::cli::atlassian::confirm::{guard_destructive_with_io, GuardOptions, GuardOutcome};
use crate::cli::atlassian::format::{output_as, OutputFormat};
use crate::cli::atlassian::helpers::create_client;

/// Manages JIRA project versions (release versions).
#[derive(Parser)]
pub struct VersionCommand {
    /// The version subcommand to execute.
    #[command(subcommand)]
    pub command: VersionSubcommands,
}

/// Version subcommands.
#[derive(Subcommand)]
pub enum VersionSubcommands {
    /// Lists versions for a project (mirrors the `jira_version_list` MCP tool).
    List(ListCommand),
    /// Creates a new project version (mirrors the `jira_version_create` MCP tool).
    Create(CreateCommand),
    /// Marks a version as released (mirrors the `jira_version_release` MCP tool).
    Release(ReleaseCommand),
    /// Archives a version (mirrors the `jira_version_archive` MCP tool).
    Archive(ArchiveCommand),
    /// Renames a version (mirrors the `jira_version_rename` MCP tool).
    Rename(RenameCommand),
    /// Deletes a version (mirrors the `jira_version_delete` MCP tool).
    Delete(DeleteCommand),
}

impl VersionCommand {
    /// Executes the version command.
    pub async fn execute(self) -> Result<()> {
        match self.command {
            VersionSubcommands::List(cmd) => cmd.execute().await,
            VersionSubcommands::Create(cmd) => cmd.execute().await,
            VersionSubcommands::Release(cmd) => cmd.execute().await,
            VersionSubcommands::Archive(cmd) => cmd.execute().await,
            VersionSubcommands::Rename(cmd) => cmd.execute().await,
            VersionSubcommands::Delete(cmd) => cmd.execute().await,
        }
    }

    /// Dispatches against an injected client result (issue #950 DI seam). Lets
    /// tests drive the full `VersionCommand` -> subcommand dispatch path against
    /// a mock without mutating process-global env.
    #[cfg(test)]
    async fn execute_with(self, client: Result<(AtlassianClient, String)>) -> Result<()> {
        match self.command {
            VersionSubcommands::List(cmd) => cmd.execute_with(client).await,
            VersionSubcommands::Create(cmd) => cmd.execute_with(client).await,
            VersionSubcommands::Release(cmd) => cmd.execute_with(client).await,
            VersionSubcommands::Archive(cmd) => cmd.execute_with(client).await,
            VersionSubcommands::Rename(cmd) => cmd.execute_with(client).await,
            VersionSubcommands::Delete(cmd) => cmd.execute_with(client).await,
        }
    }
}

/// Lists versions for a JIRA project.
#[derive(Parser)]
pub struct ListCommand {
    /// Project key (e.g., "PROJ").
    #[arg(long)]
    pub project: String,

    /// Show only released versions.
    #[arg(long, conflicts_with = "unreleased")]
    pub released: bool,

    /// Show only unreleased versions.
    #[arg(long, conflicts_with = "released")]
    pub unreleased: bool,

    /// Show only archived versions.
    #[arg(long, conflicts_with = "unarchived")]
    pub archived: bool,

    /// Show only non-archived versions.
    #[arg(long, conflicts_with = "archived")]
    pub unarchived: bool,

    /// Output format.
    #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Table)]
    pub output: OutputFormat,
}

impl ListCommand {
    /// Fetches and displays versions.
    pub async fn execute(self) -> Result<()> {
        self.execute_with(create_client()).await
    }

    /// Runs against an injected client result (issue #950 DI seam). `execute`
    /// supplies the env-resolved client; tests supply one built from explicit
    /// credentials (or an `Err` to exercise the propagation path) without
    /// touching process-global env.
    async fn execute_with(self, client: Result<(AtlassianClient, String)>) -> Result<()> {
        let (client, _instance_url) = client?;
        run_list_versions(
            &client,
            &self.project,
            tri_state(self.released, self.unreleased),
            tri_state(self.archived, self.unarchived),
            &self.output,
        )
        .await
    }
}

/// Creates a new version on a JIRA project.
#[derive(Parser)]
pub struct CreateCommand {
    /// Project key (e.g., "PROJ").
    #[arg(long)]
    pub project: String,

    /// Version name (e.g., "1.0.0").
    #[arg(long)]
    pub name: String,

    /// Version description.
    #[arg(long)]
    pub description: Option<String>,

    /// Release date (ISO 8601, "YYYY-MM-DD").
    #[arg(long)]
    pub release_date: Option<String>,

    /// Start date (ISO 8601, "YYYY-MM-DD").
    #[arg(long)]
    pub start_date: Option<String>,

    /// Mark the version as released.
    #[arg(long)]
    pub released: bool,

    /// Mark the version as archived.
    #[arg(long)]
    pub archived: bool,
}

impl CreateCommand {
    /// Creates the version.
    pub async fn execute(self) -> Result<()> {
        self.execute_with(create_client()).await
    }

    /// Runs against an injected client result (issue #950 DI seam). See
    /// [`ListCommand::execute_with`].
    async fn execute_with(self, client: Result<(AtlassianClient, String)>) -> Result<()> {
        let (client, _instance_url) = client?;
        run_create_version(
            &client,
            &self.project,
            &self.name,
            self.description.as_deref(),
            self.release_date.as_deref(),
            self.start_date.as_deref(),
            self.released,
            self.archived,
        )
        .await
    }
}

/// Marks a project version as released.
#[derive(Parser)]
pub struct ReleaseCommand {
    /// Version ID (from `version list`).
    pub version_id: String,

    /// Release date (ISO 8601, "YYYY-MM-DD"). Defaults to leaving it unset.
    #[arg(long)]
    pub release_date: Option<String>,
}

impl ReleaseCommand {
    /// Releases the version.
    pub async fn execute(self) -> Result<()> {
        self.execute_with(create_client()).await
    }

    /// Runs against an injected client result (issue #950 DI seam).
    async fn execute_with(self, client: Result<(AtlassianClient, String)>) -> Result<()> {
        let (client, _instance_url) = client?;
        client
            .update_project_version(
                &self.version_id,
                None,
                None,
                Some(true),
                self.release_date.as_deref(),
                None,
                None,
            )
            .await?;
        println!("Released version {}.", self.version_id);
        Ok(())
    }
}

/// Archives a project version.
#[derive(Parser)]
pub struct ArchiveCommand {
    /// Version ID (from `version list`).
    pub version_id: String,
}

impl ArchiveCommand {
    /// Archives the version.
    pub async fn execute(self) -> Result<()> {
        self.execute_with(create_client()).await
    }

    /// Runs against an injected client result (issue #950 DI seam).
    async fn execute_with(self, client: Result<(AtlassianClient, String)>) -> Result<()> {
        let (client, _instance_url) = client?;
        client
            .update_project_version(&self.version_id, None, None, None, None, Some(true), None)
            .await?;
        println!("Archived version {}.", self.version_id);
        Ok(())
    }
}

/// Renames (and optionally re-describes) a project version.
#[derive(Parser)]
pub struct RenameCommand {
    /// Version ID (from `version list`).
    pub version_id: String,

    /// New version name.
    pub name: String,

    /// New description (optional).
    #[arg(long)]
    pub description: Option<String>,
}

impl RenameCommand {
    /// Renames the version.
    pub async fn execute(self) -> Result<()> {
        self.execute_with(create_client()).await
    }

    /// Runs against an injected client result (issue #950 DI seam).
    async fn execute_with(self, client: Result<(AtlassianClient, String)>) -> Result<()> {
        let (client, _instance_url) = client?;
        client
            .update_project_version(
                &self.version_id,
                Some(&self.name),
                self.description.as_deref(),
                None,
                None,
                None,
                None,
            )
            .await?;
        println!("Renamed version {} to {}.", self.version_id, self.name);
        Ok(())
    }
}

/// Deletes a project version.
#[derive(Parser)]
pub struct DeleteCommand {
    /// Version ID (from `version list`).
    pub version_id: String,

    /// Reassign the `fixVersion` of affected issues to this version id before
    /// deleting (otherwise the references are simply dropped).
    #[arg(long)]
    pub move_fix_issues_to: Option<String>,

    /// Reassign the `affectedVersion` of affected issues to this version id
    /// before deleting.
    #[arg(long)]
    pub move_affected_issues_to: Option<String>,

    /// Skips the confirmation prompt.
    #[arg(long)]
    pub force: bool,

    /// Prints what would be deleted without making any API calls.
    #[arg(long)]
    pub dry_run: bool,
}

impl DeleteCommand {
    /// Deletes the version.
    pub async fn execute(self) -> Result<()> {
        self.execute_with(create_client()).await
    }

    /// Runs against an injected client result (issue #950 DI seam), with the
    /// default stdin/stdout for the confirmation prompt.
    async fn execute_with(self, client: Result<(AtlassianClient, String)>) -> Result<()> {
        let (client, _instance_url) = client?;
        let mut reader = std::io::BufReader::new(std::io::stdin());
        let mut writer = std::io::stdout();
        self.execute_with_io(&client, &mut reader, &mut writer)
            .await
    }

    /// Inner form taking explicit client and IO handles, for unit tests.
    async fn execute_with_io(
        self,
        client: &AtlassianClient,
        reader: &mut (dyn std::io::BufRead + Send),
        writer: &mut (dyn std::io::Write + Send),
    ) -> Result<()> {
        if !self.force || self.dry_run {
            let prompt = format!("Delete version {}? [y/N] ", self.version_id);
            let dry_run_message = format!("Would delete version {}.", self.version_id);

            let outcome = guard_destructive_with_io(
                &GuardOptions {
                    prompt: &prompt,
                    dry_run_message: &dry_run_message,
                    force: self.force,
                    dry_run: self.dry_run,
                },
                reader,
                writer,
            )?;

            match outcome {
                GuardOutcome::Cancelled | GuardOutcome::DryRun => return Ok(()),
                GuardOutcome::Proceed => {}
            }
        }

        client
            .delete_project_version(
                &self.version_id,
                self.move_fix_issues_to.as_deref(),
                self.move_affected_issues_to.as_deref(),
            )
            .await?;
        writeln!(writer, "Deleted version {}.", self.version_id)?;

        Ok(())
    }
}

/// Folds a pair of mutually-exclusive boolean flags into a tri-state filter:
/// `Some(true)` for the positive flag, `Some(false)` for the negative,
/// `None` when neither was passed.
fn tri_state(yes: bool, no: bool) -> Option<bool> {
    match (yes, no) {
        (true, _) => Some(true),
        (_, true) => Some(false),
        _ => None,
    }
}

async fn run_list_versions(
    client: &AtlassianClient,
    project: &str,
    released: Option<bool>,
    archived: Option<bool>,
    output: &OutputFormat,
) -> Result<()> {
    let result = client
        .get_project_versions(project, released, archived)
        .await?;
    if output_as(&result, output)? {
        return Ok(());
    }
    print_versions(&result);
    Ok(())
}

#[allow(clippy::too_many_arguments)]
async fn run_create_version(
    client: &AtlassianClient,
    project: &str,
    name: &str,
    description: Option<&str>,
    release_date: Option<&str>,
    start_date: Option<&str>,
    released: bool,
    archived: bool,
) -> Result<()> {
    let version = client
        .create_project_version(
            project,
            name,
            description,
            release_date,
            start_date,
            released,
            archived,
        )
        .await?;
    println!("Created version {} (id: {}).", version.name, version.id);
    Ok(())
}

/// Prints versions as a formatted table.
fn print_versions(result: &JiraProjectVersionList) {
    if result.versions.is_empty() {
        println!("No versions found.");
        return;
    }

    let id_width = result
        .versions
        .iter()
        .map(|v| v.id.len())
        .max()
        .unwrap_or(2)
        .max(2);
    let name_width = result
        .versions
        .iter()
        .map(|v| v.name.len())
        .max()
        .unwrap_or(4)
        .max(4);

    println!(
        "{:<id_width$}  {:<name_width$}  RELEASED  ARCHIVED  RELEASE     DESCRIPTION",
        "ID", "NAME"
    );
    let desc_sep = "-".repeat(11);
    println!(
        "{:<id_width$}  {:<name_width$}  --------  --------  ----------  {desc_sep}",
        "-".repeat(id_width),
        "-".repeat(name_width),
    );

    for v in &result.versions {
        let release = format_date(v.release_date.as_deref());
        let description = v.description.as_deref().unwrap_or("-");
        println!(
            "{:<id_width$}  {:<name_width$}  {:<8}  {:<8}  {:<10}  {}",
            v.id,
            v.name,
            yes_no(v.released),
            yes_no(v.archived),
            release,
            description,
        );
    }
}

fn yes_no(b: bool) -> &'static str {
    if b {
        "yes"
    } else {
        "no"
    }
}

fn format_date(date: Option<&str>) -> &str {
    match date {
        Some(d) if d.len() >= 10 => &d[..10],
        Some(d) => d,
        None => "-",
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::atlassian::jira_types::JiraProjectVersion;

    fn sample_version(
        id: &str,
        name: &str,
        released: bool,
        archived: bool,
        release_date: Option<&str>,
    ) -> JiraProjectVersion {
        JiraProjectVersion {
            id: id.to_string(),
            name: name.to_string(),
            description: None,
            project_key: "PROJ".to_string(),
            released,
            archived,
            release_date: release_date.map(String::from),
            start_date: None,
        }
    }

    fn mock_client(base_url: &str) -> AtlassianClient {
        AtlassianClient::new(base_url, "user@test.com", "token").unwrap()
    }

    // ── tri_state ──────────────────────────────────────────────────

    #[test]
    fn tri_state_neither() {
        assert_eq!(tri_state(false, false), None);
    }

    #[test]
    fn tri_state_yes() {
        assert_eq!(tri_state(true, false), Some(true));
    }

    #[test]
    fn tri_state_no() {
        assert_eq!(tri_state(false, true), Some(false));
    }

    #[test]
    fn tri_state_yes_wins_when_both_set() {
        // Clap normally rejects this via conflicts_with; defensive default.
        assert_eq!(tri_state(true, true), Some(true));
    }

    // ── format helpers ─────────────────────────────────────────────

    #[test]
    fn yes_no_true() {
        assert_eq!(yes_no(true), "yes");
    }

    #[test]
    fn yes_no_false() {
        assert_eq!(yes_no(false), "no");
    }

    #[test]
    fn format_date_full_iso() {
        assert_eq!(format_date(Some("2026-04-01T00:00:00.000Z")), "2026-04-01");
    }

    #[test]
    fn format_date_just_date() {
        assert_eq!(format_date(Some("2026-04-01")), "2026-04-01");
    }

    #[test]
    fn format_date_short() {
        assert_eq!(format_date(Some("2026")), "2026");
    }

    #[test]
    fn format_date_none() {
        assert_eq!(format_date(None), "-");
    }

    // ── print_versions ─────────────────────────────────────────────

    #[test]
    fn print_versions_empty() {
        let result = JiraProjectVersionList {
            versions: vec![],
            total: 0,
        };
        print_versions(&result);
    }

    #[test]
    fn print_versions_with_data() {
        let result = JiraProjectVersionList {
            versions: vec![
                sample_version("10000", "1.0.0", true, false, Some("2026-04-01")),
                sample_version("10001", "1.1.0", false, false, None),
            ],
            total: 2,
        };
        print_versions(&result);
    }

    // ── dispatch ───────────────────────────────────────────────────

    #[test]
    fn version_command_list_variant() {
        let cmd = VersionCommand {
            command: VersionSubcommands::List(ListCommand {
                project: "PROJ".to_string(),
                released: false,
                unreleased: false,
                archived: false,
                unarchived: false,
                output: OutputFormat::Table,
            }),
        };
        assert!(matches!(cmd.command, VersionSubcommands::List(_)));
    }

    #[test]
    fn version_command_create_variant() {
        let cmd = VersionCommand {
            command: VersionSubcommands::Create(CreateCommand {
                project: "PROJ".to_string(),
                name: "1.0.0".to_string(),
                description: None,
                release_date: None,
                start_date: None,
                released: false,
                archived: false,
            }),
        };
        assert!(matches!(cmd.command, VersionSubcommands::Create(_)));
    }

    #[test]
    fn version_command_release_variant() {
        let cmd = VersionCommand {
            command: VersionSubcommands::Release(ReleaseCommand {
                version_id: "100".to_string(),
                release_date: None,
            }),
        };
        assert!(matches!(cmd.command, VersionSubcommands::Release(_)));
    }

    #[test]
    fn version_command_archive_variant() {
        let cmd = VersionCommand {
            command: VersionSubcommands::Archive(ArchiveCommand {
                version_id: "100".to_string(),
            }),
        };
        assert!(matches!(cmd.command, VersionSubcommands::Archive(_)));
    }

    #[test]
    fn version_command_rename_variant() {
        let cmd = VersionCommand {
            command: VersionSubcommands::Rename(RenameCommand {
                version_id: "100".to_string(),
                name: "2.0".to_string(),
                description: None,
            }),
        };
        assert!(matches!(cmd.command, VersionSubcommands::Rename(_)));
    }

    #[test]
    fn version_command_delete_variant() {
        let cmd = VersionCommand {
            command: VersionSubcommands::Delete(DeleteCommand {
                version_id: "100".to_string(),
                move_fix_issues_to: None,
                move_affected_issues_to: None,
                force: false,
                dry_run: false,
            }),
        };
        assert!(matches!(cmd.command, VersionSubcommands::Delete(_)));
    }

    // ── run_* version functions ────────────────────────────────────

    #[tokio::test]
    async fn run_list_versions_success() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/rest/api/3/project/PROJ/versions",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!([
                    {"id": "1", "name": "1.0", "released": true, "archived": false}
                ])),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server.uri());
        assert!(
            run_list_versions(&client, "PROJ", None, None, &OutputFormat::Table)
                .await
                .is_ok()
        );
    }

    #[tokio::test]
    async fn run_list_versions_yaml_output_returns_early() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/rest/api/3/project/PROJ/versions",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!([
                    {"id": "1", "name": "1.0", "released": true, "archived": false}
                ])),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server.uri());
        // Yaml output path branches before print_versions, exercising the
        // `if output_as { return Ok(()); }` early return.
        assert!(
            run_list_versions(&client, "PROJ", None, None, &OutputFormat::Yaml)
                .await
                .is_ok()
        );
    }

    #[tokio::test]
    async fn run_list_versions_with_filter() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/rest/api/3/project/PROJ/versions",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!([
                    {"id": "1", "name": "1.0", "released": true, "archived": false},
                    {"id": "2", "name": "2.0", "released": false, "archived": false},
                ])),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server.uri());
        assert!(
            run_list_versions(&client, "PROJ", Some(true), None, &OutputFormat::Table)
                .await
                .is_ok()
        );
    }

    #[tokio::test]
    async fn run_list_versions_api_error() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/rest/api/3/project/NONE/versions",
            ))
            .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("Not Found"))
            .mount(&server)
            .await;

        let client = mock_client(&server.uri());
        let err = run_list_versions(&client, "NONE", None, None, &OutputFormat::Table)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("404"));
    }

    #[tokio::test]
    async fn run_create_version_success() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/rest/api/3/version"))
            .respond_with(wiremock::ResponseTemplate::new(201).set_body_json(
                serde_json::json!({"id": "100", "name": "1.0.0", "released": false, "archived": false}),
            ))
            .mount(&server)
            .await;

        let client = mock_client(&server.uri());
        assert!(
            run_create_version(&client, "PROJ", "1.0.0", None, None, None, false, false)
                .await
                .is_ok()
        );
    }

    #[tokio::test]
    async fn run_create_version_forbidden() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/rest/api/3/version"))
            .respond_with(wiremock::ResponseTemplate::new(403).set_body_string("Forbidden"))
            .mount(&server)
            .await;

        let client = mock_client(&server.uri());
        let err = run_create_version(&client, "PROJ", "1.0", None, None, None, false, false)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("403"));
    }

    #[tokio::test]
    async fn run_create_version_invalid_date() {
        let server = wiremock::MockServer::start().await;
        // No mock — request must short-circuit before HTTP.
        let client = mock_client(&server.uri());
        let err = run_create_version(
            &client,
            "PROJ",
            "1.0",
            None,
            Some("not-a-date"),
            None,
            false,
            false,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("YYYY-MM-DD"));
    }

    // ── execute() integration via injected client (issue #950) ─────
    //
    // The happy-path tests drive each `*Command::execute_with()` end-to-end
    // against a wiremock server by injecting a client built from explicit
    // [`AtlassianCredentials`] pointed at the mock. They do NOT touch the
    // process-global `ATLASSIAN_*` env vars and therefore need no mutex and
    // run fully in parallel — the dependency-injection fix for the flaky
    // env-race documented in issue #950.
    //
    // The error-path tests below still exercise the production `execute()` ->
    // `create_client()` wrappers (which read the environment), so they clear
    // credentials behind the one canonical [`EnvGuard`]/`AUTH_ENV_MUTEX`. That
    // mutation is fully serialised and deterministic (it only ever produces
    // `CredentialsNotFound`), so it is not subject to the original race.

    use crate::atlassian::auth::test_util::EnvGuard;
    use crate::atlassian::auth::AtlassianCredentials;
    use crate::cli::atlassian::helpers::create_client_from;

    /// Credentials pointed at a mock server. Uses dummy email/token; the mock
    /// does not authenticate, it only matches method + path.
    fn mock_credentials(instance_url: &str) -> AtlassianCredentials {
        AtlassianCredentials {
            instance_url: instance_url.to_string(),
            email: "test@example.com".to_string(),
            api_token: "test-token".into(),
        }
    }

    #[tokio::test]
    async fn version_command_execute_list_dispatches_through_create_client() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/rest/api/3/project/PROJ/versions",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!([
                    {"id": "1", "name": "1.0", "released": false, "archived": false}
                ])),
            )
            .mount(&server)
            .await;

        let cmd = VersionCommand {
            command: VersionSubcommands::List(ListCommand {
                project: "PROJ".to_string(),
                released: false,
                unreleased: false,
                archived: false,
                unarchived: false,
                output: OutputFormat::Yaml,
            }),
        };
        let client = create_client_from(mock_credentials(&server.uri()));
        assert!(cmd.execute_with(client).await.is_ok());
    }

    /// Drives the production `VersionCommand::execute` -> `ListCommand::execute`
    /// -> `create_client()` -> `execute_with(Err)` chain with credentials
    /// cleared, so the `?` propagation path runs end-to-end (covers the
    /// env-reading wrappers the injection tests bypass).
    #[tokio::test(flavor = "current_thread")]
    #[allow(clippy::await_holding_lock)]
    async fn version_command_execute_list_propagates_create_client_error() {
        let guard = EnvGuard::take();
        let _home = guard.clear_credentials();

        let cmd = VersionCommand {
            command: VersionSubcommands::List(ListCommand {
                project: "PROJ".to_string(),
                released: false,
                unreleased: false,
                archived: false,
                unarchived: false,
                output: OutputFormat::Yaml,
            }),
        };
        assert!(cmd.execute().await.is_err());
    }

    /// Same as above for the `Create` arm: covers `VersionCommand::execute`
    /// (Create), `CreateCommand::execute`, and `create_client()`.
    #[tokio::test(flavor = "current_thread")]
    #[allow(clippy::await_holding_lock)]
    async fn version_command_execute_create_propagates_create_client_error() {
        let guard = EnvGuard::take();
        let _home = guard.clear_credentials();

        let cmd = VersionCommand {
            command: VersionSubcommands::Create(CreateCommand {
                project: "PROJ".to_string(),
                name: "1.0.0".to_string(),
                description: None,
                release_date: None,
                start_date: None,
                released: false,
                archived: false,
            }),
        };
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test]
    async fn version_command_execute_create_dispatches_through_create_client() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/rest/api/3/version"))
            .respond_with(wiremock::ResponseTemplate::new(201).set_body_json(
                serde_json::json!({"id": "100", "name": "1.0.0", "released": false, "archived": false}),
            ))
            .mount(&server)
            .await;

        let cmd = VersionCommand {
            command: VersionSubcommands::Create(CreateCommand {
                project: "PROJ".to_string(),
                name: "1.0.0".to_string(),
                description: None,
                release_date: None,
                start_date: None,
                released: false,
                archived: false,
            }),
        };
        let client = create_client_from(mock_credentials(&server.uri()));
        assert!(cmd.execute_with(client).await.is_ok());
    }

    #[tokio::test]
    async fn version_command_execute_release_dispatches_through_client() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("PUT"))
            .and(wiremock::matchers::path("/rest/api/3/version/100"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "100", "name": "1.0"})),
            )
            .mount(&server)
            .await;

        let cmd = VersionCommand {
            command: VersionSubcommands::Release(ReleaseCommand {
                version_id: "100".to_string(),
                release_date: Some("2026-04-16".to_string()),
            }),
        };
        let client = create_client_from(mock_credentials(&server.uri()));
        assert!(cmd.execute_with(client).await.is_ok());
    }

    #[tokio::test]
    async fn version_command_execute_rename_dispatches_through_client() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("PUT"))
            .and(wiremock::matchers::path("/rest/api/3/version/100"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "100", "name": "2.0"})),
            )
            .mount(&server)
            .await;

        let cmd = VersionCommand {
            command: VersionSubcommands::Rename(RenameCommand {
                version_id: "100".to_string(),
                name: "2.0".to_string(),
                description: Some("Second release".to_string()),
            }),
        };
        let client = create_client_from(mock_credentials(&server.uri()));
        assert!(cmd.execute_with(client).await.is_ok());
    }

    // ── VersionCommand::execute() end-to-end ───────────────────────
    //
    // Drives the real top-level dispatch arm *and* each subcommand's public
    // execute() wrapper (create_client) — the `execute_with` DI-seam tests
    // above bypass both.

    fn version_put_mock() -> wiremock::Mock {
        wiremock::Mock::given(wiremock::matchers::method("PUT"))
            .and(wiremock::matchers::path("/rest/api/3/version/10000"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "10000", "name": "1.0"})),
            )
    }

    #[tokio::test]
    async fn version_command_execute_release_drives_create_client() {
        use crate::test_support::atlassian_env::AtlassianEnvGuard;
        let server = wiremock::MockServer::start().await;
        version_put_mock().mount(&server).await;
        let _env = AtlassianEnvGuard::new(&server.uri(), "u@t.com", "tok");
        VersionCommand {
            command: VersionSubcommands::Release(ReleaseCommand {
                version_id: "10000".to_string(),
                release_date: Some("2026-06-01".to_string()),
            }),
        }
        .execute()
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn version_command_execute_archive_drives_create_client() {
        use crate::test_support::atlassian_env::AtlassianEnvGuard;
        let server = wiremock::MockServer::start().await;
        version_put_mock().mount(&server).await;
        let _env = AtlassianEnvGuard::new(&server.uri(), "u@t.com", "tok");
        VersionCommand {
            command: VersionSubcommands::Archive(ArchiveCommand {
                version_id: "10000".to_string(),
            }),
        }
        .execute()
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn version_command_execute_rename_drives_create_client() {
        use crate::test_support::atlassian_env::AtlassianEnvGuard;
        let server = wiremock::MockServer::start().await;
        version_put_mock().mount(&server).await;
        let _env = AtlassianEnvGuard::new(&server.uri(), "u@t.com", "tok");
        VersionCommand {
            command: VersionSubcommands::Rename(RenameCommand {
                version_id: "10000".to_string(),
                name: "2.0".to_string(),
                description: None,
            }),
        }
        .execute()
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn version_command_execute_delete_drives_create_client() {
        use crate::test_support::atlassian_env::AtlassianEnvGuard;
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("DELETE"))
            .and(wiremock::matchers::path("/rest/api/3/version/10000"))
            .respond_with(wiremock::ResponseTemplate::new(204))
            .mount(&server)
            .await;
        let _env = AtlassianEnvGuard::new(&server.uri(), "u@t.com", "tok");
        // `--force` skips the prompt, so the wrapper's real stdin is not read.
        VersionCommand {
            command: VersionSubcommands::Delete(DeleteCommand {
                version_id: "10000".to_string(),
                move_fix_issues_to: None,
                move_affected_issues_to: None,
                force: true,
                dry_run: false,
            }),
        }
        .execute()
        .await
        .unwrap();
    }

    // ── DeleteCommand (confirm-guarded, tested via execute_with_io) ──

    #[tokio::test]
    async fn delete_version_force_calls_delete() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("DELETE"))
            .and(wiremock::matchers::path("/rest/api/3/version/100"))
            .respond_with(wiremock::ResponseTemplate::new(204))
            .expect(1)
            .mount(&server)
            .await;

        let (client, _) = create_client_from(mock_credentials(&server.uri())).unwrap();
        let cmd = DeleteCommand {
            version_id: "100".to_string(),
            move_fix_issues_to: None,
            move_affected_issues_to: None,
            force: true,
            dry_run: false,
        };
        let mut input = std::io::Cursor::new(Vec::<u8>::new());
        let mut output = Vec::<u8>::new();
        cmd.execute_with_io(&client, &mut input, &mut output)
            .await
            .unwrap();
        assert!(String::from_utf8(output)
            .unwrap()
            .contains("Deleted version 100."));
    }

    #[tokio::test]
    async fn delete_version_dry_run_makes_no_api_call() {
        let (client, _) = create_client_from(mock_credentials("http://127.0.0.1:1")).unwrap();
        let cmd = DeleteCommand {
            version_id: "100".to_string(),
            move_fix_issues_to: None,
            move_affected_issues_to: None,
            force: false,
            dry_run: true,
        };
        let mut input = std::io::Cursor::new(Vec::<u8>::new());
        let mut output = Vec::<u8>::new();
        cmd.execute_with_io(&client, &mut input, &mut output)
            .await
            .unwrap();
        let out = String::from_utf8(output).unwrap();
        assert!(out.contains("Would delete version 100."));
        assert!(!out.contains("Deleted version"));
    }

    /// The `Archive` arm of the `execute_with` DI-seam dispatch.
    #[tokio::test]
    async fn version_command_execute_with_archive_dispatches() {
        let server = wiremock::MockServer::start().await;
        version_put_mock().mount(&server).await;
        let cmd = VersionCommand {
            command: VersionSubcommands::Archive(ArchiveCommand {
                version_id: "10000".to_string(),
            }),
        };
        let client = create_client_from(mock_credentials(&server.uri()));
        assert!(cmd.execute_with(client).await.is_ok());
    }

    /// The `Delete` arm of the `execute_with` DI-seam dispatch (`--force`, so
    /// the default-stdin prompt is skipped).
    #[tokio::test]
    async fn version_command_execute_with_delete_dispatches() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("DELETE"))
            .and(wiremock::matchers::path("/rest/api/3/version/10000"))
            .respond_with(wiremock::ResponseTemplate::new(204))
            .mount(&server)
            .await;
        let cmd = VersionCommand {
            command: VersionSubcommands::Delete(DeleteCommand {
                version_id: "10000".to_string(),
                move_fix_issues_to: None,
                move_affected_issues_to: None,
                force: true,
                dry_run: false,
            }),
        };
        let client = create_client_from(mock_credentials(&server.uri()));
        assert!(cmd.execute_with(client).await.is_ok());
    }

    /// Answering "y" takes the `GuardOutcome::Proceed` arm.
    #[tokio::test]
    async fn delete_version_prompt_yes_calls_delete() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("DELETE"))
            .and(wiremock::matchers::path("/rest/api/3/version/10000"))
            .respond_with(wiremock::ResponseTemplate::new(204))
            .expect(1)
            .mount(&server)
            .await;

        let (client, _) = create_client_from(mock_credentials(&server.uri())).unwrap();
        let cmd = DeleteCommand {
            version_id: "10000".to_string(),
            move_fix_issues_to: None,
            move_affected_issues_to: None,
            force: false,
            dry_run: false,
        };
        let mut input = std::io::Cursor::new(b"y\n".to_vec());
        let mut output = Vec::<u8>::new();
        cmd.execute_with_io(&client, &mut input, &mut output)
            .await
            .unwrap();
        let out = String::from_utf8(output).unwrap();
        assert!(out.contains("Delete version 10000?"));
        assert!(out.contains("Deleted version 10000."));
    }

    /// A failing writer makes the guard's `writeln` fail, covering the `?`
    /// propagation on `guard_destructive_with_io`.
    #[tokio::test]
    async fn delete_version_dry_run_propagates_guard_error() {
        use crate::test_support::failing_io::FailingWriter;
        let (client, _) = create_client_from(mock_credentials("http://127.0.0.1:1")).unwrap();
        let cmd = DeleteCommand {
            version_id: "10000".to_string(),
            move_fix_issues_to: None,
            move_affected_issues_to: None,
            force: false,
            dry_run: true,
        };
        let mut input = std::io::Cursor::new(Vec::<u8>::new());
        let mut writer = FailingWriter;
        let err = cmd
            .execute_with_io(&client, &mut input, &mut writer)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("simulated write failure"));
    }

    #[tokio::test]
    async fn delete_version_prompt_no_makes_no_delete() {
        let (client, _) = create_client_from(mock_credentials("http://127.0.0.1:1")).unwrap();
        let cmd = DeleteCommand {
            version_id: "100".to_string(),
            move_fix_issues_to: None,
            move_affected_issues_to: None,
            force: false,
            dry_run: false,
        };
        let mut input = std::io::Cursor::new(b"n\n".to_vec());
        let mut output = Vec::<u8>::new();
        cmd.execute_with_io(&client, &mut input, &mut output)
            .await
            .unwrap();
        assert!(!String::from_utf8(output)
            .unwrap()
            .contains("Deleted version"));
    }
}