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
//! Shared format types for Atlassian CLI commands.

use std::io::Write;

use anyhow::{Context, Result};
use clap::ValueEnum;
use serde::Serialize;

use crate::atlassian::client::{
    AgileBoardList, AgileSprintList, ConfluenceSearchResults, ConfluenceUserSearchResults,
    JiraDevStatus, JiraDevStatusSummary, JiraProjectList, JiraSearchResult, JiraWatcherList,
    JiraWorklogList,
};

/// Output/input format for Atlassian content (read/write/create commands).
#[derive(Clone, Debug, Default, ValueEnum)]
pub enum ContentFormat {
    /// JFM markdown with YAML frontmatter.
    #[default]
    Jfm,
    /// Raw Atlassian Document Format JSON.
    Adf,
}

/// Display format for list/table commands.
#[derive(Clone, Debug, Default, ValueEnum)]
pub enum OutputFormat {
    /// Human-readable table.
    #[default]
    Table,
    /// JSON.
    Json,
    /// YAML (single document).
    Yaml,
    /// YAML stream (`---`-separated multi-document).
    Yamls,
    /// JSON Lines: one compact JSON object per line, streaming-friendly.
    Jsonl,
}

/// Writes a value as newline-terminated JSON Lines.
///
/// For collection-like types, implementations emit one JSON object per
/// contained item. For scalar types, implementations emit the value as a
/// single JSON line.
pub trait JsonlSerialize {
    /// Writes the value as JSONL to `out`, newline-terminated.
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()>;
}

/// Writes each item in an iterator as a single compact JSON line.
pub fn write_items_jsonl<'a, I, T>(items: I, out: &mut dyn Write) -> Result<()>
where
    I: IntoIterator<Item = &'a T>,
    T: Serialize + 'a,
{
    for item in items {
        let line = serde_json::to_string(item).context("Failed to serialize as JSON")?;
        writeln!(out, "{line}").context("Failed to write JSONL line")?;
    }
    Ok(())
}

/// Writes a single serializable value as one compact JSON line.
pub fn write_scalar_jsonl<T: Serialize>(item: &T, out: &mut dyn Write) -> Result<()> {
    let line = serde_json::to_string(item).context("Failed to serialize as JSON")?;
    writeln!(out, "{line}").context("Failed to write JSONL line")?;
    Ok(())
}

impl<T: Serialize> JsonlSerialize for Vec<T> {
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()> {
        write_items_jsonl(self.iter(), out)
    }
}

impl JsonlSerialize for AgileBoardList {
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()> {
        write_items_jsonl(self.boards.iter(), out)
    }
}

impl JsonlSerialize for AgileSprintList {
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()> {
        write_items_jsonl(self.sprints.iter(), out)
    }
}

impl JsonlSerialize for JiraSearchResult {
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()> {
        write_items_jsonl(self.issues.iter(), out)
    }
}

impl JsonlSerialize for JiraProjectList {
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()> {
        write_items_jsonl(self.projects.iter(), out)
    }
}

impl JsonlSerialize for JiraWatcherList {
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()> {
        write_items_jsonl(self.watchers.iter(), out)
    }
}

impl JsonlSerialize for JiraWorklogList {
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()> {
        write_items_jsonl(self.worklogs.iter(), out)
    }
}

impl JsonlSerialize for ConfluenceSearchResults {
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()> {
        write_items_jsonl(self.results.iter(), out)
    }
}

impl JsonlSerialize for ConfluenceUserSearchResults {
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()> {
        write_items_jsonl(self.users.iter(), out)
    }
}

impl JsonlSerialize for JiraDevStatus {
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()> {
        write_scalar_jsonl(self, out)
    }
}

impl JsonlSerialize for JiraDevStatusSummary {
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()> {
        write_scalar_jsonl(self, out)
    }
}

/// Writes `data` to `out` in the requested format.
///
/// Returns `Ok(true)` when `data` was written (json/yaml/yamls/jsonl), `Ok(false)`
/// when `format` is `Table` (the caller is expected to render its own table).
pub fn write_output<T: Serialize + JsonlSerialize>(
    data: &T,
    format: &OutputFormat,
    out: &mut dyn Write,
) -> Result<bool> {
    match format {
        OutputFormat::Table => Ok(false),
        OutputFormat::Json => {
            let rendered =
                serde_json::to_string_pretty(data).context("Failed to serialize as JSON")?;
            writeln!(out, "{rendered}").context("Failed to write JSON output")?;
            Ok(true)
        }
        OutputFormat::Yaml => {
            let rendered = serde_yaml::to_string(data).context("Failed to serialize as YAML")?;
            write!(out, "{rendered}").context("Failed to write YAML output")?;
            Ok(true)
        }
        OutputFormat::Yamls => {
            let rendered = format_yaml_stream(data)?;
            write!(out, "{rendered}").context("Failed to write YAML stream output")?;
            Ok(true)
        }
        OutputFormat::Jsonl => {
            data.write_jsonl(out)?;
            Ok(true)
        }
    }
}

/// Serializes a single YAML value as one `---`-prefixed document.
fn yaml_stream_doc(value: &serde_yaml::Value) -> Result<String> {
    let s = serde_yaml::to_string(value).context("Failed to serialize YAML stream item")?;
    Ok(format!("---\n{s}"))
}

/// Serializes data as a YAML multi-document stream.
///
/// If the serialized value is a sequence, each element is emitted as its own
/// `---`-prefixed YAML document. Otherwise the whole value is emitted as a
/// single `---`-prefixed document. The result always ends with a newline.
fn format_yaml_stream<T: Serialize>(data: &T) -> Result<String> {
    match serde_yaml::to_value(data).context("Failed to serialize as YAML stream")? {
        serde_yaml::Value::Sequence(items) => items.iter().map(yaml_stream_doc).collect(),
        other => yaml_stream_doc(&other),
    }
}

/// Serializes data in the requested output format to stdout.
/// Returns `Ok(true)` if data was printed (json/yaml/yamls/jsonl), `Ok(false)`
/// if the caller should handle table output.
pub fn output_as<T: Serialize + JsonlSerialize>(data: &T, format: &OutputFormat) -> Result<bool> {
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();
    write_output(data, format, &mut handle)
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::atlassian::client::{
        AgileBoard, AgileSprint, ConfluenceSearchResult, ConfluenceUserSearchResult, JiraComment,
        JiraDevStatusCount, JiraIssue, JiraProject, JiraUser, JiraWorklog,
    };

    // ── ContentFormat ──────────────────────────────────────────────

    #[test]
    fn default_is_jfm() {
        let format = ContentFormat::default();
        assert!(matches!(format, ContentFormat::Jfm));
    }

    #[test]
    fn jfm_variant() {
        let format = ContentFormat::Jfm;
        assert!(matches!(format, ContentFormat::Jfm));
    }

    #[test]
    fn adf_variant() {
        let format = ContentFormat::Adf;
        assert!(matches!(format, ContentFormat::Adf));
    }

    #[test]
    fn debug_format() {
        assert_eq!(format!("{:?}", ContentFormat::Jfm), "Jfm");
        assert_eq!(format!("{:?}", ContentFormat::Adf), "Adf");
    }

    #[test]
    fn clone() {
        let format = ContentFormat::Adf;
        let cloned = format.clone();
        assert!(matches!(cloned, ContentFormat::Adf));
    }

    // ── OutputFormat ───────────────────────────────────────────────

    #[test]
    fn output_default_is_table() {
        assert!(matches!(OutputFormat::default(), OutputFormat::Table));
    }

    #[test]
    fn output_json_variant() {
        assert!(matches!(OutputFormat::Json, OutputFormat::Json));
    }

    #[test]
    fn output_yaml_variant() {
        assert!(matches!(OutputFormat::Yaml, OutputFormat::Yaml));
    }

    #[test]
    fn output_yamls_variant() {
        assert!(matches!(OutputFormat::Yamls, OutputFormat::Yamls));
    }

    #[test]
    fn output_jsonl_variant() {
        assert!(matches!(OutputFormat::Jsonl, OutputFormat::Jsonl));
    }

    #[test]
    fn output_debug_format() {
        assert_eq!(format!("{:?}", OutputFormat::Jsonl), "Jsonl");
    }

    #[test]
    fn output_clone() {
        let format = OutputFormat::Jsonl;
        let cloned = format.clone();
        assert!(matches!(cloned, OutputFormat::Jsonl));
    }

    // ── output_as ──────────────────────────────────────────────────

    #[test]
    fn output_as_table_returns_false() {
        let data = vec![1, 2, 3];
        assert!(!output_as(&data, &OutputFormat::Table).unwrap());
    }

    #[test]
    fn output_as_json_returns_true() {
        let data = vec![1, 2, 3];
        assert!(output_as(&data, &OutputFormat::Json).unwrap());
    }

    #[test]
    fn output_as_yaml_returns_true() {
        let data = vec![1, 2, 3];
        assert!(output_as(&data, &OutputFormat::Yaml).unwrap());
    }

    #[test]
    fn output_as_yamls_returns_true() {
        let data = vec![1, 2, 3];
        assert!(output_as(&data, &OutputFormat::Yamls).unwrap());
    }

    #[test]
    fn output_as_jsonl_returns_true() {
        let data = vec![1, 2, 3];
        assert!(output_as(&data, &OutputFormat::Jsonl).unwrap());
    }

    // ── write_items_jsonl / Vec impl ───────────────────────────────

    #[test]
    fn vec_jsonl_empty_emits_nothing() {
        let data: Vec<i32> = vec![];
        let mut buf = Vec::new();
        data.write_jsonl(&mut buf).unwrap();
        assert_eq!(buf, b"");
    }

    #[test]
    fn vec_jsonl_emits_one_line_per_item() {
        let data = vec![1_i32, 2, 3];
        let mut buf = Vec::new();
        data.write_jsonl(&mut buf).unwrap();
        assert_eq!(String::from_utf8(buf).unwrap(), "1\n2\n3\n");
    }

    #[test]
    fn vec_jsonl_emits_compact_objects() {
        #[derive(Serialize)]
        struct Item {
            key: &'static str,
            val: u32,
        }
        let data = vec![Item { key: "a", val: 1 }, Item { key: "b", val: 2 }];
        let mut buf = Vec::new();
        data.write_jsonl(&mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert_eq!(
            out,
            "{\"key\":\"a\",\"val\":1}\n{\"key\":\"b\",\"val\":2}\n"
        );
    }

    #[test]
    fn vec_of_refs_jsonl() {
        let comment = sample_comment("c1", "hello");
        let comments = vec![&comment];
        let mut buf = Vec::new();
        comments.write_jsonl(&mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.starts_with('{'));
        assert!(out.ends_with('\n'));
        assert_eq!(out.lines().count(), 1);
    }

    #[test]
    fn write_items_jsonl_over_slice() {
        let data = [10_i32, 20];
        let mut buf = Vec::new();
        write_items_jsonl(data.iter(), &mut buf).unwrap();
        assert_eq!(String::from_utf8(buf).unwrap(), "10\n20\n");
    }

    #[test]
    fn write_scalar_jsonl_emits_one_line() {
        #[derive(Serialize)]
        struct Scalar {
            name: &'static str,
        }
        let item = Scalar { name: "solo" };
        let mut buf = Vec::new();
        write_scalar_jsonl(&item, &mut buf).unwrap();
        assert_eq!(String::from_utf8(buf).unwrap(), "{\"name\":\"solo\"}\n");
    }

    // ── sample data helpers ────────────────────────────────────────

    fn sample_board(id: u64, name: &str) -> AgileBoard {
        AgileBoard {
            id,
            name: name.to_string(),
            board_type: "scrum".to_string(),
            project_key: None,
        }
    }

    fn sample_sprint(id: u64, name: &str) -> AgileSprint {
        AgileSprint {
            id,
            name: name.to_string(),
            state: "active".to_string(),
            goal: None,
            start_date: None,
            end_date: None,
        }
    }

    fn sample_issue(key: &str) -> JiraIssue {
        JiraIssue {
            key: key.to_string(),
            summary: "s".to_string(),
            description_adf: None,
            status: None,
            issue_type: None,
            assignee: None,
            priority: None,
            labels: vec![],
            custom_fields: vec![],
        }
    }

    fn sample_project(key: &str) -> JiraProject {
        JiraProject {
            key: key.to_string(),
            id: "1".to_string(),
            name: "Project".to_string(),
            project_type: None,
            lead: None,
        }
    }

    fn sample_user(name: &str) -> JiraUser {
        JiraUser {
            account_id: name.to_string(),
            display_name: name.to_string(),
            email_address: None,
        }
    }

    fn sample_worklog(id: &str) -> JiraWorklog {
        JiraWorklog {
            id: id.to_string(),
            author: "alice".to_string(),
            time_spent: "1h".to_string(),
            time_spent_seconds: 3600,
            started: "2025-01-01T00:00:00Z".to_string(),
            comment: None,
        }
    }

    fn sample_confluence_result(id: &str) -> ConfluenceSearchResult {
        ConfluenceSearchResult {
            id: id.to_string(),
            title: "Title".to_string(),
            space_key: "ENG".to_string(),
        }
    }

    fn sample_confluence_user(id: &str) -> ConfluenceUserSearchResult {
        ConfluenceUserSearchResult {
            account_id: Some(id.to_string()),
            display_name: "Name".to_string(),
            email: None,
        }
    }

    fn sample_comment(id: &str, _body: &str) -> JiraComment {
        JiraComment {
            id: id.to_string(),
            author: "alice".to_string(),
            created: "2025-01-01T00:00:00Z".to_string(),
            body_adf: None,
        }
    }

    // ── wrapper type JsonlSerialize impls ──────────────────────────

    fn jsonl_string<T: JsonlSerialize>(value: &T) -> String {
        let mut buf = Vec::new();
        value.write_jsonl(&mut buf).unwrap();
        String::from_utf8(buf).unwrap()
    }

    #[test]
    fn agile_board_list_jsonl() {
        let list = AgileBoardList {
            boards: vec![sample_board(1, "B1"), sample_board(2, "B2")],
            total: 2,
        };
        let out = jsonl_string(&list);
        assert_eq!(out.lines().count(), 2);
        assert!(out.contains("\"id\":1"));
        assert!(out.contains("\"id\":2"));
    }

    #[test]
    fn agile_board_list_jsonl_empty() {
        let list = AgileBoardList {
            boards: vec![],
            total: 0,
        };
        assert_eq!(jsonl_string(&list), "");
    }

    #[test]
    fn agile_sprint_list_jsonl() {
        let list = AgileSprintList {
            sprints: vec![sample_sprint(1, "Sprint 1")],
            total: 1,
        };
        let out = jsonl_string(&list);
        assert_eq!(out.lines().count(), 1);
        assert!(out.contains("\"id\":1"));
    }

    #[test]
    fn jira_search_result_jsonl() {
        let result = JiraSearchResult {
            issues: vec![sample_issue("A-1"), sample_issue("A-2")],
            total: 2,
        };
        let out = jsonl_string(&result);
        assert_eq!(out.lines().count(), 2);
        assert!(out.contains("\"key\":\"A-1\""));
        assert!(out.contains("\"key\":\"A-2\""));
    }

    #[test]
    fn jira_project_list_jsonl() {
        let list = JiraProjectList {
            projects: vec![sample_project("P")],
            total: 1,
        };
        let out = jsonl_string(&list);
        assert_eq!(out.lines().count(), 1);
        assert!(out.contains("\"key\":\"P\""));
    }

    #[test]
    fn jira_watcher_list_jsonl() {
        let list = JiraWatcherList {
            watchers: vec![sample_user("alice"), sample_user("bob")],
            watch_count: 2,
        };
        let out = jsonl_string(&list);
        assert_eq!(out.lines().count(), 2);
    }

    #[test]
    fn jira_worklog_list_jsonl() {
        let list = JiraWorklogList {
            worklogs: vec![sample_worklog("w1")],
            total: 1,
        };
        let out = jsonl_string(&list);
        assert_eq!(out.lines().count(), 1);
        assert!(out.contains("\"id\":\"w1\""));
    }

    #[test]
    fn confluence_search_results_jsonl() {
        let list = ConfluenceSearchResults {
            results: vec![sample_confluence_result("r1")],
            total: 1,
        };
        let out = jsonl_string(&list);
        assert_eq!(out.lines().count(), 1);
        assert!(out.contains("\"id\":\"r1\""));
    }

    #[test]
    fn confluence_user_search_results_jsonl() {
        let list = ConfluenceUserSearchResults {
            users: vec![sample_confluence_user("u1")],
            total: 1,
        };
        let out = jsonl_string(&list);
        assert_eq!(out.lines().count(), 1);
        assert!(out.contains("\"accountId\":\"u1\"") || out.contains("\"account_id\":\"u1\""));
    }

    #[test]
    fn jira_dev_status_jsonl_single_line() {
        let status = JiraDevStatus {
            pull_requests: vec![],
            branches: vec![],
            repositories: vec![],
        };
        let out = jsonl_string(&status);
        assert_eq!(out.lines().count(), 1);
    }

    #[test]
    fn jira_dev_status_summary_jsonl_single_line() {
        let summary = JiraDevStatusSummary {
            pullrequest: JiraDevStatusCount {
                count: 0,
                providers: vec![],
            },
            branch: JiraDevStatusCount {
                count: 0,
                providers: vec![],
            },
            repository: JiraDevStatusCount {
                count: 0,
                providers: vec![],
            },
        };
        let out = jsonl_string(&summary);
        assert_eq!(out.lines().count(), 1);
    }

    // ── output_as jsonl round-trip ─────────────────────────────────

    #[test]
    fn output_as_jsonl_empty_vec_returns_true() {
        let data: Vec<i32> = vec![];
        assert!(output_as(&data, &OutputFormat::Jsonl).unwrap());
    }

    #[test]
    fn output_as_jsonl_wrapper_returns_true() {
        let list = AgileBoardList {
            boards: vec![sample_board(1, "b")],
            total: 1,
        };
        assert!(output_as(&list, &OutputFormat::Jsonl).unwrap());
    }

    // ── format_yaml_stream ─────────────────────────────────────────

    #[derive(serde::Serialize)]
    struct Issue {
        key: &'static str,
        summary: &'static str,
    }

    #[test]
    fn yaml_stream_emits_one_doc_per_sequence_item() {
        let data = vec![
            Issue {
                key: "PROJ-1",
                summary: "Fix login",
            },
            Issue {
                key: "PROJ-2",
                summary: "Add feature",
            },
        ];
        let out = format_yaml_stream(&data).unwrap();
        assert_eq!(
            out,
            "---\nkey: PROJ-1\nsummary: Fix login\n---\nkey: PROJ-2\nsummary: Add feature\n"
        );
    }

    #[test]
    fn yaml_stream_empty_sequence_emits_nothing() {
        let data: Vec<Issue> = vec![];
        let out = format_yaml_stream(&data).unwrap();
        assert_eq!(out, "");
    }

    #[test]
    fn yaml_stream_single_item_sequence() {
        let data = vec![Issue {
            key: "PROJ-1",
            summary: "Fix login",
        }];
        let out = format_yaml_stream(&data).unwrap();
        assert_eq!(out, "---\nkey: PROJ-1\nsummary: Fix login\n");
    }

    #[test]
    fn yaml_stream_non_sequence_emits_single_doc() {
        let data = Issue {
            key: "PROJ-1",
            summary: "Fix login",
        };
        let out = format_yaml_stream(&data).unwrap();
        assert_eq!(out, "---\nkey: PROJ-1\nsummary: Fix login\n");
    }

    #[test]
    fn yaml_stream_scalar_emits_single_doc() {
        let data: i32 = 42;
        let out = format_yaml_stream(&data).unwrap();
        assert_eq!(out, "---\n42\n");
    }

    #[test]
    fn yaml_stream_nested_sequences_treat_outer_only() {
        let data = vec![vec![1, 2], vec![3, 4]];
        let out = format_yaml_stream(&data).unwrap();
        assert_eq!(out, "---\n- 1\n- 2\n---\n- 3\n- 4\n");
    }

    #[test]
    fn yaml_stream_round_trips_via_safe_load_all() {
        use serde::Deserialize;

        let data = vec![
            Issue {
                key: "PROJ-1",
                summary: "Fix login",
            },
            Issue {
                key: "PROJ-2",
                summary: "Add feature",
            },
        ];
        let out = format_yaml_stream(&data).unwrap();

        let docs: Vec<serde_yaml::Value> = serde_yaml::Deserializer::from_str(&out)
            .map(serde_yaml::Value::deserialize)
            .collect::<Result<_, _>>()
            .unwrap();

        assert_eq!(docs.len(), 2);
        assert_eq!(docs[0]["key"], serde_yaml::Value::from("PROJ-1"));
        assert_eq!(docs[1]["key"], serde_yaml::Value::from("PROJ-2"));
    }

    // ── write_output ───────────────────────────────────────────────

    #[test]
    fn write_output_table_returns_false_and_writes_nothing() {
        let data = vec![1_i32, 2];
        let mut buf = Vec::new();
        let wrote = write_output(&data, &OutputFormat::Table, &mut buf).unwrap();
        assert!(!wrote);
        assert!(buf.is_empty());
    }

    #[test]
    fn write_output_json_emits_pretty_array() {
        let data = vec![1_i32, 2, 3];
        let mut buf = Vec::new();
        let wrote = write_output(&data, &OutputFormat::Json, &mut buf).unwrap();
        assert!(wrote);
        let out = String::from_utf8(buf).unwrap();
        assert!(out.starts_with('['));
        assert!(out.contains("  1,\n"));
        assert!(out.ends_with("]\n"));
    }

    #[test]
    fn write_output_yaml_emits_list() {
        let data = vec![1_i32, 2];
        let mut buf = Vec::new();
        let wrote = write_output(&data, &OutputFormat::Yaml, &mut buf).unwrap();
        assert!(wrote);
        let out = String::from_utf8(buf).unwrap();
        assert_eq!(out, "- 1\n- 2\n");
    }

    #[test]
    fn write_output_yamls_emits_yaml_stream() {
        let data = vec![1_i32, 2];
        let mut buf = Vec::new();
        let wrote = write_output(&data, &OutputFormat::Yamls, &mut buf).unwrap();
        assert!(wrote);
        let out = String::from_utf8(buf).unwrap();
        assert_eq!(out, "---\n1\n---\n2\n");
    }

    #[test]
    fn write_output_jsonl_emits_one_line_per_item() {
        let data = vec![1_i32, 2, 3];
        let mut buf = Vec::new();
        let wrote = write_output(&data, &OutputFormat::Jsonl, &mut buf).unwrap();
        assert!(wrote);
        assert_eq!(String::from_utf8(buf).unwrap(), "1\n2\n3\n");
    }

    #[test]
    fn write_output_jsonl_wrapper() {
        let list = AgileBoardList {
            boards: vec![sample_board(1, "b1"), sample_board(2, "b2")],
            total: 2,
        };
        let mut buf = Vec::new();
        let wrote = write_output(&list, &OutputFormat::Jsonl, &mut buf).unwrap();
        assert!(wrote);
        let out = String::from_utf8(buf).unwrap();
        assert_eq!(out.lines().count(), 2);
        assert!(out.contains("\"id\":1"));
        assert!(out.contains("\"id\":2"));
    }

    #[test]
    fn write_output_json_wrapper_includes_total_field() {
        let list = AgileBoardList {
            boards: vec![sample_board(1, "b1")],
            total: 42,
        };
        let mut buf = Vec::new();
        write_output(&list, &OutputFormat::Json, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.contains("\"total\": 42"));
    }

    #[test]
    fn write_output_yaml_wrapper_includes_total_field() {
        let list = AgileBoardList {
            boards: vec![],
            total: 0,
        };
        let mut buf = Vec::new();
        write_output(&list, &OutputFormat::Yaml, &mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert!(out.contains("total: 0"));
    }

    struct FailingWriter;

    impl Write for FailingWriter {
        fn write(&mut self, _buf: &[u8]) -> std::io::Result<usize> {
            Err(std::io::Error::other("boom"))
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Err(std::io::Error::other("boom"))
        }
    }

    #[test]
    fn write_output_propagates_write_errors() {
        let data = vec![1_i32];
        let mut writer = FailingWriter;

        assert!(write_output(&data, &OutputFormat::Json, &mut writer).is_err());
        assert!(write_output(&data, &OutputFormat::Yaml, &mut writer).is_err());
        assert!(write_output(&data, &OutputFormat::Yamls, &mut writer).is_err());
        assert!(write_output(&data, &OutputFormat::Jsonl, &mut writer).is_err());
        assert!(writer.write(b"x").is_err());
        assert!(writer.flush().is_err());
    }

    #[test]
    fn write_scalar_jsonl_propagates_write_errors() {
        let status = JiraDevStatus {
            pull_requests: vec![],
            branches: vec![],
            repositories: vec![],
        };
        let mut writer = FailingWriter;
        assert!(write_output(&status, &OutputFormat::Jsonl, &mut writer).is_err());
    }

    struct FailingSerialize;

    impl Serialize for FailingSerialize {
        fn serialize<S>(&self, _serializer: S) -> std::result::Result<S::Ok, S::Error>
        where
            S: serde::Serializer,
        {
            Err(serde::ser::Error::custom("serialize failed"))
        }
    }

    impl JsonlSerialize for FailingSerialize {
        fn write_jsonl(&self, _out: &mut dyn Write) -> Result<()> {
            Ok(())
        }
    }

    #[test]
    fn write_output_propagates_json_serialize_errors() {
        let mut buf = Vec::new();
        let err = write_output(&FailingSerialize, &OutputFormat::Json, &mut buf).unwrap_err();
        assert!(err.to_string().contains("Failed to serialize as JSON"));
    }

    #[test]
    fn write_output_propagates_yaml_serialize_errors() {
        let mut buf = Vec::new();
        let err = write_output(&FailingSerialize, &OutputFormat::Yaml, &mut buf).unwrap_err();
        assert!(err.to_string().contains("Failed to serialize as YAML"));
    }

    #[test]
    fn failing_serialize_jsonl_impl_is_a_noop() {
        let mut buf = Vec::new();
        FailingSerialize.write_jsonl(&mut buf).unwrap();
        assert!(buf.is_empty());
    }
}