gen-orb-mcp 0.1.31

Generate MCP servers from CircleCI orb definitions
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
//! Orb version history primer.
//!
//! Manages `prior-versions/` and `migrations/` directories as a sliding window:
//! - Versions within the window → snapshots and conformance rule JSON files
//!   created
//! - Versions outside the window → snapshots and rule files removed
//! - Idempotent: existing files are skipped; out-of-window files are removed

use std::path::{Path, PathBuf};

use anyhow::Result;
use chrono::{Datelike, NaiveDate};

use std::collections::HashMap;

use crate::{
    conformance_rule::ConformanceRule,
    differ,
    parser::{OrbDefinition, OrbParser},
};

/// A version tag annotated with its commit date.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TagWithDate {
    pub version: String,
    pub date: NaiveDate,
}

/// Configuration for the prime operation.
pub struct PrimeConfig {
    pub git_repo: PathBuf,
    pub tag_prefix: String,
    pub orb_path_relative: PathBuf,
    pub prior_versions_dir: PathBuf,
    pub migrations_dir: PathBuf,
    pub dry_run: bool,
    /// Manual rename-map overrides (`OLD → NEW`) injected via `--rename-map`.
    /// These take precedence over git-detected rename hints for matching keys.
    pub extra_rename_hints: Vec<(String, String)>,
}

/// Result of a prime operation.
#[derive(Debug, Default)]
pub struct PrimeResult {
    pub snapshots_added: usize,
    pub snapshots_removed: usize,
    pub migrations_added: usize,
    pub migrations_removed: usize,
}

impl std::fmt::Display for PrimeResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} snapshot(s) added, {} removed; {} migration file(s) added, {} removed",
            self.snapshots_added,
            self.snapshots_removed,
            self.migrations_added,
            self.migrations_removed
        )
    }
}

// ── Pure functions
// ────────────────────────────────────────────────────────────

/// Filter a version list to those at or after `earliest` (semver comparison).
///
/// Tags that cannot be parsed as semver are silently skipped with a warning.
pub fn filter_by_version(tags: &[String], earliest: &semver::Version) -> Vec<String> {
    tags.iter()
        .filter_map(|v| match semver::Version::parse(v) {
            Ok(parsed) if parsed >= *earliest => Some(v.clone()),
            Ok(_) => None,
            Err(_) => {
                tracing::warn!(tag = %v, "Skipping tag: not valid semver");
                None
            }
        })
        .collect()
}

/// Filter a list of tags-with-dates to those on or after `cutoff`.
pub fn filter_by_date(tags: &[TagWithDate], cutoff: NaiveDate) -> Vec<String> {
    tags.iter()
        .filter(|t| t.date >= cutoff)
        .map(|t| t.version.clone())
        .collect()
}

/// Compute the cutoff `NaiveDate` from a duration string.
///
/// Supported formats: `"N months"`, `"N month"`, `"N years"`, `"N year"`,
/// `"N weeks"`, `"N week"`.
///
/// `today` is injected so tests can pass a fixed date.
pub fn since_cutoff(since: &str, today: NaiveDate) -> Result<NaiveDate> {
    let since = since.trim().to_lowercase();
    let parts: Vec<&str> = since.splitn(2, ' ').collect();
    if parts.len() != 2 {
        anyhow::bail!(
            "Invalid --since format '{}': expected 'N unit' e.g. '6 months'",
            since
        );
    }
    let n: i64 = parts[0]
        .parse()
        .map_err(|_| anyhow::anyhow!("Invalid --since format '{}': N must be a number", since))?;
    let unit = parts[1].trim_end_matches('s'); // normalise plural
    match unit {
        "month" => {
            let month = today.month() as i64 - n;
            let (year_offset, new_month) = if month <= 0 {
                let years_back = (-month / 12) + 1;
                (years_back, month + years_back * 12)
            } else {
                (0, month)
            };
            let new_year = today.year() - year_offset as i32;
            let new_month = new_month as u32;
            // Saturate to last day of month if needed
            let max_day = days_in_month(new_year, new_month);
            let new_day = today.day().min(max_day);
            NaiveDate::from_ymd_opt(new_year, new_month, new_day)
                .ok_or_else(|| anyhow::anyhow!("Date arithmetic produced invalid date"))
        }
        "year" => {
            let new_year = today.year() - n as i32;
            let max_day = days_in_month(new_year, today.month());
            let new_day = today.day().min(max_day);
            NaiveDate::from_ymd_opt(new_year, today.month(), new_day)
                .ok_or_else(|| anyhow::anyhow!("Date arithmetic produced invalid date"))
        }
        "week" => {
            let days = chrono::Days::new((n * 7) as u64);
            today
                .checked_sub_days(days)
                .ok_or_else(|| anyhow::anyhow!("Date arithmetic overflow"))
        }
        _ => anyhow::bail!(
            "Invalid --since unit '{}': use 'months', 'years', or 'weeks'",
            parts[1]
        ),
    }
}

/// Returns the number of days in the given month/year.
fn days_in_month(year: i32, month: u32) -> u32 {
    let next_month = if month == 12 {
        NaiveDate::from_ymd_opt(year + 1, 1, 1)
    } else {
        NaiveDate::from_ymd_opt(year, month + 1, 1)
    };
    next_month
        .unwrap()
        .signed_duration_since(NaiveDate::from_ymd_opt(year, month, 1).unwrap())
        .num_days() as u32
}

/// Returns `true` if the snapshot file for `version` does not yet exist in
/// `dir`.
pub fn snapshot_needed(dir: &Path, version: &str) -> bool {
    !dir.join(format!("{version}.yml")).exists()
}

/// Returns `true` if the migration file for `version` does not yet exist in
/// `dir`.
pub fn migration_needed(dir: &Path, version: &str) -> bool {
    !dir.join(format!("{version}.json")).exists()
}

/// Compute conformance rules between two consecutive orb versions.
///
/// Returns an empty `Vec` when the orbs are structurally identical.
pub fn compute_diff(old: &OrbDefinition, new: &OrbDefinition, since: &str) -> Vec<ConformanceRule> {
    differ::diff(old, new, since)
}

/// Merge git-detected rename hints with manually supplied overrides.
///
/// Manual entries (from `--rename-map`) take precedence: they are inserted
/// last and overwrite any conflicting git-detected entry for the same old name.
pub fn merge_rename_hints(
    mut git_hints: HashMap<String, String>,
    manual: &[(String, String)],
) -> HashMap<String, String> {
    for (from, to) in manual {
        git_hints.insert(from.clone(), to.clone());
    }
    git_hints
}

/// Compute conformance rules using authoritative git rename hints.
///
/// `job_rename_hints` maps old job name → new job name as derived from
/// `git_rename_hints_for_jobs`.
pub fn compute_diff_with_hints(
    old: &OrbDefinition,
    new: &OrbDefinition,
    since: &str,
    job_rename_hints: HashMap<String, String>,
) -> Vec<ConformanceRule> {
    differ::diff_with_hints(old, new, since, job_rename_hints)
}

/// Extract job file rename pairs from git history between two version tags.
///
/// Runs `git log <old_tag>..<new_tag> --diff-filter=R --name-status`
/// restricted to `src/jobs/*.yml` and returns a map of
/// `old_job_name → new_job_name` (file stems, without `.yml`).
///
/// Returns an empty map on any error (callers fall back to Jaccard).
pub fn git_rename_hints_for_jobs(
    git_repo: &Path,
    tag_prefix: &str,
    prev_version: &str,
    curr_version: &str,
) -> HashMap<String, String> {
    let old_tag = format!("{}{}", tag_prefix, prev_version);
    let new_tag = format!("{}{}", tag_prefix, curr_version);
    let range = format!("{}..{}", old_tag, new_tag);

    let output = std::process::Command::new("git")
        .args([
            "-C",
            git_repo.to_str().unwrap_or("."),
            "log",
            &range,
            "--diff-filter=R",
            "--name-status",
            "--",
            "src/jobs/*.yml",
            "src/commands/*.yml",
        ])
        .output();

    let output = match output {
        Ok(o) if o.status.success() => o,
        Ok(o) => {
            let stderr = String::from_utf8_lossy(&o.stderr);
            tracing::warn!(prev = prev_version, curr = curr_version, stderr = %stderr, "git log for rename hints failed");
            return HashMap::new();
        }
        Err(e) => {
            tracing::warn!(prev = prev_version, curr = curr_version, error = %e, "Failed to run git log for rename hints");
            return HashMap::new();
        }
    };

    parse_rename_hints_output(&String::from_utf8_lossy(&output.stdout))
}

/// Parse the output of `git log --diff-filter=R --name-status` into a map of
/// old job name → new job name.
///
/// Each rename appears as a line like: `R100\tsrc/jobs/old.yml\tsrc/jobs/new.yml`
pub fn parse_rename_hints_output(output: &str) -> HashMap<String, String> {
    let mut hints = HashMap::new();
    for line in output.lines() {
        let line = line.trim();
        // Skip non-rename lines (commit messages, blank lines, etc.)
        if !line.starts_with('R') {
            continue;
        }
        let parts: Vec<&str> = line.splitn(3, '\t').collect();
        if parts.len() != 3 {
            continue;
        }
        // Extract file stem (job name) from path like "src/jobs/old_name.yml"
        let old_stem = file_stem_from_path(parts[1]);
        let new_stem = file_stem_from_path(parts[2]);
        if !old_stem.is_empty() && !new_stem.is_empty() {
            hints.insert(old_stem, new_stem);
        }
    }
    hints
}

/// Extract the file stem (name without directory and `.yml` extension).
fn file_stem_from_path(path: &str) -> String {
    let path = std::path::Path::new(path.trim());
    path.file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("")
        .to_string()
}

/// Serialise an `OrbDefinition` to YAML for storage as a snapshot file.
pub fn serialize_orb(orb: &OrbDefinition) -> Result<String> {
    serde_yaml::to_string(orb).map_err(|e| anyhow::anyhow!("Failed to serialise orb: {}", e))
}

// ── Git subprocess functions
// ──────────────────────────────────────────────────

/// List all version tags in `git_repo` that start with `tag_prefix`, sorted by
/// semver.
///
/// Returns bare version strings (prefix stripped).
pub fn discover_tags(git_repo: &Path, tag_prefix: &str) -> Result<Vec<String>> {
    let pattern = format!("{}*", tag_prefix);
    let output = std::process::Command::new("git")
        .args([
            "-C",
            git_repo.to_str().unwrap_or("."),
            "tag",
            "--sort=version:refname",
            "-l",
            &pattern,
        ])
        .output()
        .map_err(|e| anyhow::anyhow!("Failed to run git tag: {}", e))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git tag failed: {}", stderr);
    }

    let prefix_len = tag_prefix.len();
    let tags = String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|line| {
            let tag = line.trim();
            if tag.starts_with(tag_prefix) {
                Some(tag[prefix_len..].to_string())
            } else {
                None
            }
        })
        .collect();

    Ok(tags)
}

/// Fetch the commit date for a single version tag.
///
/// Runs `git log -1 --format=%ci <prefix><version>^{}` to dereference annotated
/// tags.
pub fn tag_date(git_repo: &Path, tag_prefix: &str, version: &str) -> Result<NaiveDate> {
    let tag = format!("{}{}", tag_prefix, version);
    let output = std::process::Command::new("git")
        .args([
            "-C",
            git_repo.to_str().unwrap_or("."),
            "log",
            "-1",
            "--format=%ci",
            &format!("{}^{{}}", tag),
        ])
        .output()
        .map_err(|e| anyhow::anyhow!("Failed to run git log for tag {}: {}", tag, e))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("git log failed for tag {}: {}", tag, stderr);
    }

    let date_str = String::from_utf8_lossy(&output.stdout);
    let date_str = date_str.trim();
    if date_str.is_empty() {
        anyhow::bail!("git log returned empty date for tag {}", tag);
    }

    // Format: "2024-01-15 10:30:00 +0000" — take the first 10 chars
    NaiveDate::parse_from_str(&date_str[..10], "%Y-%m-%d")
        .map_err(|e| anyhow::anyhow!("Failed to parse date '{}' for tag {}: {}", date_str, tag, e))
}

/// RAII guard for a git worktree.
///
/// Runs `git worktree remove --force <path>` on drop.
struct WorktreeGuard {
    path: PathBuf,
    git_repo: PathBuf,
}

impl WorktreeGuard {
    fn new(git_repo: &Path, path: &Path) -> Self {
        WorktreeGuard {
            path: path.to_owned(),
            git_repo: git_repo.to_owned(),
        }
    }
}

impl Drop for WorktreeGuard {
    fn drop(&mut self) {
        let _ = std::process::Command::new("git")
            .args([
                "-C",
                self.git_repo.to_str().unwrap_or("."),
                "worktree",
                "remove",
                "--force",
                self.path.to_str().unwrap_or(""),
            ])
            .output();
    }
}

/// Check out a version tag into a temp worktree, parse the orb, remove the
/// worktree.
///
/// The RAII guard ensures cleanup even on panic.
pub fn checkout_and_parse(
    git_repo: &Path,
    tag_prefix: &str,
    version: &str,
    orb_path_relative: &Path,
) -> Result<OrbDefinition> {
    let worktree_path = std::env::temp_dir().join(format!(
        "gen-orb-mcp-prime-{}-{}",
        std::process::id(),
        version
    ));

    // Remove stale worktree if it exists
    let _ = std::process::Command::new("git")
        .args([
            "-C",
            git_repo.to_str().unwrap_or("."),
            "worktree",
            "remove",
            "--force",
            worktree_path.to_str().unwrap_or(""),
        ])
        .output();

    let tag = format!("{}{}", tag_prefix, version);
    let add_output = std::process::Command::new("git")
        .args([
            "-C",
            git_repo.to_str().unwrap_or("."),
            "worktree",
            "add",
            worktree_path.to_str().unwrap_or(""),
            &tag,
        ])
        .output()
        .map_err(|e| anyhow::anyhow!("Failed to add worktree for {}: {}", tag, e))?;

    if !add_output.status.success() {
        let stderr = String::from_utf8_lossy(&add_output.stderr);
        anyhow::bail!("git worktree add failed for {}: {}", tag, stderr);
    }

    // RAII guard: removes worktree on drop (even if parsing fails)
    let _guard = WorktreeGuard::new(git_repo, &worktree_path);

    let orb_full_path = worktree_path.join(orb_path_relative);
    OrbParser::parse(&orb_full_path).map_err(|e| {
        anyhow::anyhow!(
            "Failed to parse orb at {} ({}): {}",
            orb_full_path.display(),
            tag,
            e
        )
    })
}

// ── High-level prime operation
// ────────────────────────────────────────────────

/// Run the prime operation: add missing snapshots/rules and remove
/// out-of-window ones.
pub fn prime(config: &PrimeConfig, window_versions: &[String]) -> Result<PrimeResult> {
    let mut result = PrimeResult::default();

    if !config.dry_run {
        std::fs::create_dir_all(&config.prior_versions_dir)?;
        std::fs::create_dir_all(&config.migrations_dir)?;
    }

    result.snapshots_added = add_snapshots(config, window_versions)?;
    result.migrations_added = add_migrations(config, window_versions)?;

    let window_set: std::collections::HashSet<&String> = window_versions.iter().collect();
    let (snaps_removed, migs_removed) = remove_out_of_window(config, &window_set)?;
    result.snapshots_removed = snaps_removed;
    result.migrations_removed += migs_removed;
    result.migrations_removed += remove_orphaned_migrations(config)?;

    Ok(result)
}

/// ADD: snapshots for in-window versions not yet present.
fn add_snapshots(config: &PrimeConfig, window_versions: &[String]) -> Result<usize> {
    let mut added = 0;
    for version in window_versions {
        if !snapshot_needed(&config.prior_versions_dir, version) {
            tracing::debug!(version, "Skipping snapshot (already exists)");
            continue;
        }
        if config.dry_run {
            println!("would create prior-versions/{version}.yml");
        } else {
            let orb = checkout_and_parse(
                &config.git_repo,
                &config.tag_prefix,
                version,
                &config.orb_path_relative,
            )?;
            let yaml = serialize_orb(&orb)?;
            let path = config.prior_versions_dir.join(format!("{version}.yml"));
            std::fs::write(&path, &yaml)?;
            println!("created prior-versions/{version}.yml");
        }
        added += 1;
    }
    Ok(added)
}

/// ADD: migration rules for consecutive in-window pairs.
fn add_migrations(config: &PrimeConfig, window_versions: &[String]) -> Result<usize> {
    let mut added = 0;
    for pair in window_versions.windows(2) {
        let prev = &pair[0];
        let curr = &pair[1];
        if !migration_needed(&config.migrations_dir, curr) {
            tracing::debug!(version = %curr, "Skipping migration (already exists)");
            continue;
        }
        if config.dry_run {
            println!("would create migrations/{curr}.json (if rules non-empty)");
        } else {
            added += write_migration_if_nonempty(config, prev, curr)?;
        }
    }
    Ok(added)
}

/// Compute and write a migration file for `curr` vs `prev`; returns 1 if
/// written, 0 if empty.
fn write_migration_if_nonempty(config: &PrimeConfig, prev: &str, curr: &str) -> Result<usize> {
    let prev_path = config.prior_versions_dir.join(format!("{prev}.yml"));
    let curr_path = config.prior_versions_dir.join(format!("{curr}.yml"));
    if !prev_path.exists() || !curr_path.exists() {
        tracing::warn!(prev, curr, "Skipping diff: snapshot missing");
        return Ok(0);
    }
    let old_orb = OrbParser::parse(&prev_path)
        .map_err(|e| anyhow::anyhow!("Failed to parse {}: {}", prev_path.display(), e))?;
    let new_orb = OrbParser::parse(&curr_path)
        .map_err(|e| anyhow::anyhow!("Failed to parse {}: {}", curr_path.display(), e))?;

    // Fetch authoritative job rename hints from git history between the two tags,
    // then overlay any manually supplied --rename-map entries (manual wins on conflict).
    let git_hints = git_rename_hints_for_jobs(&config.git_repo, &config.tag_prefix, prev, curr);
    let hints = merge_rename_hints(git_hints, &config.extra_rename_hints);
    if !hints.is_empty() {
        tracing::debug!(prev, curr, hints = ?hints, "Using rename hints for migration diff");
    }

    let rules = compute_diff_with_hints(&old_orb, &new_orb, curr, hints);
    if rules.is_empty() {
        tracing::debug!(version = %curr, "No migration rules (orbs identical in structure)");
        return Ok(0);
    }
    let json = serde_json::to_string_pretty(&rules)?;
    let path = config.migrations_dir.join(format!("{curr}.json"));
    std::fs::write(&path, &json)?;
    println!("created migrations/{curr}.json ({} rules)", rules.len());
    Ok(1)
}

/// REMOVE: snapshots outside the window and their matching migration files.
/// Returns `(snapshots_removed, migrations_removed)`.
fn remove_out_of_window(
    config: &PrimeConfig,
    window_set: &std::collections::HashSet<&String>,
) -> Result<(usize, usize)> {
    let (mut snaps, mut migs) = (0, 0);
    if !config.prior_versions_dir.is_dir() {
        return Ok((0, 0));
    }
    for entry in std::fs::read_dir(&config.prior_versions_dir)?.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("yml") {
            continue;
        }
        let version = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("")
            .to_string();
        if version.is_empty() || window_set.contains(&version) {
            continue;
        }
        remove_or_announce(
            config.dry_run,
            &path,
            &format!("prior-versions/{version}.yml (outside window)"),
        )?;
        snaps += 1;
        let mig_path = config.migrations_dir.join(format!("{version}.json"));
        if mig_path.exists() {
            remove_or_announce(
                config.dry_run,
                &mig_path,
                &format!("migrations/{version}.json (snapshot removed)"),
            )?;
            migs += 1;
        }
    }
    Ok((snaps, migs))
}

/// REMOVE: orphaned migration files (no matching snapshot). Returns count
/// removed.
fn remove_orphaned_migrations(config: &PrimeConfig) -> Result<usize> {
    let mut removed = 0;
    if !config.migrations_dir.is_dir() {
        return Ok(0);
    }
    for entry in std::fs::read_dir(&config.migrations_dir)?.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }
        let version = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("")
            .to_string();
        if version.is_empty() {
            continue;
        }
        let snapshot = config.prior_versions_dir.join(format!("{version}.yml"));
        if !snapshot.exists() {
            remove_or_announce(
                config.dry_run,
                &path,
                &format!("migrations/{version}.json (orphaned)"),
            )?;
            removed += 1;
        }
    }
    Ok(removed)
}

/// Remove a file or print a dry-run announcement.
fn remove_or_announce(dry_run: bool, path: &Path, label: &str) -> Result<()> {
    if dry_run {
        println!("would remove {label}");
    } else {
        std::fs::remove_file(path)?;
        println!("removed {label}");
    }
    Ok(())
}

// ─────────────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
    use tempfile::TempDir;

    use super::*;

    // ── Test 1: filter_by_version ─────────────────────────────────────────────
    #[test]
    fn test_filter_tags_by_version() {
        let tags = vec![
            "4.0.2".to_string(),
            "4.0.9".to_string(),
            "4.1.0".to_string(),
            "4.5.0".to_string(),
            "5.0.0".to_string(),
            "not-a-semver".to_string(),
        ];
        let earliest = semver::Version::parse("4.1.0").unwrap();
        let result = filter_by_version(&tags, &earliest);
        assert_eq!(result, vec!["4.1.0", "4.5.0", "5.0.0"]);
        // 4.0.x filtered out; "not-a-semver" silently dropped
    }

    // ── Test 2: filter_by_date ────────────────────────────────────────────────
    #[test]
    fn test_filter_tags_by_date() {
        let cutoff = NaiveDate::from_ymd_opt(2025, 9, 1).unwrap();
        let tags = vec![
            TagWithDate {
                version: "4.0.0".to_string(),
                date: NaiveDate::from_ymd_opt(2025, 8, 31).unwrap(),
            },
            TagWithDate {
                version: "4.5.0".to_string(),
                date: NaiveDate::from_ymd_opt(2025, 9, 1).unwrap(), // exactly on cutoff
            },
            TagWithDate {
                version: "4.9.6".to_string(),
                date: NaiveDate::from_ymd_opt(2025, 10, 15).unwrap(),
            },
        ];
        let result = filter_by_date(&tags, cutoff);
        assert_eq!(result, vec!["4.5.0", "4.9.6"]);
    }

    // ── Test 3: since_cutoff default of 6 months ──────────────────────────────
    #[test]
    fn test_default_since_is_six_months() {
        let today = NaiveDate::from_ymd_opt(2026, 3, 20).unwrap();
        let cutoff = since_cutoff("6 months", today).unwrap();
        assert_eq!(cutoff, NaiveDate::from_ymd_opt(2025, 9, 20).unwrap());
    }

    // ── Test 4: since_cutoff parses multiple formats ───────────────────────────
    #[test]
    fn test_since_cutoff_parsing() {
        let today = NaiveDate::from_ymd_opt(2026, 1, 15).unwrap();
        assert_eq!(
            since_cutoff("6 months", today).unwrap(),
            NaiveDate::from_ymd_opt(2025, 7, 15).unwrap()
        );
        assert_eq!(
            since_cutoff("1 year", today).unwrap(),
            NaiveDate::from_ymd_opt(2025, 1, 15).unwrap()
        );
        assert_eq!(
            since_cutoff("2 years", today).unwrap(),
            NaiveDate::from_ymd_opt(2024, 1, 15).unwrap()
        );
        assert_eq!(
            since_cutoff("3 weeks", today).unwrap(),
            NaiveDate::from_ymd_opt(2025, 12, 25).unwrap()
        );
        assert!(
            since_cutoff("garbage", today).is_err(),
            "invalid input should fail"
        );
        assert!(
            since_cutoff("abc months", today).is_err(),
            "non-numeric N should fail"
        );
    }

    // ── Test 5: month-end saturation ──────────────────────────────────────────
    #[test]
    fn test_since_cutoff_month_end() {
        // March 31 - 6 months = September 30 (September has 30 days, not 31)
        let today = NaiveDate::from_ymd_opt(2026, 3, 31).unwrap();
        let cutoff = since_cutoff("6 months", today).unwrap();
        assert_eq!(cutoff, NaiveDate::from_ymd_opt(2025, 9, 30).unwrap());
    }

    // ── Test 6: idempotent — skips existing snapshot ──────────────────────────
    #[test]
    fn test_idempotent_skips_existing_snapshot() {
        let tmp = TempDir::new().unwrap();
        let pv_dir = tmp.path().join("prior-versions");
        std::fs::create_dir_all(&pv_dir).unwrap();
        let snap = pv_dir.join("4.5.0.yml");
        std::fs::write(&snap, "sentinel: existing").unwrap();

        assert!(
            !snapshot_needed(&pv_dir, "4.5.0"),
            "should report not needed"
        );
        assert_eq!(
            std::fs::read_to_string(&snap).unwrap(),
            "sentinel: existing",
            "file must not be overwritten"
        );
    }

    // ── Test 7: idempotent — skips existing migration ─────────────────────────
    #[test]
    fn test_idempotent_skips_existing_diff() {
        let tmp = TempDir::new().unwrap();
        let mig_dir = tmp.path().join("migrations");
        std::fs::create_dir_all(&mig_dir).unwrap();
        let mig = mig_dir.join("4.5.0.json");
        std::fs::write(&mig, r#"[{"type":"existing"}]"#).unwrap();

        assert!(!migration_needed(&mig_dir, "4.5.0"));
        assert_eq!(
            std::fs::read_to_string(&mig).unwrap(),
            r#"[{"type":"existing"}]"#
        );
    }

    // ── Test 8: empty diff — no file written ──────────────────────────────────
    #[test]
    fn test_empty_diff_not_written() {
        let orb = OrbDefinition::default();
        let rules = compute_diff(&orb, &orb, "4.5.0");
        assert!(rules.is_empty(), "identical orbs should produce no rules");

        let tmp = TempDir::new().unwrap();
        let mig_dir = tmp.path().join("migrations");
        std::fs::create_dir_all(&mig_dir).unwrap();

        // Simulate the write-if-non-empty logic
        if !rules.is_empty() {
            std::fs::write(mig_dir.join("4.5.0.json"), "[]").unwrap();
        }
        assert!(
            !mig_dir.join("4.5.0.json").exists(),
            "empty diff must not create a file"
        );
    }

    // ── Test 9: sliding window removes out-of-window snapshot ─────────────────
    #[test]
    fn test_sliding_window_removes_old_snapshot() {
        let tmp = TempDir::new().unwrap();
        let pv_dir = tmp.path().join("prior-versions");
        let mig_dir = tmp.path().join("migrations");
        std::fs::create_dir_all(&pv_dir).unwrap();
        std::fs::create_dir_all(&mig_dir).unwrap();

        // Simulate two snapshots: 4.0.0 (old, out of window) and 5.0.0 (current window)
        std::fs::write(pv_dir.join("4.0.0.yml"), "old: true").unwrap();
        std::fs::write(pv_dir.join("5.0.0.yml"), "current: true").unwrap();

        let window = ["5.0.0".to_string()];
        let config = PrimeConfig {
            git_repo: tmp.path().to_owned(),
            tag_prefix: "v".to_string(),
            orb_path_relative: PathBuf::from("src/@orb.yml"),
            prior_versions_dir: pv_dir.clone(),
            migrations_dir: mig_dir,
            dry_run: false,
            extra_rename_hints: vec![],
        };

        // Only run the removal part (window already satisfied, no git ops needed)
        let window_set: std::collections::HashSet<&String> = window.iter().collect();
        for entry in std::fs::read_dir(&pv_dir).unwrap().flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("yml") {
                continue;
            }
            let version = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_string();
            if !window_set.contains(&version) {
                std::fs::remove_file(&path).unwrap();
            }
        }

        assert!(
            !pv_dir.join("4.0.0.yml").exists(),
            "out-of-window snapshot must be removed"
        );
        assert!(
            pv_dir.join("5.0.0.yml").exists(),
            "in-window snapshot must remain"
        );
        drop(config); // suppress unused warning
    }

    // ── Test 10: sliding window removes orphaned migration ────────────────────
    #[test]
    fn test_sliding_window_removes_orphaned_migration() {
        let tmp = TempDir::new().unwrap();
        let pv_dir = tmp.path().join("prior-versions");
        let mig_dir = tmp.path().join("migrations");
        std::fs::create_dir_all(&pv_dir).unwrap();
        std::fs::create_dir_all(&mig_dir).unwrap();

        // Migration for 4.0.0 exists but its snapshot does not
        std::fs::write(mig_dir.join("4.0.0.json"), r#"[]"#).unwrap();
        // Snapshot for 5.0.0 exists (in window)
        std::fs::write(pv_dir.join("5.0.0.yml"), "current: true").unwrap();

        // Simulate orphan removal
        for entry in std::fs::read_dir(&mig_dir).unwrap().flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("json") {
                continue;
            }
            let version = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_string();
            let snapshot = pv_dir.join(format!("{version}.yml"));
            if !snapshot.exists() {
                std::fs::remove_file(&path).unwrap();
            }
        }

        assert!(
            !mig_dir.join("4.0.0.json").exists(),
            "orphaned migration must be removed"
        );
    }

    // ── Test 11: parse_rename_hints_output ───────────────────────────────────
    #[test]
    fn test_parse_rename_hints_output() {
        let output = "R100\tsrc/jobs/required_builds_rolling.yml\tsrc/jobs/required_builds.yml\n\
                      R100\tsrc/jobs/common_tests_rolling.yml\tsrc/jobs/common_tests.yml\n\
                      M\tsrc/jobs/other.yml\n\
                      \n\
                      commit abc123\n";
        let hints = parse_rename_hints_output(output);
        assert_eq!(
            hints.get("required_builds_rolling"),
            Some(&"required_builds".to_string())
        );
        assert_eq!(
            hints.get("common_tests_rolling"),
            Some(&"common_tests".to_string())
        );
        // Non-rename lines must not appear in output
        assert!(!hints.contains_key("other"), "M-lines must be ignored");
        assert_eq!(hints.len(), 2);
    }

    #[test]
    fn test_parse_rename_hints_output_empty() {
        let hints = parse_rename_hints_output("");
        assert!(hints.is_empty());
    }

    // ── Test 12: extra_rename_hints override git-detected hints ──────────────
    #[test]
    fn test_extra_rename_hints_override_git_hints() {
        // Manual hint says `common_tests_rolling -> common_tests`.
        // Git hint (simulated) would say `common_tests_rolling -> common_tests_pinned`.
        // The manual entry must win.
        let mut git_hints = HashMap::new();
        git_hints.insert(
            "common_tests_rolling".to_string(),
            "common_tests_pinned".to_string(),
        );
        let manual: Vec<(String, String)> = vec![(
            "common_tests_rolling".to_string(),
            "common_tests".to_string(),
        )];
        let merged = merge_rename_hints(git_hints, &manual);
        assert_eq!(
            merged.get("common_tests_rolling"),
            Some(&"common_tests".to_string()),
            "manual hint must override git-detected hint"
        );
    }

    // ── Test 13: extra_rename_hints supplement git hints for uncovered jobs ──
    #[test]
    fn test_extra_rename_hints_supplement_git_hints() {
        // Git only detected one rename; manual adds another.
        let mut git_hints = HashMap::new();
        git_hints.insert(
            "required_builds_rolling".to_string(),
            "required_builds".to_string(),
        );
        let manual: Vec<(String, String)> = vec![(
            "common_tests_rolling".to_string(),
            "common_tests".to_string(),
        )];
        let merged = merge_rename_hints(git_hints, &manual);
        assert_eq!(merged.len(), 2);
        assert_eq!(
            merged.get("required_builds_rolling"),
            Some(&"required_builds".to_string()),
            "git hint must be preserved"
        );
        assert_eq!(
            merged.get("common_tests_rolling"),
            Some(&"common_tests".to_string()),
            "manual hint must be added"
        );
    }

    // ── Test 14: empty manual hints leaves git hints unchanged ────────────────
    #[test]
    fn test_extra_rename_hints_empty_manual_is_noop() {
        let mut git_hints = HashMap::new();
        git_hints.insert("foo".to_string(), "bar".to_string());
        let merged = merge_rename_hints(git_hints.clone(), &[]);
        assert_eq!(merged, git_hints);
    }

    // ── Tests 15+: CLI parsing (in lib.rs) ───────────────────────────────────
    // These are defined in lib.rs in the tests module for the Prime command
    // variant.

    // ── Test integration: dry-run creates no files ────────────────────────────
    // This is an integration test requiring a real git repo fixture.
    // Defined in tests/prime_integration_tests.rs (to be added).
}