teamctl 0.8.0

Declarative CLI for running persistent AI agent teams.
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
//! Release-body fetch, parse, and render for `teamctl update`'s
//! post-success "what's new" display and the `teamctl whatsnew`
//! subcommand. The GitHub release body is the source of truth for the
//! user-facing voice piece; this module turns its markdown into a
//! framed terminal block.
//!
//! Two display modes share the parser + renderer:
//!
//! - **Single-version** — `teamctl whatsnew [version]` or a post-update
//!   call where there's only one body to show. Frame: `✨ What's new
//!   in v<X.Y.Z>`.
//! - **Aggregate / range** — `teamctl whatsnew --since X` or a
//!   post-update call that crossed multiple versions. Frame: `✨
//!   What's new in v<from> → v<to>`. Each version's body rendered
//!   below its own `v<X.Y.Z>` subheader, oldest-first.
//!
//! Floor: pre-`FLOOR_VERSION` releases (cargo-dist auto-generated
//! noise) are silently excluded from aggregates. Operator can still
//! ask for them by name with `teamctl whatsnew <ver>`, but the raw
//! fallback kicks in since their markdown shape isn't the convention.

use std::process::Command;

use anyhow::{anyhow, bail, Context, Result};
use serde::Deserialize;
use serde_json::Value;

use crate::cmd::update::{compare_versions, VersionOrder, CURRENT_VERSION};

const RELEASES_TAG_API: &str = "https://api.github.com/repos/Alireza29675/teamctl/releases/tags/";
const RELEASES_LIST_API: &str = "https://api.github.com/repos/Alireza29675/teamctl/releases";

/// First version with curated release-body convention. Anything below
/// this is cargo-dist auto-generated and silently excluded from
/// aggregate displays.
const FLOOR_VERSION: &str = "0.8.0";

/// Public changelog URL referenced in the footer of every rendered
/// "what's new" block. Lives at the Astro Starlight site (ships in
/// #169 / T-169 alongside this PR).
const CHANGELOG_URL: &str = "https://teamctl.run/changelog";

/// ANSI escape opening italic + dim. Pairs with [`STYLE_RESET`].
const STYLE_DIM_ITALIC: &str = "\x1b[2;3m";
const STYLE_RESET: &str = "\x1b[0m";

#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Entry {
    pub headline: String,
    pub description: String,
}

/// One release as returned by the GitHub /releases list endpoint —
/// just the two fields the renderer needs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ReleaseEntry {
    pub version: String,
    pub body: String,
}

/// Fetch the GitHub release-body markdown for a tagged version. The
/// tag is the v-prefixed shape (`v0.8.0`); callers pass either form.
pub fn fetch_release_body(version: &str) -> Result<String> {
    let v = version.trim_start_matches('v');
    let url = format!("{RELEASES_TAG_API}v{v}");
    let raw = curl_get(&url)?;
    extract_body_field(&raw)
        .ok_or_else(|| anyhow!("no `body` field in GitHub releases response for v{v}"))
}

/// Subset of the GitHub releases-API response we actually read. All
/// other fields are ignored on parse. `body` is `Option` to cover both
/// the `"body": null` and the field-missing shapes the API has been
/// observed in.
#[derive(Deserialize)]
struct ReleaseResponse {
    #[serde(default)]
    body: Option<String>,
}

/// Pull the `body` value out of a GitHub releases-API JSON blob.
/// Returns `None` when the field is missing, `null`, or empty — all
/// three mean "no release notes to show." Parse failure (malformed
/// JSON) also resolves to `None`; the caller falls back to the
/// release-link line rather than raising.
fn extract_body_field(json: &str) -> Option<String> {
    let parsed: ReleaseResponse = serde_json::from_str(json).ok()?;
    let body = parsed.body?;
    if body.is_empty() {
        None
    } else {
        Some(body)
    }
}

/// Fetch the list of all GitHub releases (newest-first per the API)
/// and parse the tag + body fields out of each. Used by the aggregate
/// (`--since` and post-update multi-version) display.
pub(crate) fn fetch_releases_list() -> Result<Vec<ReleaseEntry>> {
    let raw = curl_get(RELEASES_LIST_API)?;
    let list = parse_releases_list(&raw);
    if list.is_empty() {
        bail!("no usable releases in GitHub releases response");
    }
    Ok(list)
}

/// Parse the `/releases` JSON array into `(tag, body)` pairs. Returns
/// empty Vec on malformed JSON (tolerant: a parse failure on the list
/// endpoint shouldn't break `teamctl update`'s install path).
fn parse_releases_list(json: &str) -> Vec<ReleaseEntry> {
    let v: Value = match serde_json::from_str(json) {
        Ok(v) => v,
        Err(_) => return Vec::new(),
    };
    let Some(arr) = v.as_array() else {
        return Vec::new();
    };
    arr.iter()
        .filter_map(|item| {
            let tag = item
                .get("tag_name")?
                .as_str()?
                .trim_start_matches('v')
                .to_string();
            if tag.is_empty() {
                return None;
            }
            let body = item
                .get("body")
                .and_then(|b| b.as_str())
                .unwrap_or("")
                .to_string();
            Some(ReleaseEntry { version: tag, body })
        })
        .collect()
}

/// `true` when `version` is below the curated-display floor. Pre-floor
/// bodies are excluded from aggregate displays as cargo-dist noise.
pub(crate) fn is_below_floor(version: &str) -> bool {
    matches!(
        compare_versions(version.trim_start_matches('v'), FLOOR_VERSION),
        VersionOrder::Older
    )
}

/// Select all releases in `(from, to]` that sit at or above the floor.
/// `from` is exclusive (you've already seen it), `to` is inclusive (it's
/// the new version). Returned oldest-first so the operator reads in
/// chronological order.
pub(crate) fn select_range(all: &[ReleaseEntry], from: &str, to: &str) -> Vec<ReleaseEntry> {
    let from = from.trim_start_matches('v');
    let to = to.trim_start_matches('v');
    let mut selected: Vec<ReleaseEntry> = all
        .iter()
        .filter(|r| !is_below_floor(&r.version))
        .filter(|r| matches!(compare_versions(&r.version, from), VersionOrder::Newer))
        .filter(|r| !matches!(compare_versions(&r.version, to), VersionOrder::Newer))
        .cloned()
        .collect();
    selected.sort_by(|a, b| match compare_versions(&a.version, &b.version) {
        VersionOrder::Older => std::cmp::Ordering::Less,
        VersionOrder::Equal => std::cmp::Ordering::Equal,
        VersionOrder::Newer => std::cmp::Ordering::Greater,
    });
    selected
}

/// Parse `# Headline\nDescription` pairs out of a release-body markdown
/// string. Lines starting with exactly `# ` are headlines; lines after
/// a headline (until the next `# ` or EOF) are the description.
///
/// Non-conforming-body detection: returns an empty Vec when the body
/// contains markdown that the curated convention doesn't allow —
/// sub-headings (`## `, `### `, ...) or fenced code blocks (` ``` `).
/// That keeps the cargo-dist auto-generated body shape (which uses
/// `# team-bot 0.7.3` as section labels around install-shell snippets)
/// from being mis-rendered as styled "entries"; the caller falls
/// through to raw display.
pub(crate) fn parse_release_body(body: &str) -> Vec<Entry> {
    if has_non_convention_markdown(body) {
        return Vec::new();
    }
    let mut entries: Vec<Entry> = Vec::new();
    let mut current: Option<(String, Vec<String>)> = None;
    for line in body.lines() {
        if let Some(headline) = line.strip_prefix("# ") {
            if let Some((h, desc)) = current.take() {
                entries.push(Entry {
                    headline: h,
                    description: desc.join("\n").trim().to_string(),
                });
            }
            current = Some((headline.trim().to_string(), Vec::new()));
        } else if let Some((_, desc)) = current.as_mut() {
            desc.push(line.to_string());
        }
    }
    if let Some((h, desc)) = current {
        entries.push(Entry {
            headline: h,
            description: desc.join("\n").trim().to_string(),
        });
    }
    entries
}

/// Detect markdown the curated release-body convention deliberately
/// excludes. Sub-headings (`## ` and deeper) and fenced code blocks
/// (` ``` `) both signal "this is a richer markdown body, not the
/// curated voice piece" — most commonly the cargo-dist auto-generated
/// body. When either is present, the parser short-circuits to "no
/// entries" and the renderer falls through to raw display.
fn has_non_convention_markdown(body: &str) -> bool {
    body.lines()
        .any(|l| l.starts_with("## ") || l.starts_with("```"))
}

/// Render the body of a single release — entries with styled
/// descriptions, or raw fallback. No top frame, no footer. Use
/// [`render`] for the single-version display and [`render_range`] for
/// aggregate.
fn render_body(body: &str) -> String {
    let entries = parse_release_body(body);
    if entries.is_empty() {
        let trimmed = body.trim_end();
        if trimmed.is_empty() {
            return String::new();
        }
        let mut out = String::new();
        out.push_str(trimmed);
        out.push('\n');
        return out;
    }
    let mut out = String::new();
    for (i, e) in entries.iter().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        out.push_str(&e.headline);
        out.push('\n');
        for line in e.description.lines() {
            out.push_str("  ");
            out.push_str(STYLE_DIM_ITALIC);
            out.push_str(line);
            out.push_str(STYLE_RESET);
            out.push('\n');
        }
    }
    out
}

/// Single-version frame line — `✨ What's new in v<X.Y.Z>` followed by
/// a blank line.
fn frame_single(version: &str) -> String {
    let v = version.trim_start_matches('v');
    format!("✨ What's new in v{v}\n\n")
}

/// Aggregate frame line — `✨ What's new in v<from> → v<to>` followed
/// by a blank line. Explicitly shows the range so the operator knows
/// what they're reading.
fn frame_range(from: &str, to: &str) -> String {
    let from = from.trim_start_matches('v');
    let to = to.trim_start_matches('v');
    format!("✨ What's new in v{from} → v{to}\n\n")
}

/// Footer line printed at the bottom of every "what's new" output —
/// links to the full curated changelog.
fn footer_line() -> String {
    format!("📖 Full changelog: {CHANGELOG_URL}")
}

/// Compose the framed single-version "what's new" terminal block.
/// Non-conforming body (no `# ` headings, or contains `##`/code-fence)
/// → raw body after the frame, no styling. Footer link at the bottom.
pub fn render(version: &str, body: &str) -> String {
    let mut out = frame_single(version);
    out.push_str(&render_body(body));
    out.push('\n');
    out.push_str(&footer_line());
    out.push('\n');
    out
}

/// Compose the aggregate "what's new" block — range frame, then each
/// release as a `v<X.Y.Z>` subheader followed by its body, footer at
/// the bottom. Entries should be ordered oldest-first.
pub(crate) fn render_range(from: &str, to: &str, entries: &[ReleaseEntry]) -> String {
    let mut out = frame_range(from, to);
    for (i, e) in entries.iter().enumerate() {
        if i > 0 {
            out.push('\n');
        }
        out.push_str(&format!("v{}\n", e.version.trim_start_matches('v')));
        out.push_str(&render_body(&e.body));
    }
    out.push('\n');
    out.push_str(&footer_line());
    out.push('\n');
    out
}

/// Single-line fallback when the release-body fetch fails (network,
/// `gh` missing, 404, malformed JSON). Always exit 0; never raise.
pub fn fallback_link(version: &str) -> String {
    let v = version.trim_start_matches('v');
    format!(
        "(release notes unavailable — check https://github.com/Alireza29675/teamctl/releases/tag/v{v})"
    )
}

/// Best-effort single-version print. Used by the `whatsnew` subcommand
/// when no `--since` is given. Fetch failure → fallback link, exit 0.
/// Callers that want a leading blank line (post-install visual gap)
/// should emit it themselves; this function prints the block as-is.
pub fn print_for(version: &str) {
    match fetch_release_body(version) {
        Ok(body) => print!("{}", render(version, &body)),
        Err(_) => println!("{}", fallback_link(version)),
    }
}

/// Effective FROM for the displayed frame. Per owner: the range is
/// `max(current, FLOOR_VERSION) to updated`. Selection logic already
/// clamps via `is_below_floor`; this is just the visual side so a
/// pre-floor `current` doesn't leak into the header.
fn effective_from(current: &str) -> String {
    if is_below_floor(current) {
        FLOOR_VERSION.to_string()
    } else {
        current.trim_start_matches('v').to_string()
    }
}

/// Best-effort aggregate print of every release body in `(from, to]`
/// that sits at or above the floor. Used by `teamctl update`'s
/// post-success display and `whatsnew --since X`. Fetch failure on
/// the list endpoint → falls back to single-version print of `to`.
/// Empty range (no intermediates above floor, or only `to` matters)
/// → single-version print of `to` so the user always sees the target.
pub fn print_since(from: &str, to: &str) {
    let display_from = effective_from(from);
    let to_v = to.trim_start_matches('v');
    // Degenerate range — effective from equals to (e.g. `whatsnew
    // --since 0.7.3` from a v0.8.0 binary clamps to 0.8.0 → 0.8.0).
    // Drop to the single-version frame so the operator doesn't see
    // "v0.8.0 → v0.8.0" in the header.
    if display_from == to_v {
        print_target_inline(to);
        return;
    }
    let entries = match fetch_releases_list() {
        Ok(all) => select_range(&all, from, to),
        Err(_) => {
            // The list endpoint failed; fall through to fetching just
            // the target version's body. Preserves the "always show
            // the target" contract.
            print_target_inline(to);
            return;
        }
    };
    if entries.is_empty() {
        // No intermediates landed in (from, to] above floor — fall
        // back to single-version display of the target.
        print_target_inline(to);
        return;
    }
    print!("{}", render_range(&display_from, to, &entries));
}

/// Helper used by `print_since` when the list-endpoint path can't
/// produce a range — fetches and prints just the target's body, or
/// the quiet fallback line if even that fails.
fn print_target_inline(version: &str) {
    match fetch_release_body(version) {
        Ok(body) => print!("{}", render(version, &body)),
        Err(_) => println!("{}", fallback_link(version)),
    }
}

fn curl_get(url: &str) -> Result<String> {
    let out = Command::new("curl")
        .args([
            "-sS",
            "-H",
            &format!("User-Agent: teamctl-cli/{CURRENT_VERSION}"),
            "--max-time",
            "15",
            url,
        ])
        .output()
        .context("run curl (is curl installed?)")?;
    if !out.status.success() {
        let err = String::from_utf8_lossy(&out.stderr);
        bail!("curl failed: {}", err.trim());
    }
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn extract_body_handles_single_line_json() {
        let blob = r#"{"id":1,"body":"hello world","name":"v0.8.0"}"#;
        assert_eq!(extract_body_field(blob).as_deref(), Some("hello world"));
    }

    #[test]
    fn extract_body_unescapes_newlines_and_quotes() {
        let blob = r#"{"body":"line1\nline2 \"quoted\" \\path"}"#;
        assert_eq!(
            extract_body_field(blob).as_deref(),
            Some("line1\nline2 \"quoted\" \\path")
        );
    }

    #[test]
    fn extract_body_returns_none_for_null_body() {
        let blob = r#"{"body":null,"tag_name":"v0.8.0"}"#;
        assert!(extract_body_field(blob).is_none());
    }

    #[test]
    fn extract_body_returns_none_for_empty_body() {
        let blob = r#"{"body":""}"#;
        assert!(extract_body_field(blob).is_none());
    }

    #[test]
    fn extract_body_returns_none_for_missing_field() {
        let blob = r#"{"tag_name":"v0.8.0"}"#;
        assert!(extract_body_field(blob).is_none());
    }

    #[test]
    fn extract_body_handles_unicode_escape() {
        let blob = r#"{"body":"✨ sparkle"}"#;
        assert_eq!(extract_body_field(blob).as_deref(), Some("✨ sparkle"));
    }

    #[test]
    fn extract_body_survives_round_trip_with_realistic_release_body() {
        // T-180: pin the serde_json swap against a release-body shape
        // that mixes the escapes the old hand-rolled parser had to
        // special-case: nested quotes around CLI vocabulary, escaped
        // backslashes inside backtick-spans, unicode-escaped accent,
        // and an emoji-prefixed opening line. If serde drifts or the
        // struct stops covering all three, this fails loud.
        let blob = r#"{"tag_name":"v0.8.0","body":"✨ \"What's new\" cleanup\n\nSwap `extract_body_field` to serde_json — fixes \"escaped quote\" handling and unicode (éclat) survives round-trip. Path: C:\\Users\\test.","name":"0.8.0"}"#;
        let body = extract_body_field(blob).expect("body present");
        assert!(body.contains("\"What's new\""));
        assert!(body.contains("`extract_body_field`"));
        assert!(body.contains("éclat"));
        assert!(body.contains(r"C:\Users\test"));
        assert!(body.starts_with(""));
    }

    #[test]
    fn extract_body_returns_none_for_malformed_json() {
        // Old hand-rolled parser silently returned None on shapes it
        // couldn't walk; serde behaves the same via `.ok()?`. Pin it
        // explicitly so a future change can't accidentally raise.
        let blob = r#"{"body": "unterminated"#;
        assert!(extract_body_field(blob).is_none());
    }

    #[test]
    fn parse_release_body_handles_single_entry() {
        let body = "# First headline\nA description line.\nAnother line.\n";
        let parsed = parse_release_body(body);
        assert_eq!(parsed.len(), 1);
        assert_eq!(parsed[0].headline, "First headline");
        assert_eq!(parsed[0].description, "A description line.\nAnother line.");
    }

    #[test]
    fn parse_release_body_handles_multiple_entries() {
        let body = "# Headline A\nDesc A.\n\n# Headline B\nDesc B line 1.\nDesc B line 2.\n";
        let parsed = parse_release_body(body);
        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0].headline, "Headline A");
        assert_eq!(parsed[0].description, "Desc A.");
        assert_eq!(parsed[1].headline, "Headline B");
        assert_eq!(parsed[1].description, "Desc B line 1.\nDesc B line 2.");
    }

    #[test]
    fn parse_release_body_returns_empty_when_no_headings() {
        let body = "just a paragraph of release notes\nwith two lines";
        assert!(parse_release_body(body).is_empty());
    }

    #[test]
    fn parse_release_body_treats_h2_as_non_convention() {
        let body = "# Headline\nIntro line.\n## Subsection\nMore description.\n";
        assert!(parse_release_body(body).is_empty());
    }

    #[test]
    fn parse_release_body_treats_code_fence_as_non_convention() {
        let body = "# Headline\nDescription with snippet:\n```sh\nteamctl up\n```\n";
        assert!(parse_release_body(body).is_empty());
    }

    #[test]
    fn parse_release_body_treats_cargo_dist_body_as_non_convention() {
        let body = "# team-bot 0.7.3\n## Install team-bot 0.7.3\n### shell\n```sh\ncurl ...\n```\n";
        assert!(parse_release_body(body).is_empty());
    }

    #[test]
    fn parse_release_body_handles_headline_without_description() {
        let body = "# Only a headline\n\n# Another\nWith body.\n";
        let parsed = parse_release_body(body);
        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0].headline, "Only a headline");
        assert!(parsed[0].description.is_empty());
        assert_eq!(parsed[1].headline, "Another");
    }

    #[test]
    fn render_frames_version_and_styles_descriptions() {
        let body = "# Headline\nLine one.\nLine two.\n";
        let rendered = render("0.8.0", body);
        assert!(rendered.starts_with("✨ What's new in v0.8.0\n\n"));
        assert!(rendered.contains("Headline\n"));
        assert!(rendered.contains("  \x1b[2;3mLine one.\x1b[0m"));
        assert!(rendered.contains("  \x1b[2;3mLine two.\x1b[0m"));
    }

    #[test]
    fn render_strips_v_prefix_in_header() {
        let body = "# H\nD.\n";
        let rendered = render("v0.8.0", body);
        assert!(rendered.starts_with("✨ What's new in v0.8.0\n\n"));
        assert!(!rendered.contains("vv0.8.0"));
    }

    #[test]
    fn render_falls_back_to_raw_for_non_conforming_body() {
        let body = "Older release with no structured convention.\nJust prose.\n";
        let rendered = render("0.6.0", body);
        assert!(rendered.starts_with("✨ What's new in v0.6.0\n\n"));
        assert!(rendered.contains("Older release with no structured convention."));
        assert!(rendered.contains("Just prose."));
        // No ANSI escapes on the raw fallback path.
        let body_only = rendered.replace("📖 Full changelog: https://teamctl.run/changelog\n", "");
        assert!(!body_only.contains("\x1b["));
    }

    #[test]
    fn render_separates_entries_with_blank_line() {
        let body = "# A\nDesc A.\n\n# B\nDesc B.\n";
        let rendered = render("0.8.0", body);
        let a_idx = rendered.find("Desc A.").unwrap();
        let b_idx = rendered.find("B\n").unwrap();
        let between = &rendered[a_idx..b_idx];
        let nl_count = between.matches('\n').count();
        assert!(
            nl_count >= 2,
            "expected blank line between entries, got: {between:?}"
        );
    }

    #[test]
    fn render_handles_empty_body() {
        let rendered = render("0.8.0", "");
        assert!(rendered.starts_with("✨ What's new in v0.8.0\n\n"));
        assert!(rendered.contains("📖 Full changelog"));
    }

    #[test]
    fn render_appends_footer_line() {
        let rendered = render("0.8.0", "# H\nD.\n");
        assert!(rendered.contains("📖 Full changelog: https://teamctl.run/changelog"));
        assert!(
            rendered.ends_with("https://teamctl.run/changelog\n"),
            "footer should be the last line: {rendered:?}"
        );
    }

    #[test]
    fn fallback_link_contains_tag_url() {
        let line = fallback_link("0.8.0");
        assert!(line.contains("https://github.com/Alireza29675/teamctl/releases/tag/v0.8.0"));
        assert!(line.contains("release notes unavailable"));
    }

    #[test]
    fn fallback_link_strips_v_prefix() {
        assert_eq!(fallback_link("v0.8.0"), fallback_link("0.8.0"));
    }

    // ── Range / aggregate display ────────────────────────────────────

    #[test]
    fn is_below_floor_is_inclusive_at_floor() {
        // The floor IS the first supported version, not below it.
        assert!(!is_below_floor("0.8.0"));
        assert!(!is_below_floor("v0.8.0"));
        assert!(!is_below_floor("0.8.1"));
        assert!(!is_below_floor("0.9.0"));
        assert!(!is_below_floor("1.0.0"));
    }

    #[test]
    fn is_below_floor_excludes_pre_floor_versions() {
        assert!(is_below_floor("0.7.3"));
        assert!(is_below_floor("0.7.0"));
        assert!(is_below_floor("0.6.0"));
        assert!(is_below_floor("v0.7.3"));
    }

    #[test]
    fn parse_releases_list_extracts_tag_and_body() {
        // r##""## escape needed because the JSON content contains `"#`
        // (body field starts with `"# `), which would prematurely close
        // a single-hash raw string.
        let json = r##"[
            {"tag_name":"v0.8.2","body":"# H2\nBody2","name":"v0.8.2"},
            {"tag_name":"v0.8.1","body":"# H1\nBody1"},
            {"tag_name":"v0.8.0","body":"# H0\nBody0"}
        ]"##;
        let list = parse_releases_list(json);
        assert_eq!(list.len(), 3);
        assert_eq!(list[0].version, "0.8.2");
        assert_eq!(list[0].body, "# H2\nBody2");
        assert_eq!(list[2].version, "0.8.0");
    }

    #[test]
    fn parse_releases_list_returns_empty_on_malformed_json() {
        assert!(parse_releases_list("{not json").is_empty());
        assert!(parse_releases_list(r#"{"message":"Not Found"}"#).is_empty());
    }

    #[test]
    fn parse_releases_list_skips_items_missing_tag() {
        let json = r#"[
            {"tag_name":"v0.8.0","body":"keep"},
            {"body":"skip me — no tag"},
            {"tag_name":"","body":"skip — empty tag"}
        ]"#;
        let list = parse_releases_list(json);
        assert_eq!(list.len(), 1);
        assert_eq!(list[0].version, "0.8.0");
    }

    #[test]
    fn parse_releases_list_tolerates_null_body() {
        let json = r#"[{"tag_name":"v0.8.0","body":null}]"#;
        let list = parse_releases_list(json);
        assert_eq!(list.len(), 1);
        assert_eq!(list[0].body, "");
    }

    fn sample_releases() -> Vec<ReleaseEntry> {
        // GitHub returns newest-first; mirror that here.
        vec![
            ReleaseEntry {
                version: "0.8.3".into(),
                body: "# T3\nD3".into(),
            },
            ReleaseEntry {
                version: "0.8.2".into(),
                body: "# T2\nD2".into(),
            },
            ReleaseEntry {
                version: "0.8.1".into(),
                body: "# T1\nD1".into(),
            },
            ReleaseEntry {
                version: "0.8.0".into(),
                body: "# T0\nD0".into(),
            },
            ReleaseEntry {
                version: "0.7.3".into(),
                body: "old".into(),
            },
        ]
    }

    #[test]
    fn select_range_excludes_from_and_includes_to() {
        let r = select_range(&sample_releases(), "0.8.0", "0.8.3");
        let vs: Vec<&str> = r.iter().map(|e| e.version.as_str()).collect();
        assert_eq!(vs, vec!["0.8.1", "0.8.2", "0.8.3"]);
    }

    #[test]
    fn select_range_cuts_below_floor() {
        // from below floor; floor + above should still surface.
        let r = select_range(&sample_releases(), "0.7.0", "0.8.1");
        let vs: Vec<&str> = r.iter().map(|e| e.version.as_str()).collect();
        // 0.7.3 excluded by floor; 0.8.0 + 0.8.1 included.
        assert_eq!(vs, vec!["0.8.0", "0.8.1"]);
    }

    #[test]
    fn select_range_returns_oldest_first() {
        let r = select_range(&sample_releases(), "0.7.0", "0.8.3");
        assert_eq!(r.first().unwrap().version, "0.8.0");
        assert_eq!(r.last().unwrap().version, "0.8.3");
    }

    #[test]
    fn select_range_is_empty_when_from_equals_to() {
        // (X, X] is empty; the caller falls back to single-version.
        let r = select_range(&sample_releases(), "0.8.2", "0.8.2");
        assert!(r.is_empty());
    }

    #[test]
    fn select_range_excludes_targets_below_floor() {
        // Both endpoints pre-floor; the result should be empty.
        let r = select_range(&sample_releases(), "0.7.0", "0.7.3");
        assert!(r.is_empty());
    }

    #[test]
    fn render_range_shows_range_frame_and_per_version_subheaders() {
        let entries = vec![
            ReleaseEntry {
                version: "0.8.1".into(),
                body: "# H1\nD1.".into(),
            },
            ReleaseEntry {
                version: "0.8.2".into(),
                body: "# H2\nD2.".into(),
            },
        ];
        let rendered = render_range("0.8.0", "0.8.2", &entries);
        assert!(rendered.starts_with("✨ What's new in v0.8.0 → v0.8.2\n\n"));
        assert!(rendered.contains("v0.8.1\nH1\n"));
        assert!(rendered.contains("v0.8.2\nH2\n"));
        assert!(rendered.ends_with("https://teamctl.run/changelog\n"));
    }

    #[test]
    fn render_range_strips_v_prefix_consistently() {
        let entries = vec![ReleaseEntry {
            version: "v0.8.1".into(),
            body: "# H\nD.".into(),
        }];
        let rendered = render_range("v0.8.0", "v0.8.1", &entries);
        assert!(rendered.starts_with("✨ What's new in v0.8.0 → v0.8.1\n\n"));
        // No double-v leaking through anywhere.
        assert!(!rendered.contains("vv"));
    }

    #[test]
    fn render_range_separates_versions_with_blank_line() {
        let entries = vec![
            ReleaseEntry {
                version: "0.8.1".into(),
                body: "# A\nDesc A.".into(),
            },
            ReleaseEntry {
                version: "0.8.3".into(),
                body: "# B\nDesc B.".into(),
            },
        ];
        // Frame uses v0.8.0 → v0.8.4 so the frame doesn't end in a
        // string that collides with our subheader search patterns.
        let rendered = render_range("0.8.0", "0.8.4", &entries);
        assert!(
            rendered.contains("\n\nv0.8.3\n"),
            "expected blank line before v0.8.3 subheader, got: {rendered:?}"
        );
    }

    #[test]
    fn footer_line_points_to_changelog() {
        assert_eq!(
            footer_line(),
            "📖 Full changelog: https://teamctl.run/changelog"
        );
    }

    #[test]
    fn effective_from_clamps_pre_floor_current_to_floor() {
        // Hypothetical 0.7.x backport: the running binary's version is
        // pre-floor, so the displayed frame's FROM clamps up to 0.8.0
        // rather than leaking "v0.7.3" into the header.
        assert_eq!(effective_from("0.7.3"), "0.8.0");
        assert_eq!(effective_from("v0.6.0"), "0.8.0");
    }

    #[test]
    fn effective_from_preserves_at_or_above_floor() {
        assert_eq!(effective_from("0.8.0"), "0.8.0");
        assert_eq!(effective_from("0.8.5"), "0.8.5");
        assert_eq!(effective_from("v0.9.0"), "0.9.0");
        assert_eq!(effective_from("1.0.0"), "1.0.0");
    }
}