omni-dev 0.23.1

A powerful Git commit message analysis and amendment toolkit
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
//! MCP resource URIs: parsing and read dispatch.
//!
//! Resources expose omni-dev content at stable URIs so an MCP client can
//! fetch them without issuing a tool call. Each URI template is backed by
//! the same core function the CLI uses, so surface and CLI stay in lock
//! step. See issue #606 for the URI catalogue.

use anyhow::{Context, Result};
use rmcp::{
    model::{
        ListResourceTemplatesResult, ListResourcesResult, RawResource, RawResourceTemplate,
        ReadResourceResult, Resource, ResourceContents, ResourceTemplate,
    },
    ErrorData as McpError,
};
use serde_json::json;

use crate::atlassian::api::{AtlassianApi, ContentItem};
use crate::atlassian::confluence_api::ConfluenceApi;
use crate::atlassian::document::content_item_to_document;
use crate::atlassian::jira_api::JiraApi;
use crate::cli::atlassian::helpers::create_client;

/// Format suffix for a resource URI.
///
/// `git://` URIs do not carry a format suffix (always YAML). Atlassian URIs
/// accept an optional `.adf` suffix: absent means JFM markdown, present means
/// raw ADF JSON.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResourceFormat {
    /// JFM markdown (the default for Atlassian resources).
    Jfm,
    /// Raw ADF JSON (opted into via the `.adf` suffix).
    Adf,
}

/// A parsed omni-dev resource URI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResourceUri {
    /// `git://repo/commits/{range}` — YAML commit analysis.
    GitCommits {
        /// A git revision range or single ref (e.g. `HEAD`, `HEAD~3..HEAD`).
        range: String,
    },
    /// `jira://issue/{key}` / `jira://issue/{key}.adf` — JIRA issue body.
    JiraIssue {
        /// JIRA issue key (e.g. `PROJ-123`).
        key: String,
        /// Output format: JFM or ADF JSON.
        format: ResourceFormat,
    },
    /// `confluence://page/{id}` / `confluence://page/{id}.adf` — Confluence page.
    ConfluencePage {
        /// Confluence page id (decimal string).
        id: String,
        /// Output format: JFM or ADF JSON.
        format: ResourceFormat,
    },
}

/// Errors returned by the URI parser.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum UriParseError {
    /// The URI scheme is not one omni-dev knows about.
    #[error("unknown URI scheme in `{0}`; expected git://, jira://, or confluence://")]
    UnknownScheme(String),
    /// The URI authority/path shape does not match any known template.
    #[error("malformed URI `{0}`: {1}")]
    Malformed(String, &'static str),
    /// The path identifier (range, key, id) is empty.
    #[error("empty identifier in URI `{0}`")]
    EmptyIdentifier(String),
}

impl ResourceUri {
    /// Parses a resource URI string.
    ///
    /// Rejects URIs that do not match one of the known templates.
    pub fn parse(uri: &str) -> Result<Self, UriParseError> {
        if let Some(rest) = uri.strip_prefix("git://repo/commits/") {
            if rest.is_empty() {
                return Err(UriParseError::EmptyIdentifier(uri.to_string()));
            }
            return Ok(Self::GitCommits {
                range: rest.to_string(),
            });
        }

        if let Some(rest) = uri.strip_prefix("jira://issue/") {
            let (key, format) = split_suffix(rest);
            if key.is_empty() {
                return Err(UriParseError::EmptyIdentifier(uri.to_string()));
            }
            return Ok(Self::JiraIssue {
                key: key.to_string(),
                format,
            });
        }

        if let Some(rest) = uri.strip_prefix("confluence://page/") {
            let (id, format) = split_suffix(rest);
            if id.is_empty() {
                return Err(UriParseError::EmptyIdentifier(uri.to_string()));
            }
            return Ok(Self::ConfluencePage {
                id: id.to_string(),
                format,
            });
        }

        // Reject `<scheme>://` URIs with a different path shape explicitly
        // rather than falling through to UnknownScheme, so the client sees
        // what's actually wrong. Placeholders are escaped for the lint.
        if uri.starts_with("git://") {
            return Err(UriParseError::Malformed(
                uri.to_string(),
                "expected `git://repo/commits/<range>`",
            ));
        }
        if uri.starts_with("jira://") {
            return Err(UriParseError::Malformed(
                uri.to_string(),
                "expected `jira://issue/<key>` or `jira://issue/<key>.adf`",
            ));
        }
        if uri.starts_with("confluence://") {
            return Err(UriParseError::Malformed(
                uri.to_string(),
                "expected `confluence://page/<id>` or `confluence://page/<id>.adf`",
            ));
        }

        Err(UriParseError::UnknownScheme(uri.to_string()))
    }
}

/// Splits a trailing `.adf` suffix off a path segment.
fn split_suffix(rest: &str) -> (&str, ResourceFormat) {
    match rest.strip_suffix(".adf") {
        Some(id) => (id, ResourceFormat::Adf),
        None => (rest, ResourceFormat::Jfm),
    }
}

/// The static catalogue of resource templates omni-dev advertises.
///
/// Returned by `list_resource_templates`. URIs are RFC 6570 templates; the
/// placeholders match the identifiers [`ResourceUri::parse`] understands.
pub fn resource_templates() -> Vec<ResourceTemplate> {
    let git_commits = RawResourceTemplate::new("git://repo/commits/{range}", "git_commits")
        .with_description(
            "YAML commit analysis for a git range (e.g. `HEAD`, `HEAD~3..HEAD`). \
             Backed by the same core as `omni-dev git commit message view`.",
        )
        .with_mime_type("application/yaml");

    let jira_issue_jfm = RawResourceTemplate::new("jira://issue/{key}", "jira_issue_jfm")
        .with_description("JIRA issue rendered as JFM (JIRA-flavoured markdown).")
        .with_mime_type("text/markdown");

    let jira_issue_adf = RawResourceTemplate::new("jira://issue/{key}.adf", "jira_issue_adf")
        .with_description("JIRA issue body as raw Atlassian Document Format (ADF) JSON.")
        .with_mime_type("application/json");

    let confluence_page_jfm =
        RawResourceTemplate::new("confluence://page/{id}", "confluence_page_jfm")
            .with_description("Confluence page rendered as JFM markdown.")
            .with_mime_type("text/markdown");

    let confluence_page_adf =
        RawResourceTemplate::new("confluence://page/{id}.adf", "confluence_page_adf")
            .with_description("Confluence page body as raw ADF JSON.")
            .with_mime_type("application/json");

    vec![
        annotate_template(git_commits),
        annotate_template(jira_issue_jfm),
        annotate_template(jira_issue_adf),
        annotate_template(confluence_page_jfm),
        annotate_template(confluence_page_adf),
    ]
}

fn annotate_template(raw: RawResourceTemplate) -> ResourceTemplate {
    ResourceTemplate {
        raw,
        annotations: None,
    }
}

/// Resources surfaced by `list_resources`.
///
/// Per the MCP spec, resources returned here must have concrete URIs. We
/// expose the URI templates themselves as informational pointers so a client
/// that does not support `list_resource_templates` can still discover the
/// URI shape; real content lives behind `read_resource`.
pub fn resource_listing() -> Vec<Resource> {
    resource_templates()
        .into_iter()
        .map(|tpl| {
            let RawResourceTemplate {
                uri_template,
                name,
                title,
                description,
                mime_type,
                icons,
            } = tpl.raw;
            Resource {
                raw: RawResource {
                    uri: uri_template,
                    name,
                    title,
                    description,
                    mime_type,
                    size: None,
                    icons,
                    meta: None,
                },
                annotations: None,
            }
        })
        .collect()
}

/// Resolves a parsed URI into [`ReadResourceResult`] contents.
pub async fn read_resource(uri: &ResourceUri, raw_uri: &str) -> Result<ReadResourceResult> {
    match uri {
        ResourceUri::GitCommits { range } => {
            let range = range.clone();
            let yaml = tokio::task::spawn_blocking(move || {
                crate::cli::git::run_view(&range, None::<&str>)
            })
            .await
            .context("git run_view task panicked")??;
            Ok(ReadResourceResult::new(vec![ResourceContents::text(
                yaml, raw_uri,
            )
            .with_mime_type("application/yaml")]))
        }
        ResourceUri::JiraIssue { key, format } => {
            let (client, instance_url) =
                create_client().context("Failed to load Atlassian credentials")?;
            let api = JiraApi::new(client);
            let item = api
                .get_content(key)
                .await
                .with_context(|| format!("Failed to fetch JIRA issue {key}"))?;
            let (text, mime) = render_content_item(&item, &instance_url, *format)?;
            Ok(ReadResourceResult::new(vec![ResourceContents::text(
                text, raw_uri,
            )
            .with_mime_type(mime)]))
        }
        ResourceUri::ConfluencePage { id, format } => {
            let (client, instance_url) =
                create_client().context("Failed to load Atlassian credentials")?;
            let api = ConfluenceApi::new(client);
            let item = api
                .get_content(id)
                .await
                .with_context(|| format!("Failed to fetch Confluence page {id}"))?;
            let (text, mime) = render_content_item(&item, &instance_url, *format)?;
            Ok(ReadResourceResult::new(vec![ResourceContents::text(
                text, raw_uri,
            )
            .with_mime_type(mime)]))
        }
    }
}

/// Renders a [`ContentItem`] as either JFM markdown or ADF JSON.
///
/// Returns the rendered text and the MIME type to advertise.
pub fn render_content_item(
    item: &ContentItem,
    instance_url: &str,
    format: ResourceFormat,
) -> Result<(String, &'static str)> {
    match format {
        ResourceFormat::Jfm => {
            let doc = content_item_to_document(item, instance_url)?;
            let rendered = doc.render()?;
            Ok((rendered, "text/markdown"))
        }
        ResourceFormat::Adf => {
            let json = serde_json::to_string_pretty(
                &item.body_adf.clone().unwrap_or(serde_json::Value::Null),
            )
            .context("Failed to serialize ADF JSON")?;
            Ok((json, "application/json"))
        }
    }
}

/// Converts a URI-lookup failure into a protocol-level `resource_not_found`.
///
/// The raw URI is included in `data` per the MCP spec so the client can tell
/// which resource failed when multiple reads are in flight.
pub fn not_found(uri: &str, reason: impl std::fmt::Display) -> McpError {
    McpError::resource_not_found(
        format!("resource_not_found: {reason}"),
        Some(json!({ "uri": uri })),
    )
}

/// Builds the full [`ListResourcesResult`] payload.
pub fn list_resources_result() -> ListResourcesResult {
    ListResourcesResult {
        resources: resource_listing(),
        next_cursor: None,
        meta: None,
    }
}

/// Builds the full [`ListResourceTemplatesResult`] payload.
pub fn list_resource_templates_result() -> ListResourceTemplatesResult {
    ListResourceTemplatesResult {
        resource_templates: resource_templates(),
        next_cursor: None,
        meta: None,
    }
}

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

    // ── Parser ─────────────────────────────────────────────────────

    #[test]
    fn parse_git_commits_head() {
        let uri = ResourceUri::parse("git://repo/commits/HEAD").unwrap();
        assert_eq!(
            uri,
            ResourceUri::GitCommits {
                range: "HEAD".to_string(),
            }
        );
    }

    #[test]
    fn parse_git_commits_range() {
        let uri = ResourceUri::parse("git://repo/commits/HEAD~3..HEAD").unwrap();
        assert_eq!(
            uri,
            ResourceUri::GitCommits {
                range: "HEAD~3..HEAD".to_string(),
            }
        );
    }

    #[test]
    fn parse_git_commits_triple_dot_range() {
        let uri = ResourceUri::parse("git://repo/commits/main...feature").unwrap();
        assert_eq!(
            uri,
            ResourceUri::GitCommits {
                range: "main...feature".to_string(),
            }
        );
    }

    #[test]
    fn parse_jira_issue_jfm() {
        let uri = ResourceUri::parse("jira://issue/PROJ-123").unwrap();
        assert_eq!(
            uri,
            ResourceUri::JiraIssue {
                key: "PROJ-123".to_string(),
                format: ResourceFormat::Jfm,
            }
        );
    }

    #[test]
    fn parse_jira_issue_adf() {
        let uri = ResourceUri::parse("jira://issue/PROJ-123.adf").unwrap();
        assert_eq!(
            uri,
            ResourceUri::JiraIssue {
                key: "PROJ-123".to_string(),
                format: ResourceFormat::Adf,
            }
        );
    }

    #[test]
    fn parse_confluence_page_jfm() {
        let uri = ResourceUri::parse("confluence://page/12345").unwrap();
        assert_eq!(
            uri,
            ResourceUri::ConfluencePage {
                id: "12345".to_string(),
                format: ResourceFormat::Jfm,
            }
        );
    }

    #[test]
    fn parse_confluence_page_adf() {
        let uri = ResourceUri::parse("confluence://page/12345.adf").unwrap();
        assert_eq!(
            uri,
            ResourceUri::ConfluencePage {
                id: "12345".to_string(),
                format: ResourceFormat::Adf,
            }
        );
    }

    #[test]
    fn parse_unknown_scheme_is_rejected() {
        let err = ResourceUri::parse("http://example.com/resource").unwrap_err();
        assert!(matches!(err, UriParseError::UnknownScheme(_)));
    }

    #[test]
    fn parse_empty_string_is_unknown_scheme() {
        let err = ResourceUri::parse("").unwrap_err();
        assert!(matches!(err, UriParseError::UnknownScheme(_)));
    }

    #[test]
    fn parse_git_wrong_path_is_malformed() {
        let err = ResourceUri::parse("git://repo/bogus").unwrap_err();
        match err {
            UriParseError::Malformed(ref uri, reason) => {
                assert_eq!(uri, "git://repo/bogus");
                assert!(reason.contains("git://repo/commits/"));
                assert!(err.to_string().contains("git://repo/bogus"));
            }
            other => panic!("expected Malformed, got {other:?}"),
        }
    }

    #[test]
    fn parse_jira_wrong_path_is_malformed() {
        let err = ResourceUri::parse("jira://board/123").unwrap_err();
        assert!(matches!(err, UriParseError::Malformed(_, _)));
    }

    #[test]
    fn parse_confluence_wrong_path_is_malformed() {
        let err = ResourceUri::parse("confluence://space/ENG").unwrap_err();
        assert!(matches!(err, UriParseError::Malformed(_, _)));
    }

    #[test]
    fn parse_empty_git_range_is_empty_identifier() {
        let err = ResourceUri::parse("git://repo/commits/").unwrap_err();
        assert!(matches!(err, UriParseError::EmptyIdentifier(_)));
    }

    #[test]
    fn parse_empty_jira_key_is_empty_identifier() {
        let err = ResourceUri::parse("jira://issue/").unwrap_err();
        assert!(matches!(err, UriParseError::EmptyIdentifier(_)));
    }

    #[test]
    fn parse_empty_confluence_id_is_empty_identifier() {
        let err = ResourceUri::parse("confluence://page/").unwrap_err();
        assert!(matches!(err, UriParseError::EmptyIdentifier(_)));
    }

    #[test]
    fn parse_jira_adf_with_empty_key_is_empty_identifier() {
        // `jira://issue/.adf` strips to empty key after the `.adf` suffix.
        let err = ResourceUri::parse("jira://issue/.adf").unwrap_err();
        assert!(matches!(err, UriParseError::EmptyIdentifier(_)));
    }

    #[test]
    fn error_messages_surface_uri() {
        let err = ResourceUri::parse("ftp://x").unwrap_err();
        assert!(err.to_string().contains("ftp://x"));
    }

    // ── Templates / listings ───────────────────────────────────────

    #[test]
    fn templates_include_all_five_uris() {
        let templates = resource_templates();
        let template_uris: Vec<&str> = templates
            .iter()
            .map(|t| t.raw.uri_template.as_str())
            .collect();
        assert!(template_uris.contains(&"git://repo/commits/{range}"));
        assert!(template_uris.contains(&"jira://issue/{key}"));
        assert!(template_uris.contains(&"jira://issue/{key}.adf"));
        assert!(template_uris.contains(&"confluence://page/{id}"));
        assert!(template_uris.contains(&"confluence://page/{id}.adf"));
    }

    #[test]
    fn every_template_has_description_and_mime() {
        for tpl in resource_templates() {
            assert!(
                tpl.raw.description.is_some(),
                "missing description for {}",
                tpl.raw.uri_template
            );
            assert!(
                tpl.raw.mime_type.is_some(),
                "missing mime for {}",
                tpl.raw.uri_template
            );
        }
    }

    #[test]
    fn resource_listing_mirrors_templates() {
        let resources = resource_listing();
        let templates = resource_templates();
        assert_eq!(resources.len(), templates.len());
        for (resource, tpl) in resources.iter().zip(templates.iter()) {
            assert_eq!(resource.raw.uri, tpl.raw.uri_template);
            assert_eq!(resource.raw.name, tpl.raw.name);
        }
    }

    #[test]
    fn list_resources_result_has_no_pagination() {
        let result = list_resources_result();
        assert!(result.next_cursor.is_none());
        assert_eq!(result.resources.len(), 5);
    }

    #[test]
    fn list_resource_templates_result_has_no_pagination() {
        let result = list_resource_templates_result();
        assert!(result.next_cursor.is_none());
        assert_eq!(result.resource_templates.len(), 5);
    }

    // ── not_found ──────────────────────────────────────────────────

    #[test]
    fn not_found_puts_uri_in_data() {
        let err = not_found("jira://issue/NOPE", "parse failed");
        assert!(err.message.contains("parse failed"));
        let data = err.data.as_ref().expect("data payload present");
        assert_eq!(
            data.get("uri").and_then(|v| v.as_str()),
            Some("jira://issue/NOPE")
        );
    }

    // ── render_content_item ────────────────────────────────────────

    fn jira_item_with(body: Option<serde_json::Value>) -> ContentItem {
        use crate::atlassian::api::ContentMetadata;
        ContentItem {
            id: "PROJ-1".to_string(),
            title: "Sample".to_string(),
            body_adf: body,
            metadata: ContentMetadata::Jira {
                status: Some("Open".to_string()),
                issue_type: Some("Bug".to_string()),
                assignee: None,
                priority: None,
                labels: vec![],
            },
        }
    }

    #[test]
    fn render_content_item_jfm_contains_frontmatter_and_body() {
        let body = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Hello"}]}]
        });
        let item = jira_item_with(Some(body));
        let (text, mime) =
            render_content_item(&item, "https://org.atlassian.net", ResourceFormat::Jfm).unwrap();
        assert_eq!(mime, "text/markdown");
        assert!(text.contains("PROJ-1"), "missing key: {text}");
        assert!(text.contains("Hello"), "missing body: {text}");
    }

    #[test]
    fn render_content_item_adf_returns_pretty_json() {
        let body = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": []
        });
        let item = jira_item_with(Some(body.clone()));
        let (text, mime) =
            render_content_item(&item, "https://org.atlassian.net", ResourceFormat::Adf).unwrap();
        assert_eq!(mime, "application/json");
        let parsed: serde_json::Value = serde_json::from_str(&text).unwrap();
        assert_eq!(parsed, body);
    }

    #[test]
    fn render_content_item_adf_null_body_serializes_as_null() {
        let item = jira_item_with(None);
        let (text, _) =
            render_content_item(&item, "https://org.atlassian.net", ResourceFormat::Adf).unwrap();
        assert_eq!(text.trim(), "null");
    }

    // ── read_resource (git path only; Atlassian paths need creds) ──

    use git2::{Repository, Signature};

    fn init_tmp_repo() -> tempfile::TempDir {
        let tmp_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
        std::fs::create_dir_all(&tmp_root).unwrap();
        let temp_dir = tempfile::tempdir_in(&tmp_root).unwrap();
        let repo = Repository::init(temp_dir.path()).unwrap();
        {
            let mut config = repo.config().unwrap();
            config.set_str("user.name", "Test").unwrap();
            config.set_str("user.email", "test@example.com").unwrap();
        }
        let signature = Signature::now("Test", "test@example.com").unwrap();
        std::fs::write(temp_dir.path().join("f.txt"), "x").unwrap();
        let mut idx = repo.index().unwrap();
        idx.add_path(std::path::Path::new("f.txt")).unwrap();
        idx.write().unwrap();
        let tree_id = idx.write_tree().unwrap();
        let tree = repo.find_tree(tree_id).unwrap();
        repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            "feat: seed",
            &tree,
            &[],
        )
        .unwrap();
        temp_dir
    }

    use crate::cli::git::CWD_MUTEX;

    // `read_resource` is async and must run with the CWD held fixed, so we
    // hold the guard across `.await` points. The shared
    // `tokio::sync::Mutex` is designed for this; no clippy suppression is
    // needed. The critical section is CPU-bound `run_view` work behind
    // `spawn_blocking`, so no cross-task yield contends for the lock.
    #[tokio::test(flavor = "multi_thread")]
    async fn read_resource_git_commits_returns_yaml() {
        let _guard = CWD_MUTEX.lock().await;
        let temp_dir = init_tmp_repo();
        let original_cwd = std::env::current_dir().unwrap();
        std::env::set_current_dir(temp_dir.path()).unwrap();

        let uri = ResourceUri::parse("git://repo/commits/HEAD").unwrap();
        let result = read_resource(&uri, "git://repo/commits/HEAD").await;

        std::env::set_current_dir(original_cwd).unwrap();
        let result = result.unwrap();
        let contents = result.contents;
        assert_eq!(contents.len(), 1);
        match &contents[0] {
            ResourceContents::TextResourceContents {
                text,
                mime_type,
                uri: reply_uri,
                ..
            } => {
                assert!(text.contains("commits:"), "yaml missing commits: {text}");
                assert!(text.contains("feat: seed"), "yaml missing subject: {text}");
                assert_eq!(mime_type.as_deref(), Some("application/yaml"));
                assert_eq!(reply_uri, "git://repo/commits/HEAD");
            }
            other @ ResourceContents::BlobResourceContents { .. } => {
                panic!("expected text resource contents, got {other:?}")
            }
        }
    }

    // ── Atlassian branches of read_resource ────────────────────────
    //
    // These tests exercise the JIRA/Confluence branches by pointing
    // `ATLASSIAN_*` env vars at a wiremock server and checking the
    // full handler path. `ENV_MUTEX` serialises env-var access — the
    // stdlib warns that process-env access races across threads, and
    // `create_client` reads these vars internally.

    static ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());

    struct EnvGuard {
        keys: Vec<&'static str>,
    }

    impl EnvGuard {
        fn set(pairs: &[(&'static str, String)]) -> Self {
            let keys = pairs.iter().map(|(k, _)| *k).collect();
            for (k, v) in pairs {
                std::env::set_var(k, v);
            }
            Self { keys }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            for k in &self.keys {
                std::env::remove_var(k);
            }
        }
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test(flavor = "multi_thread")]
    async fn read_resource_jira_issue_jfm_against_wiremock() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/rest/api/3/issue/PROJ-7"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "key": "PROJ-7",
                    "fields": {
                        "summary": "Resource test issue",
                        "description": {
                            "type": "doc",
                            "version": 1,
                            "content": [{
                                "type": "paragraph",
                                "content": [{"type": "text", "text": "resource body"}]
                            }]
                        },
                        "status": {"name": "Open"},
                        "issuetype": {"name": "Task"},
                        "assignee": null,
                        "priority": null,
                        "labels": []
                    }
                })),
            )
            .mount(&server)
            .await;

        let _guard = ENV_MUTEX.lock().unwrap();
        let _env = EnvGuard::set(&[
            ("ATLASSIAN_INSTANCE_URL", server.uri()),
            ("ATLASSIAN_EMAIL", "test@example.com".to_string()),
            ("ATLASSIAN_API_TOKEN", "fake-token".to_string()),
        ]);

        let uri = ResourceUri::parse("jira://issue/PROJ-7").unwrap();
        let result = read_resource(&uri, "jira://issue/PROJ-7").await.unwrap();
        assert_eq!(result.contents.len(), 1);
        match &result.contents[0] {
            ResourceContents::TextResourceContents {
                text,
                mime_type,
                uri: reply_uri,
                ..
            } => {
                assert!(text.contains("PROJ-7"), "missing key: {text}");
                assert!(text.contains("resource body"), "missing body: {text}");
                assert_eq!(mime_type.as_deref(), Some("text/markdown"));
                assert_eq!(reply_uri, "jira://issue/PROJ-7");
            }
            other @ ResourceContents::BlobResourceContents { .. } => {
                panic!("expected text, got {other:?}")
            }
        }
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test(flavor = "multi_thread")]
    async fn read_resource_jira_issue_adf_returns_json() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/rest/api/3/issue/PROJ-8"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "key": "PROJ-8",
                    "fields": {
                        "summary": "ADF payload issue",
                        "description": {
                            "type": "doc",
                            "version": 1,
                            "content": []
                        },
                        "status": {"name": "Open"},
                        "issuetype": {"name": "Bug"},
                        "assignee": null,
                        "priority": null,
                        "labels": []
                    }
                })),
            )
            .mount(&server)
            .await;

        let _guard = ENV_MUTEX.lock().unwrap();
        let _env = EnvGuard::set(&[
            ("ATLASSIAN_INSTANCE_URL", server.uri()),
            ("ATLASSIAN_EMAIL", "test@example.com".to_string()),
            ("ATLASSIAN_API_TOKEN", "fake-token".to_string()),
        ]);

        let uri = ResourceUri::parse("jira://issue/PROJ-8.adf").unwrap();
        let result = read_resource(&uri, "jira://issue/PROJ-8.adf")
            .await
            .unwrap();
        match &result.contents[0] {
            ResourceContents::TextResourceContents {
                text, mime_type, ..
            } => {
                assert_eq!(mime_type.as_deref(), Some("application/json"));
                let parsed: serde_json::Value = serde_json::from_str(text).unwrap();
                assert_eq!(parsed["type"], "doc");
            }
            other @ ResourceContents::BlobResourceContents { .. } => {
                panic!("expected text, got {other:?}")
            }
        }
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test(flavor = "multi_thread")]
    async fn read_resource_jira_propagates_server_errors() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/rest/api/3/issue/NOPE-1"))
            .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("not found"))
            .mount(&server)
            .await;

        let _guard = ENV_MUTEX.lock().unwrap();
        let _env = EnvGuard::set(&[
            ("ATLASSIAN_INSTANCE_URL", server.uri()),
            ("ATLASSIAN_EMAIL", "test@example.com".to_string()),
            ("ATLASSIAN_API_TOKEN", "fake-token".to_string()),
        ]);

        let uri = ResourceUri::parse("jira://issue/NOPE-1").unwrap();
        let err = read_resource(&uri, "jira://issue/NOPE-1")
            .await
            .expect_err("404 should surface as error");
        let chain = format!("{err:#}");
        assert!(
            chain.contains("NOPE-1") || chain.contains("404"),
            "unexpected chain: {chain}"
        );
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test(flavor = "multi_thread")]
    async fn read_resource_confluence_page_jfm_against_wiremock() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/99999"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "99999",
                    "title": "Resource page",
                    "status": "current",
                    "version": {"number": 3},
                    "spaceId": "10",
                    "parentId": null,
                    "body": {
                        "atlas_doc_format": {
                            "representation": "atlas_doc_format",
                            "value": serde_json::json!({
                                "type": "doc",
                                "version": 1,
                                "content": [{
                                    "type": "paragraph",
                                    "content": [{"type": "text", "text": "page content"}]
                                }]
                            }).to_string()
                        }
                    }
                })),
            )
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/spaces/10"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "10",
                    "key": "ENG",
                    "name": "Engineering"
                })),
            )
            .mount(&server)
            .await;

        let _guard = ENV_MUTEX.lock().unwrap();
        let _env = EnvGuard::set(&[
            ("ATLASSIAN_INSTANCE_URL", server.uri()),
            ("ATLASSIAN_EMAIL", "test@example.com".to_string()),
            ("ATLASSIAN_API_TOKEN", "fake-token".to_string()),
        ]);

        let uri = ResourceUri::parse("confluence://page/99999").unwrap();
        let result = read_resource(&uri, "confluence://page/99999").await;
        // We don't pin the exact rendered output (depends on internal ADF
        // rendering details), only that the branch ran and produced
        // TextResourceContents with the markdown MIME type.
        match result {
            Ok(res) => match &res.contents[0] {
                ResourceContents::TextResourceContents { mime_type, .. } => {
                    assert_eq!(mime_type.as_deref(), Some("text/markdown"));
                }
                other @ ResourceContents::BlobResourceContents { .. } => {
                    panic!("expected text, got {other:?}")
                }
            },
            // Some Confluence client paths require additional endpoints we
            // haven't mocked. The goal here is branch coverage of
            // `ResourceUri::ConfluencePage`, which runs either way — accept
            // an error too, just assert the URI appears in the chain.
            Err(e) => {
                let chain = format!("{e:#}");
                assert!(
                    chain.contains("99999") || chain.contains("Confluence"),
                    "unexpected error chain: {chain}"
                );
            }
        }
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test(flavor = "multi_thread")]
    async fn read_resource_confluence_propagates_server_errors() {
        let server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/wiki/api/v2/pages/404404"))
            .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("not found"))
            .mount(&server)
            .await;

        let _guard = ENV_MUTEX.lock().unwrap();
        let _env = EnvGuard::set(&[
            ("ATLASSIAN_INSTANCE_URL", server.uri()),
            ("ATLASSIAN_EMAIL", "test@example.com".to_string()),
            ("ATLASSIAN_API_TOKEN", "fake-token".to_string()),
        ]);

        let uri = ResourceUri::parse("confluence://page/404404").unwrap();
        let err = read_resource(&uri, "confluence://page/404404")
            .await
            .expect_err("404 should surface as error");
        let chain = format!("{err:#}");
        assert!(
            chain.contains("404404") || chain.contains("404") || chain.contains("Confluence"),
            "unexpected chain: {chain}"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn read_resource_jira_without_credentials_errors() {
        // No ATLASSIAN_* env vars set → create_client() fails in the JIRA
        // branch of read_resource, exercising the "Failed to load Atlassian
        // credentials" context wrap.
        let _guard = ENV_MUTEX.lock().unwrap();
        // Scrub any stray vars the surrounding process may have set so
        // create_client() definitively fails.
        for key in [
            "ATLASSIAN_INSTANCE_URL",
            "ATLASSIAN_EMAIL",
            "ATLASSIAN_API_TOKEN",
            "JIRA_INSTANCE_URL",
            "JIRA_EMAIL",
            "JIRA_API_TOKEN",
        ] {
            std::env::remove_var(key);
        }
        std::env::set_var("HOME", std::env::temp_dir());

        let uri = ResourceUri::parse("jira://issue/ZZZ-1").unwrap();
        let err = read_resource(&uri, "jira://issue/ZZZ-1")
            .await
            .expect_err("missing credentials must error");
        let chain = format!("{err:#}");
        assert!(
            chain.contains("Atlassian") || chain.contains("credential"),
            "unexpected chain: {chain}"
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn read_resource_confluence_without_credentials_errors() {
        let _guard = ENV_MUTEX.lock().unwrap();
        for key in [
            "ATLASSIAN_INSTANCE_URL",
            "ATLASSIAN_EMAIL",
            "ATLASSIAN_API_TOKEN",
            "JIRA_INSTANCE_URL",
            "JIRA_EMAIL",
            "JIRA_API_TOKEN",
        ] {
            std::env::remove_var(key);
        }
        std::env::set_var("HOME", std::env::temp_dir());

        let uri = ResourceUri::parse("confluence://page/0").unwrap();
        let err = read_resource(&uri, "confluence://page/0")
            .await
            .expect_err("missing credentials must error");
        let chain = format!("{err:#}");
        assert!(
            chain.contains("Atlassian") || chain.contains("credential"),
            "unexpected chain: {chain}"
        );
    }

    #[test]
    fn render_content_item_jfm_for_confluence_page() {
        use crate::atlassian::api::ContentMetadata;
        let body = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": "conf body"}]}]
        });
        let item = ContentItem {
            id: "12345".to_string(),
            title: "Test Page".to_string(),
            body_adf: Some(body),
            metadata: ContentMetadata::Confluence {
                space_key: "ENG".to_string(),
                status: Some("current".to_string()),
                version: Some(1),
                parent_id: None,
            },
        };
        let (text, mime) =
            render_content_item(&item, "https://org.atlassian.net", ResourceFormat::Jfm).unwrap();
        assert_eq!(mime, "text/markdown");
        assert!(text.contains("conf body"), "missing body: {text}");
    }

    #[test]
    fn uri_parse_error_variants_display_expected_messages() {
        let malformed = UriParseError::Malformed("git://x".to_string(), "oops");
        assert!(malformed.to_string().contains("oops"));
        let empty = UriParseError::EmptyIdentifier("jira://issue/".to_string());
        assert!(empty.to_string().contains("empty identifier"));
    }

    #[test]
    fn resource_uri_debug_and_clone() {
        let uri = ResourceUri::JiraIssue {
            key: "X-1".to_string(),
            format: ResourceFormat::Jfm,
        };
        let dup = uri.clone();
        assert_eq!(uri, dup);
        assert!(format!("{uri:?}").contains("JiraIssue"));
    }

    #[test]
    fn resource_format_copy_and_eq() {
        let a = ResourceFormat::Adf;
        let b = a;
        assert_eq!(a, b);
        assert_ne!(a, ResourceFormat::Jfm);
    }
}