omni-dev 0.32.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
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
//! CLI commands for Confluence page comments.

use std::io::{self, BufRead, Write};

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

use crate::atlassian::adf::AdfDocument;
use crate::atlassian::adf_validated::{markdown_to_validated_adf, ValidatedAdfDocument};
use crate::atlassian::confluence_api::ConfluenceApi;
use crate::atlassian::confluence_types::{CommentKind, ConfluenceComment, InlineAnchor};
use crate::atlassian::convert::adf_to_markdown;
use crate::atlassian::document::JfmDocument;
use crate::atlassian::inline_comment::{
    audit_inline_comments, reanchor_inline_comment, CommentDrift, DriftStatus,
};
use crate::cli::atlassian::confirm::{guard_destructive_with_io, GuardOptions, GuardOutcome};
use crate::cli::atlassian::format::{output_as, ContentFormat, OutputFormat};
use crate::cli::atlassian::helpers::{create_client, read_input};

/// Manages comments on a Confluence page.
#[derive(Parser)]
pub struct CommentCommand {
    /// The comment subcommand to execute.
    #[command(subcommand)]
    pub command: CommentSubcommands,
}

/// Comment subcommands.
#[derive(Subcommand)]
pub enum CommentSubcommands {
    /// Lists comments on a Confluence page (mirrors the `confluence_comment_list` MCP tool).
    List(ListCommand),
    /// Adds a footer comment to a Confluence page (mirrors the `confluence_comment_add` MCP tool).
    Add(AddCommand),
    /// Adds an inline (anchored) comment to a Confluence page (mirrors the `confluence_comment_add_inline` MCP tool).
    AddInline(AddInlineCommand),
    /// Lists the replies of a comment (mirrors the `confluence_comment_replies` MCP tool).
    Replies(RepliesCommand),
    /// Audits inline comments for anchor drift (mirrors the `confluence_comment_audit` MCP tool).
    Audit(AuditCommand),
    /// Moves an inline comment's anchor to a new text run (mirrors the `confluence_comment_reanchor` MCP tool).
    Reanchor(ReanchorCommand),
}

impl CommentCommand {
    /// Executes the comment command.
    pub async fn execute(self) -> Result<()> {
        match self.command {
            CommentSubcommands::List(cmd) => cmd.execute().await,
            CommentSubcommands::Add(cmd) => cmd.execute().await,
            CommentSubcommands::AddInline(cmd) => cmd.execute().await,
            CommentSubcommands::Replies(cmd) => cmd.execute().await,
            CommentSubcommands::Audit(cmd) => cmd.execute().await,
            CommentSubcommands::Reanchor(cmd) => cmd.execute().await,
        }
    }
}

/// `--kind` filter for `confluence comment list`.
///
/// `All` (the default) issues both the footer and inline list calls and
/// concatenates the results so a single invocation surfaces every comment on
/// the page.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
pub enum CommentKindFilter {
    /// Page-level footer comments only.
    Footer,
    /// Inline (anchored) comments only.
    Inline,
    /// Both kinds, concatenated and sorted by creation time.
    All,
}

/// `--kind` selector for `confluence comment replies` (no `All` — replies live
/// on a kind-specific endpoint, so the caller must commit to one).
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
pub enum CommentKindArg {
    /// Replies under a footer comment.
    Footer,
    /// Replies under an inline comment.
    Inline,
}

impl From<CommentKindArg> for CommentKind {
    fn from(k: CommentKindArg) -> Self {
        match k {
            CommentKindArg::Footer => Self::Footer,
            CommentKindArg::Inline => Self::Inline,
        }
    }
}

/// Lists comments on a Confluence page.
///
/// Comment authors are returned as Atlassian account IDs — resolve them to
/// display names with `omni-dev atlassian confluence user get`.
#[derive(Parser)]
pub struct ListCommand {
    /// Confluence page ID.
    pub id: String,

    /// Which kind of comments to show.
    #[arg(long, value_enum, default_value_t = CommentKindFilter::All)]
    pub kind: CommentKindFilter,

    /// Maximum number of comments to display.
    #[arg(long, default_value_t = 25)]
    pub limit: usize,

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

impl ListCommand {
    /// Fetches and displays comments.
    pub async fn execute(self) -> Result<()> {
        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        run_list_comments(&api, &self.id, self.kind, self.limit, &self.output).await
    }
}

/// Adds a footer comment to a Confluence page.
#[derive(Parser)]
pub struct AddCommand {
    /// Confluence page ID.
    pub id: String,

    /// Input file (reads from stdin if omitted or "-").
    pub file: Option<String>,

    /// Input format.
    #[arg(long, value_enum, default_value_t = ContentFormat::Jfm)]
    pub format: ContentFormat,
}

impl AddCommand {
    /// Reads input, converts to ADF, and posts the comment.
    pub async fn execute(self) -> Result<()> {
        let adf = parse_comment_input(self.file.as_deref(), self.format)?;

        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        run_add_comment(&api, &self.id, &adf).await
    }
}

/// Adds an inline (anchored) comment to a Confluence page.
#[derive(Parser)]
pub struct AddInlineCommand {
    /// Confluence page ID.
    pub id: String,

    /// Input file (reads from stdin if omitted or "-").
    pub file: Option<String>,

    /// Input format.
    #[arg(long, value_enum, default_value_t = ContentFormat::Jfm)]
    pub format: ContentFormat,

    /// Exact text on the page that the comment should anchor to.
    #[arg(long)]
    pub anchor_text: String,

    /// 1-based occurrence to anchor to when `--anchor-text` appears more than
    /// once on the page. Required for ambiguous anchors; rejected if out of
    /// range.
    #[arg(long)]
    pub match_index: Option<usize>,
}

impl AddInlineCommand {
    /// Reads input, resolves the anchor, and posts the inline comment.
    pub async fn execute(self) -> Result<()> {
        let adf = parse_comment_input(self.file.as_deref(), self.format)?;

        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        let anchor = api
            .resolve_anchor(&self.id, &self.anchor_text, self.match_index)
            .await?;
        run_add_inline_comment(&api, &self.id, &adf, &anchor).await
    }
}

/// Lists the replies of a comment.
#[derive(Parser)]
pub struct RepliesCommand {
    /// Comment ID.
    pub id: String,

    /// Whether the parent is a footer or inline comment (the Confluence API
    /// requires this to pick the right endpoint).
    #[arg(long, value_enum)]
    pub kind: CommentKindArg,

    /// Maximum number of replies to display.
    #[arg(long, default_value_t = 25)]
    pub limit: usize,

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

impl RepliesCommand {
    /// Fetches and displays the replies of a comment.
    pub async fn execute(self) -> Result<()> {
        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        run_list_replies(&api, &self.id, self.kind.into(), self.limit, &self.output).await
    }
}

/// Audits every inline comment on a page for anchor drift.
///
/// Inline-comment anchors do NOT follow text edits: when the annotated text is
/// rewritten, Confluence keeps the mark on whatever original characters survive.
/// This compares each comment's currently-anchored text against the reviewer's
/// original highlight and reports the drift. Read-only.
#[derive(Parser)]
pub struct AuditCommand {
    /// Confluence page ID.
    pub id: String,

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

impl AuditCommand {
    /// Fetches inline comments and the page ADF, then reports drift.
    pub async fn execute(self) -> Result<()> {
        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        let drifts = audit_inline_comments(&api, &self.id).await?;
        if output_as(&drifts, &self.output)? {
            return Ok(());
        }
        print_drifts(&drifts);
        Ok(())
    }
}

/// Moves an inline comment's anchor to a new run of text in the current-version
/// ADF and writes the page back.
///
/// Operates entirely on ADF (it never round-trips through JFM, which would
/// discard the annotation marks the anchor depends on). Destructive — the page
/// is updated — so it prompts for confirmation unless `--force`.
#[derive(Parser)]
pub struct ReanchorCommand {
    /// Confluence page ID.
    pub id: String,

    /// The inline comment ID to re-anchor.
    #[arg(long)]
    pub comment: String,

    /// Exact text on the current page to move the comment's anchor to.
    #[arg(long)]
    pub anchor_text: String,

    /// 1-based occurrence to anchor to when `--anchor-text` appears more than
    /// once on the page. Required for ambiguous anchors; rejected if out of range.
    #[arg(long)]
    pub match_index: Option<usize>,

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

    /// Prints what would change without writing the page.
    #[arg(long)]
    pub dry_run: bool,
}

impl ReanchorCommand {
    /// Executes the re-anchor command.
    pub async fn execute(self) -> Result<()> {
        let (client, _instance_url) = create_client()?;
        let api = ConfluenceApi::new(client);
        let mut reader = io::BufReader::new(io::stdin());
        let mut writer = io::stdout();
        self.execute_with_io(&api, &mut reader, &mut writer).await
    }

    /// Inner form taking explicit API and IO handles, for unit tests.
    async fn execute_with_io(
        self,
        api: &ConfluenceApi,
        reader: &mut (dyn BufRead + Send),
        writer: &mut (dyn Write + Send),
    ) -> Result<()> {
        let prompt = format!(
            "Re-anchor inline comment {} on page {} to {:?}? [y/N] ",
            self.comment, self.id, self.anchor_text
        );
        let dry_run_message = format!(
            "Would re-anchor inline comment {} on page {} to {:?}.",
            self.comment, self.id, self.anchor_text
        );
        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 => {}
        }

        let outcome = reanchor_inline_comment(
            api,
            &self.id,
            &self.comment,
            &self.anchor_text,
            self.match_index,
            false,
        )
        .await?;
        writeln!(
            writer,
            "Re-anchored inline comment {} to {:?}.",
            outcome.comment_id, outcome.new_anchor_text
        )?;
        Ok(())
    }
}

/// Prints inline-comment drift reports in a readable format.
fn print_drifts(drifts: &[CommentDrift]) {
    if drifts.is_empty() {
        println!("No inline comments.");
        return;
    }

    for (i, drift) in drifts.iter().enumerate() {
        if i > 0 {
            println!();
        }
        let status = match drift.status {
            DriftStatus::Ok => "OK",
            DriftStatus::Torn => "TORN",
            DriftStatus::MarkLost => "MARK LOST",
            DriftStatus::Drifted => "DRIFTED",
        };
        println!("--- {} | {} ---", drift.comment_id, status);
        println!("  original:  {:?}", drift.original_selection);
        match &drift.current_anchored_text {
            Some(text) => println!("  current:   {text:?}"),
            None => println!("  current:   (mark not present)"),
        }
        if let Some(suggestion) = &drift.suggested_new_anchor {
            let count = drift.suggested_match_count.unwrap_or(0);
            println!("  suggested: {suggestion:?} (appears {count}x on the current page)");
        }
    }
}

/// Parses a comment input file (or stdin) into a validated ADF document.
///
/// Shared by `comment add` (footer) and `comment add-inline` so both surfaces
/// accept the same input formats — JFM with frontmatter, raw markdown, or
/// pre-built ADF JSON.
fn parse_comment_input(file: Option<&str>, format: ContentFormat) -> Result<ValidatedAdfDocument> {
    let input = read_input(file)?;

    let validated: ValidatedAdfDocument = match format {
        ContentFormat::Jfm => {
            if input.starts_with("---\n") {
                let doc = JfmDocument::parse(&input)?;
                markdown_to_validated_adf(&doc.body)?
            } else {
                markdown_to_validated_adf(&input)?
            }
        }
        ContentFormat::Adf => {
            let adf: AdfDocument =
                serde_json::from_str(&input).context("Failed to parse ADF JSON input")?;
            ValidatedAdfDocument::try_new(adf)?
        }
    };
    Ok(validated)
}

/// Fetches and displays comments for a page.
async fn run_list_comments(
    api: &ConfluenceApi,
    id: &str,
    kind: CommentKindFilter,
    limit: usize,
    output: &OutputFormat,
) -> Result<()> {
    let mut comments = match kind {
        CommentKindFilter::Footer => api.get_page_comments(id).await?,
        CommentKindFilter::Inline => api.get_page_inline_comments(id).await?,
        CommentKindFilter::All => {
            let mut footer = api.get_page_comments(id).await?;
            let inline = api.get_page_inline_comments(id).await?;
            footer.extend(inline);
            footer.sort_by(|a, b| a.created.cmp(&b.created));
            footer
        }
    };
    comments.truncate(limit);
    if output_as(&comments, output)? {
        return Ok(());
    }
    print_comments(&comments);
    Ok(())
}

/// Fetches and displays the replies of a single comment.
async fn run_list_replies(
    api: &ConfluenceApi,
    comment_id: &str,
    kind: CommentKind,
    limit: usize,
    output: &OutputFormat,
) -> Result<()> {
    let mut replies = api.get_comment_replies(comment_id, kind).await?;
    replies.truncate(limit);
    if output_as(&replies, output)? {
        return Ok(());
    }
    print_comments(&replies);
    Ok(())
}

/// Posts a footer comment to a page.
async fn run_add_comment(api: &ConfluenceApi, id: &str, adf: &ValidatedAdfDocument) -> Result<()> {
    api.add_page_comment(id, adf).await?;
    println!("Comment added to page {id}.");
    Ok(())
}

/// Posts an inline comment to a page.
async fn run_add_inline_comment(
    api: &ConfluenceApi,
    id: &str,
    adf: &ValidatedAdfDocument,
    anchor: &InlineAnchor,
) -> Result<()> {
    api.add_inline_page_comment(id, adf, anchor).await?;
    println!(
        "Inline comment added to page {id} anchored to {:?} (occurrence {} of {}).",
        anchor.text,
        anchor.match_index + 1,
        anchor.match_count
    );
    Ok(())
}

/// Prints comments in a readable format.
fn print_comments(comments: &[ConfluenceComment]) {
    if comments.is_empty() {
        println!("No comments.");
        return;
    }

    for (i, comment) in comments.iter().enumerate() {
        if i > 0 {
            println!();
        }

        let timestamp = format_timestamp(&comment.created);
        println!(
            "--- {} | {} | {} ---",
            comment.author, timestamp, comment.kind
        );
        println!("{}", format_comment_body(&comment.body_adf));
    }
}

/// Formats a comment body for display.
fn format_comment_body(body_adf: &Option<serde_json::Value>) -> String {
    let Some(adf_value) = body_adf else {
        return "[empty]".to_string();
    };

    let Ok(adf) = serde_json::from_value::<AdfDocument>(adf_value.clone()) else {
        return "[ADF content]".to_string();
    };

    let Ok(md) = adf_to_markdown(&adf) else {
        return "[ADF content]".to_string();
    };

    let trimmed = md.trim();
    if trimmed.is_empty() {
        "[empty]".to_string()
    } else {
        trimmed.to_string()
    }
}

/// Formats an ISO 8601 timestamp to a shorter display format.
fn format_timestamp(ts: &str) -> &str {
    // Return just the date+time portion (before the timezone offset or milliseconds)
    // e.g., "2026-04-01T10:00:00.000Z" -> "2026-04-01T10:00:00"
    ts.split('.').next().unwrap_or(ts)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::await_holding_lock)]
mod tests {
    use super::*;
    use std::fs;

    fn sample_comment(
        id: &str,
        author: &str,
        body_adf: Option<serde_json::Value>,
    ) -> ConfluenceComment {
        ConfluenceComment {
            id: id.to_string(),
            author: author.to_string(),
            kind: CommentKind::Footer,
            body_adf,
            created: "2026-04-01T10:30:00.000Z".to_string(),
            inline_marker_ref: None,
            inline_original_selection: None,
        }
    }

    fn sample_inline_comment(
        id: &str,
        author: &str,
        body_adf: Option<serde_json::Value>,
    ) -> ConfluenceComment {
        ConfluenceComment {
            id: id.to_string(),
            author: author.to_string(),
            kind: CommentKind::Inline,
            body_adf,
            created: "2026-04-02T10:30:00.000Z".to_string(),
            inline_marker_ref: Some("marker-1".to_string()),
            inline_original_selection: Some("original highlighted text".to_string()),
        }
    }

    // ── print_comments ─────────────────────────────────────────────

    #[test]
    fn print_comments_empty() {
        print_comments(&[]);
    }

    #[test]
    fn print_comments_with_adf_body() {
        let adf = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Hello world"}]}]
        });
        let comments = vec![sample_comment("1", "Alice", Some(adf))];
        print_comments(&comments);
    }

    #[test]
    fn print_comments_with_null_body() {
        let comments = vec![sample_comment("1", "Bob", None)];
        print_comments(&comments);
    }

    #[test]
    fn print_comments_with_invalid_adf() {
        let invalid = serde_json::json!({"not": "adf"});
        let comments = vec![sample_comment("1", "Carol", Some(invalid))];
        print_comments(&comments);
    }

    #[test]
    fn print_comments_multiple() {
        let adf = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": "First"}]}]
        });
        let comments = vec![
            sample_comment("1", "Alice", Some(adf)),
            sample_inline_comment("2", "Bob", None),
        ];
        print_comments(&comments);
    }

    // ── format_comment_body ─────────────────────────────────────────

    #[test]
    fn format_body_none() {
        assert_eq!(format_comment_body(&None), "[empty]");
    }

    #[test]
    fn format_body_valid_adf_with_text() {
        let adf = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Hello"}]}]
        });
        let result = format_comment_body(&Some(adf));
        assert_eq!(result, "Hello");
    }

    #[test]
    fn format_body_valid_adf_empty_content() {
        let adf = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": []
        });
        let result = format_comment_body(&Some(adf));
        assert_eq!(result, "[empty]");
    }

    #[test]
    fn format_body_invalid_adf() {
        let invalid = serde_json::json!({"not": "adf"});
        assert_eq!(format_comment_body(&Some(invalid)), "[ADF content]");
    }

    // ── format_timestamp ───────────────────────────────────────────

    #[test]
    fn format_timestamp_with_millis() {
        assert_eq!(
            format_timestamp("2026-04-01T10:30:00.000Z"),
            "2026-04-01T10:30:00"
        );
    }

    #[test]
    fn format_timestamp_without_millis() {
        assert_eq!(
            format_timestamp("2026-04-01T10:30:00"),
            "2026-04-01T10:30:00"
        );
    }

    #[test]
    fn format_timestamp_empty() {
        assert_eq!(format_timestamp(""), "");
    }

    // ── parse_comment_input ────────────────────────────────────────

    #[test]
    fn parse_input_raw_markdown() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("comment.md");
        fs::write(&file_path, "Hello **world**\n").unwrap();

        let adf =
            parse_comment_input(Some(file_path.to_str().unwrap()), ContentFormat::Jfm).unwrap();
        assert!(!adf.content.is_empty());
    }

    #[test]
    fn parse_input_jfm_with_frontmatter() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("comment.md");
        let content =
            "---\ntype: confluence\ninstance: https://org.atlassian.net\nid: \"12345\"\ntitle: Test\nspace_key: ENG\n---\n\nComment body\n";
        fs::write(&file_path, content).unwrap();

        let adf =
            parse_comment_input(Some(file_path.to_str().unwrap()), ContentFormat::Jfm).unwrap();
        assert!(!adf.content.is_empty());
    }

    #[test]
    fn parse_input_adf_format() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("comment.json");
        let adf_json = r#"{"version":1,"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Hello"}]}]}"#;
        fs::write(&file_path, adf_json).unwrap();

        let adf =
            parse_comment_input(Some(file_path.to_str().unwrap()), ContentFormat::Adf).unwrap();
        assert_eq!(adf.content.len(), 1);
    }

    #[test]
    fn parse_input_invalid_adf() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("bad.json");
        fs::write(&file_path, "not json").unwrap();

        assert!(
            parse_comment_input(Some(file_path.to_str().unwrap()), ContentFormat::Adf).is_err()
        );
    }

    #[test]
    fn parse_input_jfm_rejects_invalid_adf_nesting() {
        // Issue #714: JFM that converts to invalid ADF (panel→expand) must
        // be rejected at parse time, before the API call.
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("bad.md");
        fs::write(
            &file_path,
            ":::panel{type=info}\n:::expand{title=\"x\"}\nbody\n:::\n:::",
        )
        .unwrap();

        let err =
            parse_comment_input(Some(file_path.to_str().unwrap()), ContentFormat::Jfm).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("invalid ADF nesting"));
        assert!(msg.contains("`expand` cannot be a child of `panel`"));
    }

    // ── CommentCommand dispatch ────────────────────────────────────

    #[test]
    fn comment_command_list_variant() {
        let cmd = CommentCommand {
            command: CommentSubcommands::List(ListCommand {
                id: "12345".to_string(),
                kind: CommentKindFilter::All,
                limit: 25,
                output: OutputFormat::Table,
            }),
        };
        assert!(matches!(cmd.command, CommentSubcommands::List(_)));
    }

    #[test]
    fn comment_command_add_variant() {
        let cmd = CommentCommand {
            command: CommentSubcommands::Add(AddCommand {
                id: "12345".to_string(),
                file: None,
                format: ContentFormat::Jfm,
            }),
        };
        assert!(matches!(cmd.command, CommentSubcommands::Add(_)));
    }

    #[test]
    fn comment_command_add_inline_variant() {
        let cmd = CommentCommand {
            command: CommentSubcommands::AddInline(AddInlineCommand {
                id: "12345".to_string(),
                file: None,
                format: ContentFormat::Jfm,
                anchor_text: "phrase".to_string(),
                match_index: None,
            }),
        };
        assert!(matches!(cmd.command, CommentSubcommands::AddInline(_)));
    }

    #[test]
    fn comment_command_replies_variant() {
        let cmd = CommentCommand {
            command: CommentSubcommands::Replies(RepliesCommand {
                id: "abc".to_string(),
                kind: CommentKindArg::Inline,
                limit: 25,
                output: OutputFormat::Table,
            }),
        };
        assert!(matches!(cmd.command, CommentSubcommands::Replies(_)));
    }

    // ── CommentKindArg → CommentKind conversion ────────────────────

    #[test]
    fn comment_kind_arg_into_footer() {
        let k: CommentKind = CommentKindArg::Footer.into();
        assert_eq!(k, CommentKind::Footer);
    }

    #[test]
    fn comment_kind_arg_into_inline() {
        let k: CommentKind = CommentKindArg::Inline.into();
        assert_eq!(k, CommentKind::Inline);
    }

    // ── run_list_comments / run_add_comment ────────────────────────

    fn mock_api(server: &wiremock::MockServer) -> ConfluenceApi {
        let client =
            crate::atlassian::client::AtlassianClient::new(&server.uri(), "user@test.com", "token")
                .unwrap();
        ConfluenceApi::new(client)
    }

    #[tokio::test]
    async fn run_list_comments_success() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/footer-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&server)
            .await;

        let api = mock_api(&server);
        assert!(run_list_comments(
            &api,
            "12345",
            CommentKindFilter::Footer,
            25,
            &OutputFormat::Table,
        )
        .await
        .is_ok());
    }

    #[tokio::test]
    async fn run_list_comments_json_output() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/footer-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&server)
            .await;

        let api = mock_api(&server);
        assert!(run_list_comments(
            &api,
            "12345",
            CommentKindFilter::Footer,
            25,
            &OutputFormat::Json,
        )
        .await
        .is_ok());
    }

    #[tokio::test]
    async fn run_list_comments_api_error() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/99999/footer-comments",
            ))
            .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("Not Found"))
            .mount(&server)
            .await;

        let api = mock_api(&server);
        let err = run_list_comments(
            &api,
            "99999",
            CommentKindFilter::Footer,
            25,
            &OutputFormat::Table,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("404"));
    }

    #[tokio::test]
    async fn run_list_comments_inline_kind_hits_inline_endpoint() {
        // `Inline` filter must NOT touch the footer endpoint.
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/inline-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .expect(1)
            .mount(&server)
            .await;

        let api = mock_api(&server);
        assert!(run_list_comments(
            &api,
            "12345",
            CommentKindFilter::Inline,
            25,
            &OutputFormat::Json,
        )
        .await
        .is_ok());
    }

    #[tokio::test]
    async fn run_list_comments_all_kind_fetches_both() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/footer-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [{
                        "id": "f1",
                        "version": {"authorId": "alice", "createdAt": "2026-04-01T10:00:00Z"}
                    }]
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/inline-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [{
                        "id": "i1",
                        "version": {"authorId": "bob", "createdAt": "2026-04-02T10:00:00Z"}
                    }]
                })),
            )
            .mount(&server)
            .await;

        let api = mock_api(&server);
        assert!(run_list_comments(
            &api,
            "12345",
            CommentKindFilter::All,
            25,
            &OutputFormat::Json,
        )
        .await
        .is_ok());
    }

    #[tokio::test]
    async fn run_list_replies_success() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/inline-comments/abc/children",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&server)
            .await;

        let api = mock_api(&server);
        assert!(
            run_list_replies(&api, "abc", CommentKind::Inline, 25, &OutputFormat::Table,)
                .await
                .is_ok()
        );
    }

    #[tokio::test]
    async fn run_add_comment_success() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/wiki/api/v2/footer-comments"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "200"})),
            )
            .mount(&server)
            .await;

        let api = mock_api(&server);
        let adf = ValidatedAdfDocument::empty();
        assert!(run_add_comment(&api, "12345", &adf).await.is_ok());
    }

    #[tokio::test]
    async fn run_add_comment_api_error() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/wiki/api/v2/footer-comments"))
            .respond_with(wiremock::ResponseTemplate::new(403).set_body_string("Forbidden"))
            .mount(&server)
            .await;

        let api = mock_api(&server);
        let adf = ValidatedAdfDocument::empty();
        let err = run_add_comment(&api, "12345", &adf).await.unwrap_err();
        assert!(err.to_string().contains("403"));
    }

    #[tokio::test]
    async fn run_add_inline_comment_success() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/wiki/api/v2/inline-comments"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "300"})),
            )
            .mount(&server)
            .await;

        let api = mock_api(&server);
        let adf = ValidatedAdfDocument::empty();
        let anchor = InlineAnchor {
            text: "phrase".to_string(),
            match_index: 0,
            match_count: 1,
        };
        assert!(run_add_inline_comment(&api, "12345", &adf, &anchor)
            .await
            .is_ok());
    }

    // ── *Command::execute (env-mutex serialised) ───────────────────
    //
    // Each `*::execute()` is a thin wrapper around `create_client()` and a
    // `run_*` helper. Exercising the `Err` propagation through `?` plus one
    // happy-path dispatch is enough to cover the wrapper; the underlying
    // helper logic is covered by the `run_*` tests above.

    fn set_atlassian_env(uri: &str) {
        std::env::set_var(crate::atlassian::auth::ATLASSIAN_INSTANCE_URL, uri);
        std::env::set_var(crate::atlassian::auth::ATLASSIAN_EMAIL, "user@test.com");
        std::env::set_var(crate::atlassian::auth::ATLASSIAN_API_TOKEN, "t");
    }

    fn clear_atlassian_env() {
        std::env::remove_var(crate::atlassian::auth::ATLASSIAN_INSTANCE_URL);
        std::env::remove_var(crate::atlassian::auth::ATLASSIAN_EMAIL);
        std::env::remove_var(crate::atlassian::auth::ATLASSIAN_API_TOKEN);
    }

    #[tokio::test]
    async fn list_command_execute_propagates_create_client_error() {
        let guard = crate::atlassian::auth::test_util::EnvGuard::take();
        let _home = guard.clear_credentials();

        let cmd = ListCommand {
            id: "12345".to_string(),
            kind: CommentKindFilter::All,
            limit: 25,
            output: OutputFormat::Yaml,
        };
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn list_command_execute_runs_through_dispatch() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/footer-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/inline-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&server)
            .await;

        set_atlassian_env(&server.uri());
        let cmd = CommentCommand {
            command: CommentSubcommands::List(ListCommand {
                id: "12345".to_string(),
                kind: CommentKindFilter::All,
                limit: 25,
                output: OutputFormat::Json,
            }),
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    #[tokio::test]
    async fn add_command_execute_propagates_create_client_error() {
        let guard = crate::atlassian::auth::test_util::EnvGuard::take();
        let _home = guard.clear_credentials();

        let temp_dir = tempfile::tempdir().unwrap();
        let body_path = temp_dir.path().join("body.md");
        fs::write(&body_path, "Hello").unwrap();

        let cmd = AddCommand {
            id: "12345".to_string(),
            file: Some(body_path.to_str().unwrap().to_string()),
            format: ContentFormat::Jfm,
        };
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn add_command_execute_runs_through_dispatch() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/wiki/api/v2/footer-comments"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "c9"})),
            )
            .mount(&server)
            .await;

        let temp_dir = tempfile::tempdir().unwrap();
        let body_path = temp_dir.path().join("body.md");
        fs::write(&body_path, "Hello").unwrap();

        set_atlassian_env(&server.uri());
        let cmd = CommentCommand {
            command: CommentSubcommands::Add(AddCommand {
                id: "12345".to_string(),
                file: Some(body_path.to_str().unwrap().to_string()),
                format: ContentFormat::Jfm,
            }),
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    #[tokio::test]
    async fn add_inline_command_execute_propagates_create_client_error() {
        let guard = crate::atlassian::auth::test_util::EnvGuard::take();
        let _home = guard.clear_credentials();

        let temp_dir = tempfile::tempdir().unwrap();
        let body_path = temp_dir.path().join("body.md");
        fs::write(&body_path, "Hello").unwrap();

        let cmd = AddInlineCommand {
            id: "12345".to_string(),
            file: Some(body_path.to_str().unwrap().to_string()),
            format: ContentFormat::Jfm,
            anchor_text: "phrase".to_string(),
            match_index: None,
        };
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn add_inline_command_execute_runs_through_dispatch() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "12345",
                    "title": "Mock",
                    "status": "current",
                    "spaceId": "98",
                    "version": {"number": 1},
                    "body": {"atlas_doc_format": {
                        "value": "{\"version\":1,\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"the anchor\"}]}]}"
                    }}
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces/98"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"key": "ENG"})),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/wiki/api/v2/inline-comments"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "ic1"})),
            )
            .mount(&server)
            .await;

        let temp_dir = tempfile::tempdir().unwrap();
        let body_path = temp_dir.path().join("body.md");
        fs::write(&body_path, "Inline note").unwrap();

        set_atlassian_env(&server.uri());
        let cmd = CommentCommand {
            command: CommentSubcommands::AddInline(AddInlineCommand {
                id: "12345".to_string(),
                file: Some(body_path.to_str().unwrap().to_string()),
                format: ContentFormat::Jfm,
                anchor_text: "the anchor".to_string(),
                match_index: None,
            }),
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    #[tokio::test]
    async fn replies_command_execute_propagates_create_client_error() {
        let guard = crate::atlassian::auth::test_util::EnvGuard::take();
        let _home = guard.clear_credentials();

        let cmd = RepliesCommand {
            id: "abc".to_string(),
            kind: CommentKindArg::Inline,
            limit: 25,
            output: OutputFormat::Yaml,
        };
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn replies_command_execute_runs_through_dispatch() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/inline-comments/abc/children",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"results": []})),
            )
            .mount(&server)
            .await;

        set_atlassian_env(&server.uri());
        let cmd = CommentCommand {
            command: CommentSubcommands::Replies(RepliesCommand {
                id: "abc".to_string(),
                kind: CommentKindArg::Inline,
                limit: 25,
                output: OutputFormat::Json,
            }),
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    // ── print_drifts ───────────────────────────────────────────────

    fn sample_drift(id: &str, status: DriftStatus) -> CommentDrift {
        CommentDrift {
            comment_id: id.to_string(),
            author: "alice".to_string(),
            created: "2026-04-01T10:00:00.000Z".to_string(),
            marker_ref: "marker-1".to_string(),
            status,
            original_selection: "original text".to_string(),
            current_anchored_text: Some("current text".to_string()),
            suggested_new_anchor: None,
            suggested_match_count: None,
        }
    }

    #[test]
    fn print_drifts_empty() {
        print_drifts(&[]);
    }

    #[test]
    fn print_drifts_all_statuses() {
        let mut lost = sample_drift("c3", DriftStatus::MarkLost);
        lost.current_anchored_text = None;
        lost.suggested_new_anchor = Some("original text".to_string());
        lost.suggested_match_count = Some(2);
        let mut drifted = sample_drift("c4", DriftStatus::Drifted);
        // Suggestion without a count exercises the `unwrap_or(0)` fallback.
        drifted.suggested_new_anchor = Some("original text".to_string());
        let drifts = vec![
            sample_drift("c1", DriftStatus::Ok),
            sample_drift("c2", DriftStatus::Torn),
            lost,
            drifted,
        ];
        print_drifts(&drifts);
    }

    // ── audit / reanchor command execution ──────────────────────────

    /// Mounts the endpoints a reanchor (and audit) needs: the page (whose ADF
    /// contains "the anchor"), its space, one inline comment `ic1` bearing
    /// marker `aaa`, and the page-update PUT.
    async fn mount_reanchor_fixture(server: &wiremock::MockServer) {
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "12345",
                    "title": "Mock",
                    "status": "current",
                    "spaceId": "98",
                    "version": {"number": 1},
                    "body": {"atlas_doc_format": {
                        "value": "{\"version\":1,\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"the anchor\"}]}]}"
                    }}
                })),
            )
            .mount(server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces/98"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"key": "ENG"})),
            )
            .mount(server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(
                "/wiki/api/v2/pages/12345/inline-comments",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "results": [
                        {"id": "ic1", "version": {"authorId": "a", "createdAt": "t"},
                         "properties": {"inlineMarkerRef": "aaa", "inlineOriginalSelection": "old"}}
                    ]
                })),
            )
            .mount(server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("PUT"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/12345"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
            .mount(server)
            .await;
    }

    #[tokio::test]
    async fn audit_command_execute_propagates_create_client_error() {
        let guard = crate::atlassian::auth::test_util::EnvGuard::take();
        let _home = guard.clear_credentials();

        let cmd = AuditCommand {
            id: "12345".to_string(),
            output: OutputFormat::Yaml,
        };
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn audit_command_execute_runs_through_dispatch() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        let server = wiremock::MockServer::start().await;
        mount_reanchor_fixture(&server).await;

        set_atlassian_env(&server.uri());
        let cmd = CommentCommand {
            command: CommentSubcommands::Audit(AuditCommand {
                id: "12345".to_string(),
                output: OutputFormat::Json,
            }),
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    #[tokio::test(flavor = "current_thread")]
    async fn audit_command_execute_table_output_prints_drifts() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        let server = wiremock::MockServer::start().await;
        mount_reanchor_fixture(&server).await;

        set_atlassian_env(&server.uri());
        let cmd = AuditCommand {
            id: "12345".to_string(),
            output: OutputFormat::Table,
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    fn reanchor_command(force: bool, dry_run: bool) -> ReanchorCommand {
        ReanchorCommand {
            id: "12345".to_string(),
            comment: "ic1".to_string(),
            anchor_text: "the anchor".to_string(),
            match_index: None,
            force,
            dry_run,
        }
    }

    #[tokio::test]
    async fn reanchor_command_execute_propagates_create_client_error() {
        let guard = crate::atlassian::auth::test_util::EnvGuard::take();
        let _home = guard.clear_credentials();

        let cmd = reanchor_command(true, false);
        assert!(cmd.execute().await.is_err());
    }

    #[tokio::test(flavor = "current_thread")]
    async fn reanchor_command_execute_runs_through_dispatch() {
        let _lock = crate::atlassian::auth::test_util::AUTH_ENV_MUTEX
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        let server = wiremock::MockServer::start().await;
        mount_reanchor_fixture(&server).await;

        set_atlassian_env(&server.uri());
        let cmd = CommentCommand {
            command: CommentSubcommands::Reanchor(reanchor_command(true, false)),
        };
        let result = cmd.execute().await;
        clear_atlassian_env();
        assert!(result.is_ok(), "{result:?}");
    }

    #[tokio::test]
    async fn reanchor_execute_with_io_cancelled_makes_no_api_calls() {
        let server = wiremock::MockServer::start().await;
        let api = mock_api(&server);

        let cmd = reanchor_command(false, false);
        let mut reader = io::Cursor::new(b"n\n".to_vec());
        let mut writer: Vec<u8> = Vec::new();
        cmd.execute_with_io(&api, &mut reader, &mut writer)
            .await
            .unwrap();

        let out = String::from_utf8(writer).unwrap();
        assert!(out.contains("Re-anchor inline comment ic1"));
        assert!(out.contains("Cancelled."));
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn reanchor_execute_with_io_dry_run_makes_no_api_calls() {
        let server = wiremock::MockServer::start().await;
        let api = mock_api(&server);

        let cmd = reanchor_command(false, true);
        let mut reader = io::Cursor::new(Vec::new());
        let mut writer: Vec<u8> = Vec::new();
        cmd.execute_with_io(&api, &mut reader, &mut writer)
            .await
            .unwrap();

        let out = String::from_utf8(writer).unwrap();
        assert!(out.contains("Would re-anchor inline comment ic1"));
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn reanchor_execute_with_io_confirmed_proceeds() {
        let server = wiremock::MockServer::start().await;
        mount_reanchor_fixture(&server).await;
        let api = mock_api(&server);

        let cmd = reanchor_command(false, false);
        let mut reader = io::Cursor::new(b"y\n".to_vec());
        let mut writer: Vec<u8> = Vec::new();
        cmd.execute_with_io(&api, &mut reader, &mut writer)
            .await
            .unwrap();

        let out = String::from_utf8(writer).unwrap();
        assert!(out.contains("Re-anchored inline comment ic1"));
        let requests = server.received_requests().await.unwrap();
        assert!(requests
            .iter()
            .any(|r| r.method == wiremock::http::Method::PUT));
    }

    /// A writer that fails at a chosen point (`write` or, when writes are
    /// allowed through, `flush`), for exercising IO-error propagation through
    /// `execute_with_io`.
    struct FailingWriter {
        fail_write: bool,
    }

    impl Write for FailingWriter {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            if self.fail_write {
                Err(io::Error::other("writer failed"))
            } else {
                Ok(buf.len())
            }
        }

        fn flush(&mut self) -> io::Result<()> {
            Err(io::Error::other("writer failed"))
        }
    }

    #[tokio::test]
    async fn reanchor_execute_with_io_propagates_prompt_write_error() {
        let server = wiremock::MockServer::start().await;
        let api = mock_api(&server);

        // Without --force the guard writes the prompt first; the failing
        // writer surfaces that IO error before any API call.
        let cmd = reanchor_command(false, false);
        let mut reader = io::Cursor::new(b"y\n".to_vec());
        let mut writer = FailingWriter { fail_write: true };
        assert!(cmd
            .execute_with_io(&api, &mut reader, &mut writer)
            .await
            .is_err());
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn reanchor_execute_with_io_propagates_prompt_flush_error() {
        let server = wiremock::MockServer::start().await;
        let api = mock_api(&server);

        // Writes go through but the guard's flush after the prompt fails.
        let cmd = reanchor_command(false, false);
        let mut reader = io::Cursor::new(b"y\n".to_vec());
        let mut writer = FailingWriter { fail_write: false };
        assert!(cmd
            .execute_with_io(&api, &mut reader, &mut writer)
            .await
            .is_err());
        assert!(server.received_requests().await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn reanchor_execute_with_io_propagates_result_write_error() {
        let server = wiremock::MockServer::start().await;
        mount_reanchor_fixture(&server).await;
        let api = mock_api(&server);

        // With --force the guard writes nothing; the re-anchor succeeds and
        // the failure comes from writing the success message.
        let cmd = reanchor_command(true, false);
        let mut reader = io::Cursor::new(Vec::new());
        let mut writer = FailingWriter { fail_write: true };
        assert!(cmd
            .execute_with_io(&api, &mut reader, &mut writer)
            .await
            .is_err());
        let requests = server.received_requests().await.unwrap();
        assert!(requests
            .iter()
            .any(|r| r.method == wiremock::http::Method::PUT));
    }
}