oakum 0.12.1

A polyglot release tool that derives dependent version bumps from the dependency graph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
//! Reading rules for `.changeset/*.md` (`okm-wnp`).
//!
//! Spec (`docs/specs/bump-files.md`): every `.md` directly in the directory is a
//! bump file except four instruction names; subdirectories and non-`.md` files
//! are not candidates; a malformed body is collected by path, and every
//! command refuses on it; an unknown package name is an error naming the file
//! and the name.
//!
//! This module does not touch the filesystem. Callers list the directory and
//! pass `(file_name, body)` pairs; `clippy.toml` keeps it free of I/O (ADR-0002).

use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

use crate::plan::{BumpFile, BumpLevel, PackageId, Workspace};

use super::format::{parse, parse_migration, ChangeFile, ParseError};

/// Exact-match instruction files `@changesets/read` v3 skips (case-sensitive).
const EXACT_SKIP: &[&str] = &["AGENTS.md", "CLAUDE.md", "GEMINI.md"];

/// True when `file_name` is one of the four instruction names that are not bump
/// files: `README.md` case-insensitively, and `AGENTS.md` / `CLAUDE.md` /
/// `GEMINI.md` by exact string equality.
#[must_use]
pub fn skipped_instruction_name(file_name: &str) -> bool {
    if file_name.eq_ignore_ascii_case("README.md") {
        return true;
    }
    EXACT_SKIP.contains(&file_name)
}

/// True when `file_name` is a direct `.changeset/` candidate: a bare `.md`
/// name (case-sensitive suffix, no path separators) that is not an instruction skip.
#[must_use]
pub fn is_bump_file_name(file_name: &str) -> bool {
    if file_name.contains('/') || file_name.contains('\\') {
        return false;
    }
    lowercase_md_suffix(file_name) && !skipped_instruction_name(file_name)
}

/// `@changesets/read` and knope both match `.md` case-sensitively.
fn lowercase_md_suffix(file_name: &str) -> bool {
    #[expect(
        clippy::case_sensitive_file_extension_comparisons,
        reason = "foreign readers match `.md` case-sensitively; `.MD` is not a bump file"
    )]
    {
        file_name.ends_with(".md")
    }
}

/// How a `.changeset/` directory entry relates to the instruction skip list (`okm-3a3`).
///
/// Oakum never fails a run for these names. [`InstructionKind::SkippedAgent`] is
/// what `init` reports; `migrate` warns on every kind because knope still reads
/// the directory. [`InstructionKind::AgentCaseVariant`] is a bump file, not a skip.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InstructionKind {
    /// `README.md` in any case. Skipped by oakum and `@changesets/read` v3;
    /// fatal to knope. `init` writes this file, so it does not report it.
    Readme,
    /// Exact `AGENTS.md` / `CLAUDE.md` / `GEMINI.md`. Skipped by oakum and
    /// `@changesets/read` v3; fatal to knope.
    SkippedAgent,
    /// Case variant of those three with a lowercase `.md` suffix (`agents.md`).
    /// Every reader parses it as a bump file; a body without front matter aborts
    /// knope and `@changesets/cli`. Names whose suffix is not `.md` (`AGENTS.MD`)
    /// are not this kind: those readers ignore them.
    AgentCaseVariant,
}

/// A `.changeset/` listing name classified by [`classify_instruction_name`].
///
/// Fields are private so a caller cannot pair `SkippedAgent` with a bump-file
/// name. The only public constructor is [`instruction_occupants`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InstructionOccupant {
    file_name: String,
    kind: InstructionKind,
}

impl InstructionKind {
    /// `init` reports exact agent skip names and continues. README is the file
    /// `init` writes; case variants are bump files, not instruction files.
    #[must_use]
    pub fn reported_by_init(self) -> bool {
        matches!(self, Self::SkippedAgent)
    }
}

impl InstructionOccupant {
    fn from_name(file_name: &str) -> Option<Self> {
        classify_instruction_name(file_name).map(|kind| Self {
            file_name: String::from(file_name),
            kind,
        })
    }

    #[must_use]
    pub fn file_name(&self) -> &str {
        &self.file_name
    }

    #[must_use]
    pub fn kind(&self) -> InstructionKind {
        self.kind
    }

    /// Line `init` prints, if this occupant is in init's report set.
    #[must_use]
    pub fn init_message(&self) -> Option<String> {
        debug_assert_eq!(classify_instruction_name(&self.file_name), Some(self.kind));
        if !self.kind.reported_by_init() {
            return None;
        }
        Some(alloc::format!(
            "`{}` is an instruction file, not a bump file; oakum skips it. Notes in `.changeset/` need a different name. A lowercase variant would be parsed as a bump file.",
            self.file_name
        ))
    }

    /// Line `migrate` prints. Never a hard error.
    #[must_use]
    pub fn migrate_message(&self) -> String {
        debug_assert_eq!(classify_instruction_name(&self.file_name), Some(self.kind));
        match self.kind {
            InstructionKind::Readme => alloc::format!(
                "`{}` in `.changeset/` is not a bump file: oakum and @changesets/cli v3 skip it; knope would abort on it.",
                self.file_name
            ),
            InstructionKind::SkippedAgent => alloc::format!(
                "`{}` aborts knope; @changesets/cli v3 skips it. Oakum skips it too.",
                self.file_name
            ),
            InstructionKind::AgentCaseVariant => alloc::format!(
                "`{}` is not on the skip list; knope and @changesets/cli parse it as a bump file and abort if it has no front matter.",
                self.file_name
            ),
        }
    }
}

/// Classify a `.changeset/` listing name against the instruction skip list.
///
/// Path separators yield `None`: callers pass directory entry names, not paths.
/// A suffix other than lowercase `.md` is also `None`: knope and `@changesets/read`
/// ignore those names, so migrate must not warn as if they were bump files.
#[must_use]
pub fn classify_instruction_name(file_name: &str) -> Option<InstructionKind> {
    if file_name.contains('/') || file_name.contains('\\') {
        return None;
    }
    if !lowercase_md_suffix(file_name) {
        return None;
    }
    if file_name.eq_ignore_ascii_case("README.md") {
        return Some(InstructionKind::Readme);
    }
    if EXACT_SKIP.contains(&file_name) {
        return Some(InstructionKind::SkippedAgent);
    }
    if EXACT_SKIP
        .iter()
        .any(|skip| file_name.eq_ignore_ascii_case(skip))
    {
        return Some(InstructionKind::AgentCaseVariant);
    }
    None
}

/// Occupants in listing order. Names `classify_instruction_name` ignores are omitted.
#[must_use]
pub fn instruction_occupants<'a, I>(names: I) -> Vec<InstructionOccupant>
where
    I: IntoIterator<Item = &'a str>,
{
    names
        .into_iter()
        .filter_map(InstructionOccupant::from_name)
        .collect()
}

/// Whether a `.changeset/` listing contains any bump file (`okm-3a3`).
///
/// Instruction skip names do not count, so `AGENTS.md` alone is not a migrate.
#[must_use]
pub fn listing_contains_bump_file<'a, I>(names: I) -> bool
where
    I: IntoIterator<Item = &'a str>,
{
    names.into_iter().any(is_bump_file_name)
}

/// Why a bump-file body could not become a planner [`BumpFile`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LoadError {
    Malformed(MalformedBumpFile),
    UnknownPackage(UnknownPackage),
}

impl fmt::Display for LoadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Malformed(err) => write!(f, "{err}"),
            Self::UnknownPackage(err) => write!(f, "{err}"),
        }
    }
}

impl core::error::Error for LoadError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Malformed(err) => Some(&err.error),
            Self::UnknownPackage(err) => Some(err),
        }
    }
}

/// Why a frontmatter key did not resolve to exactly one workspace package.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnknownReason {
    /// No package with this name.
    Missing,
    /// More than one package shares the name (typically across ecosystems).
    Ambiguous,
}

/// A frontmatter key that is not exactly one package in the workspace.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnknownPackage {
    pub file: String,
    pub name: String,
    pub reason: UnknownReason,
}

impl fmt::Display for UnknownPackage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.reason {
            UnknownReason::Missing => write!(
                f,
                "bump file `{}` names package `{}`, which is not in the workspace; if it was removed, its tags stay as history: delete its line from the file, or the file when it names nothing else",
                self.file, self.name
            ),
            UnknownReason::Ambiguous => write!(
                f,
                "bump file `{}` names package `{}`, which matches more than one workspace package",
                self.file, self.name
            ),
        }
    }
}

impl core::error::Error for UnknownPackage {}

/// Hard failure from [`load_bump_files`]: an unknown package, plus every
/// malformed candidate seen in the same pass (so soft failures are not dropped).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LoadAbort {
    pub unknown: UnknownPackage,
    pub malformed: Vec<MalformedBumpFile>,
}

impl fmt::Display for LoadAbort {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.unknown)?;
        for report in &self.malformed {
            write!(f, "; also {report}")?;
        }
        Ok(())
    }
}

impl core::error::Error for LoadAbort {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        Some(&self.unknown)
    }
}

/// A candidate whose body failed the intersection grammar. Collected rather
/// than dropped; every command refuses on the list.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MalformedBumpFile {
    pub file: String,
    pub error: ParseError,
}

impl fmt::Display for MalformedBumpFile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "`{}` is not a bump file: {}", self.file, self.error)
    }
}

/// Result of loading every bump-file candidate from already-read bodies.
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use]
pub struct LoadedBumpFiles {
    pub files: Vec<BumpFile>,
    pub malformed: Vec<MalformedBumpFile>,
}

/// Parse `body`, resolve package names against `workspace`, and build a
/// [`BumpFile`] whose `id` is `file_name`.
///
/// # Errors
///
/// [`LoadError::Malformed`] when the body is outside the intersection grammar
/// (always includes `file_name`). [`LoadError::UnknownPackage`] when a key is
/// missing from the workspace or matches more than one package.
pub fn resolve_bump_file(
    file_name: impl Into<String>,
    body: &str,
    workspace: &Workspace,
) -> Result<BumpFile, LoadError> {
    let file_name = file_name.into();
    let change = parse(body).map_err(|error| {
        LoadError::Malformed(MalformedBumpFile {
            file: file_name.clone(),
            error,
        })
    })?;
    let mut entries = Vec::with_capacity(change.entries().len());
    for (name, level) in change.entries() {
        let id = match resolve_package_name(name, workspace) {
            Ok(id) => id,
            Err(reason) => {
                return Err(LoadError::UnknownPackage(UnknownPackage {
                    file: file_name,
                    name: String::from(name),
                    reason,
                }));
            }
        };
        entries.push((id, *level));
    }
    Ok(BumpFile {
        id: file_name,
        entries,
        note: String::from(change.note()),
    })
}

/// Apply reading rules to `(file_name, body)` pairs already loaded from disk.
///
/// Non-candidates (wrong extension, nested paths, instruction skips) are
/// ignored. Malformed bodies are collected for the caller to refuse, after the
/// full pass so one refusal names them all. Unknown package names abort the
/// load after the full pass, retaining every malformed report.
///
/// # Errors
///
/// Returns [`LoadAbort`] when any candidate names a package absent from or
/// ambiguous in `workspace`.
pub fn load_bump_files<'a>(
    files: impl IntoIterator<Item = (&'a str, &'a str)>,
    workspace: &Workspace,
) -> Result<LoadedBumpFiles, LoadAbort> {
    let mut loaded = Vec::new();
    let mut malformed = Vec::new();
    let mut unknown = None;
    for (file_name, body) in files {
        if !is_bump_file_name(file_name) {
            continue;
        }
        match resolve_bump_file(file_name, body, workspace) {
            Ok(file) => {
                if unknown.is_none() {
                    loaded.push(file);
                }
            }
            Err(LoadError::Malformed(report)) => malformed.push(report),
            Err(LoadError::UnknownPackage(err)) => {
                if unknown.is_none() {
                    unknown = Some(err);
                }
            }
        }
    }
    if let Some(unknown) = unknown {
        return Err(LoadAbort { unknown, malformed });
    }
    Ok(LoadedBumpFiles {
        files: loaded,
        malformed,
    })
}

/// Migration bump file: missing names kept; ambiguous names refuse.
///
/// Missing names are omitted from [`Self::bump_file`]. Construct only via
/// [`resolve_migration_change`] / [`resolve_migration_bump_file`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MigrationBumpFile {
    id: String,
    change: ChangeFile,
    known: Vec<(PackageId, BumpLevel)>,
    unknown_missing: Vec<String>,
}

impl MigrationBumpFile {
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }

    #[must_use]
    pub const fn change(&self) -> &ChangeFile {
        &self.change
    }

    #[must_use]
    pub fn unknown_missing(&self) -> &[String] {
        &self.unknown_missing
    }

    /// Known packages only for compose/aggregate (missing names omitted; empty if all missing).
    ///
    /// [`Self::change`] keeps the full parse for rewrite/display.
    #[must_use]
    pub fn bump_file(&self) -> BumpFile {
        BumpFile {
            id: self.id.clone(),
            entries: self.known.clone(),
            note: String::from(self.change.note()),
        }
    }
}

/// Migration load result: missing packages collected; ambiguous aborts.
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use]
pub struct LoadedMigrationFiles {
    files: Vec<MigrationBumpFile>,
    malformed: Vec<MalformedBumpFile>,
}

impl LoadedMigrationFiles {
    #[must_use]
    pub fn files(&self) -> &[MigrationBumpFile] {
        &self.files
    }

    #[must_use]
    pub fn malformed(&self) -> &[MalformedBumpFile] {
        &self.malformed
    }

    #[must_use]
    pub fn bump_files(&self) -> Vec<BumpFile> {
        self.files
            .iter()
            .map(MigrationBumpFile::bump_file)
            .collect()
    }

    /// `(file id, package name)` pairs for missing packages.
    #[must_use]
    pub fn unknown_missing(&self) -> Vec<(String, String)> {
        self.files
            .iter()
            .flat_map(|file| {
                file.unknown_missing
                    .iter()
                    .map(|name| (file.id.clone(), name.clone()))
            })
            .collect()
    }
}

/// Hard failure from [`load_migration_bump_files`]: ambiguous package, plus malformed reports.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MigrationLoadAbort {
    ambiguous: UnknownPackage,
    malformed: Vec<MalformedBumpFile>,
}

impl MigrationLoadAbort {
    #[must_use]
    pub const fn ambiguous(&self) -> &UnknownPackage {
        &self.ambiguous
    }

    #[must_use]
    pub fn malformed(&self) -> &[MalformedBumpFile] {
        &self.malformed
    }
}

impl fmt::Display for MigrationLoadAbort {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.ambiguous)?;
        for report in &self.malformed {
            write!(f, "; also {report}")?;
        }
        Ok(())
    }
}

impl core::error::Error for MigrationLoadAbort {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        Some(&self.ambiguous)
    }
}

/// # Errors
///
/// [`LoadError::Malformed`] when the body is outside the migration grammar.
/// [`LoadError::UnknownPackage`] only for [`UnknownReason::Ambiguous`].
pub fn resolve_migration_bump_file(
    file_name: impl Into<String>,
    body: &str,
    workspace: &Workspace,
) -> Result<MigrationBumpFile, LoadError> {
    let file_name = file_name.into();
    let change = parse_migration(body).map_err(|error| {
        LoadError::Malformed(MalformedBumpFile {
            file: file_name.clone(),
            error,
        })
    })?;
    resolve_migration_change(file_name, change, workspace)
}

/// # Errors
///
/// [`LoadError::UnknownPackage`] only for [`UnknownReason::Ambiguous`].
/// Successful results partition frontmatter names: `|entries| = |known| + |unknown_missing|`.
pub fn resolve_migration_change(
    file_name: impl Into<String>,
    change: ChangeFile,
    workspace: &Workspace,
) -> Result<MigrationBumpFile, LoadError> {
    let file_name = file_name.into();
    let mut known = Vec::with_capacity(change.entries().len());
    let mut unknown_missing = Vec::new();
    for (name, level) in change.entries() {
        match resolve_package_name(name, workspace) {
            Ok(id) => known.push((id, *level)),
            Err(UnknownReason::Missing) => unknown_missing.push(name.clone()),
            Err(UnknownReason::Ambiguous) => {
                return Err(LoadError::UnknownPackage(UnknownPackage {
                    file: file_name,
                    name: String::from(name),
                    reason: UnknownReason::Ambiguous,
                }));
            }
        }
    }
    Ok(MigrationBumpFile {
        id: file_name,
        change,
        known,
        unknown_missing,
    })
}

/// Load migration bump-file candidates. Missing packages are collected; only
/// ambiguous names abort.
///
/// Uses [`parse_migration`] (quoted unscoped keys accepted). Keys may be bare
/// names or paths; candidacy checks the final segment via [`is_bump_file_name`],
/// and the key is kept as the file id. Malformed bodies go into
/// [`LoadedMigrationFiles::malformed`]; the caller refuses on that list before
/// composing.
///
/// # Errors
///
/// Returns [`MigrationLoadAbort`] when any candidate names an ambiguous package.
pub fn load_migration_bump_files<'a>(
    files: impl IntoIterator<Item = (&'a str, &'a str)>,
    workspace: &Workspace,
) -> Result<LoadedMigrationFiles, MigrationLoadAbort> {
    let mut loaded = Vec::new();
    let mut malformed = Vec::new();
    let mut ambiguous = None;
    for (file_name, body) in files {
        let base = file_name.rsplit(['/', '\\']).next().unwrap_or(file_name);
        if !is_bump_file_name(base) {
            continue;
        }
        match resolve_migration_bump_file(file_name, body, workspace) {
            Ok(file) => {
                if ambiguous.is_none() {
                    loaded.push(file);
                }
            }
            Err(LoadError::Malformed(report)) => malformed.push(report),
            Err(LoadError::UnknownPackage(err)) => {
                debug_assert_eq!(err.reason, UnknownReason::Ambiguous);
                if ambiguous.is_none() {
                    ambiguous = Some(err);
                }
            }
        }
    }
    if let Some(ambiguous) = ambiguous {
        return Err(MigrationLoadAbort {
            ambiguous,
            malformed,
        });
    }
    Ok(LoadedMigrationFiles {
        files: loaded,
        malformed,
    })
}

/// Resolve a frontmatter name to exactly one [`PackageId`].
///
/// # Errors
///
/// [`UnknownReason::Missing`] when no package has that name;
/// [`UnknownReason::Ambiguous`] when more than one does.
pub fn resolve_package_name(name: &str, workspace: &Workspace) -> Result<PackageId, UnknownReason> {
    let mut matches = workspace
        .packages()
        .filter(|pkg| pkg.id().name == name)
        .map(|pkg| pkg.id().clone());
    let Some(first) = matches.next() else {
        return Err(UnknownReason::Missing);
    };
    match matches.next() {
        Some(_) => Err(UnknownReason::Ambiguous),
        None => Ok(first),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plan::{
        BumpLevel, Ecosystem, Package, PackageId, ResolvesDependenciesAt, Workspace,
    };
    use alloc::string::ToString;
    use alloc::vec;
    use semver::Version;

    fn cargo_pkg(name: &str) -> Package {
        Package::new(
            PackageId::new(Ecosystem::Cargo, name),
            Version::new(0, 1, 0),
            ResolvesDependenciesAt::Install,
            true,
            vec![],
        )
    }

    fn workspace(packages: Vec<Package>) -> Workspace {
        Workspace::new(packages).expect("workspace")
    }

    #[test]
    fn skip_list_matches_changesets_read_v3_asymmetry() {
        assert!(skipped_instruction_name("README.md"));
        assert!(skipped_instruction_name("readme.md"));
        assert!(skipped_instruction_name("ReadMe.MD"));
        assert!(skipped_instruction_name("AGENTS.md"));
        assert!(skipped_instruction_name("CLAUDE.md"));
        assert!(skipped_instruction_name("GEMINI.md"));
        assert!(!skipped_instruction_name("agents.md"));
        assert!(!skipped_instruction_name("claude.md"));
        assert!(!skipped_instruction_name("Claude.md"));
        assert!(!skipped_instruction_name("AGENTS.MD"));
        assert!(!skipped_instruction_name("gemini.md"));
        assert!(!skipped_instruction_name("change.md"));
        assert!(!is_bump_file_name("AGENTS.md"));
        assert!(is_bump_file_name("Claude.md"));
    }

    #[test]
    fn bump_file_name_requires_md_suffix_case_sensitive() {
        assert!(is_bump_file_name("feat.md"));
        assert!(!is_bump_file_name("feat.MD"));
        assert!(!is_bump_file_name("feat.Md"));
        assert!(!is_bump_file_name("_config.toml"));
        assert!(!is_bump_file_name("README.md"));
        assert!(!is_bump_file_name("nested/change.md"));
        assert!(!is_bump_file_name("nested\\change.md"));
        assert!(is_bump_file_name("agents.md"));
    }

    #[test]
    fn classify_splits_skip_readme_agent_and_case_variant() {
        assert_eq!(
            classify_instruction_name("README.md"),
            Some(InstructionKind::Readme)
        );
        assert_eq!(
            classify_instruction_name("readme.md"),
            Some(InstructionKind::Readme)
        );
        assert_eq!(
            classify_instruction_name("AGENTS.md"),
            Some(InstructionKind::SkippedAgent)
        );
        assert_eq!(
            classify_instruction_name("CLAUDE.md"),
            Some(InstructionKind::SkippedAgent)
        );
        assert_eq!(
            classify_instruction_name("GEMINI.md"),
            Some(InstructionKind::SkippedAgent)
        );
        assert_eq!(
            classify_instruction_name("agents.md"),
            Some(InstructionKind::AgentCaseVariant)
        );
        assert_eq!(
            classify_instruction_name("claude.md"),
            Some(InstructionKind::AgentCaseVariant)
        );
        assert_eq!(
            classify_instruction_name("gemini.md"),
            Some(InstructionKind::AgentCaseVariant)
        );
        assert_eq!(
            classify_instruction_name("Claude.md"),
            Some(InstructionKind::AgentCaseVariant)
        );
        assert_eq!(classify_instruction_name("AGENTS.MD"), None);
        assert_eq!(classify_instruction_name("README.MD"), None);
        assert_eq!(classify_instruction_name("change.md"), None);
        assert_eq!(classify_instruction_name("nested/AGENTS.md"), None);
        assert!(InstructionKind::SkippedAgent.reported_by_init());
        assert!(!InstructionKind::Readme.reported_by_init());
        assert!(!InstructionKind::AgentCaseVariant.reported_by_init());
    }

    #[test]
    fn occupants_preserve_order_and_omit_unclassified_names() {
        let found = instruction_occupants([
            "feat.md",
            "AGENTS.md",
            "CLAUDE.md",
            "GEMINI.md",
            "readme.md",
            "agents.md",
            "AGENTS.MD",
            "_config.toml",
        ]);
        assert_eq!(
            found
                .iter()
                .map(|o| (o.file_name(), o.kind()))
                .collect::<Vec<_>>(),
            vec![
                ("AGENTS.md", InstructionKind::SkippedAgent),
                ("CLAUDE.md", InstructionKind::SkippedAgent),
                ("GEMINI.md", InstructionKind::SkippedAgent),
                ("readme.md", InstructionKind::Readme),
                ("agents.md", InstructionKind::AgentCaseVariant),
            ]
        );
        let agents_init = found[0].init_message().expect("AGENTS.md init");
        assert!(
            agents_init.contains("`AGENTS.md`") && agents_init.contains("oakum skips it"),
            "{agents_init}"
        );
        assert!(found[1].init_message().is_some());
        assert!(found[2].init_message().is_some());
        assert!(found[3].init_message().is_none());
        assert!(found[4].init_message().is_none());
        let agents_migrate = found[0].migrate_message();
        let readme_migrate = found[3].migrate_message();
        let variant_migrate = found[4].migrate_message();
        assert!(
            agents_migrate.contains("Oakum skips it too")
                && agents_migrate.contains("@changesets/cli v3 skips it"),
            "{agents_migrate}"
        );
        assert!(
            readme_migrate.contains("is not a bump file: oakum and @changesets/cli v3 skip it")
                && !readme_migrate.contains("left in place"),
            "{readme_migrate}"
        );
        assert!(
            variant_migrate.contains("not on the skip list")
                && variant_migrate.contains("no front matter"),
            "{variant_migrate}"
        );
    }

    #[test]
    fn listing_skip_names_alone_are_not_bump_files() {
        assert!(!listing_contains_bump_file([
            "AGENTS.md",
            "CLAUDE.md",
            "GEMINI.md",
            "README.md",
            "readme.md",
        ]));
        assert!(listing_contains_bump_file(["AGENTS.md", "agents.md"]));
        assert!(listing_contains_bump_file(["feat.md"]));
    }

    #[test]
    fn resolve_maps_names_and_rejects_unknown() {
        let ws = workspace(vec![cargo_pkg("core"), cargo_pkg("utils")]);
        let body = "---\ncore: minor\nutils: patch\n---\nnote\n";
        let file = resolve_bump_file("change.md", body, &ws).expect("resolve");
        assert_eq!(file.id, "change.md");
        assert_eq!(file.note, "note\n");
        assert_eq!(
            file.entries,
            vec![
                (PackageId::new(Ecosystem::Cargo, "core"), BumpLevel::Minor),
                (PackageId::new(Ecosystem::Cargo, "utils"), BumpLevel::Patch),
            ]
        );

        let err = resolve_bump_file("bad.md", "---\nmissing: patch\n---\n", &ws).unwrap_err();
        assert_eq!(
            err,
            LoadError::UnknownPackage(UnknownPackage {
                file: "bad.md".to_string(),
                name: "missing".to_string(),
                reason: UnknownReason::Missing,
            })
        );
    }

    #[test]
    fn resolve_reports_first_unknown_name_in_file() {
        let ws = workspace(vec![cargo_pkg("core")]);
        let err =
            resolve_bump_file("x.md", "---\ncore: patch\nmissing: minor\n---\n", &ws).unwrap_err();
        assert_eq!(
            err,
            LoadError::UnknownPackage(UnknownPackage {
                file: "x.md".to_string(),
                name: "missing".to_string(),
                reason: UnknownReason::Missing,
            })
        );
    }

    #[test]
    fn resolve_surfaces_malformed_with_file_name() {
        let ws = workspace(vec![cargo_pkg("core")]);
        let err = resolve_bump_file("b.md", "preamble\n---\ncore: patch\n---\n", &ws).unwrap_err();
        match err {
            LoadError::Malformed(report) => {
                assert_eq!(report.file, "b.md");
                assert!(report.to_string().contains("b.md"));
            }
            LoadError::UnknownPackage(_) => panic!("expected malformed"),
        }
    }

    #[test]
    fn load_empty_or_all_skipped_is_ok() {
        let ws = workspace(vec![cargo_pkg("core")]);
        let empty = load_bump_files([], &ws).expect("empty");
        assert!(empty.files.is_empty() && empty.malformed.is_empty());
        let skipped =
            load_bump_files([("README.md", "---\ncore: patch\n---\n")], &ws).expect("skip");
        assert!(skipped.files.is_empty() && skipped.malformed.is_empty());
    }

    #[test]
    fn load_skips_instruction_and_non_md_and_continues_past_malformed() {
        let ws = workspace(vec![cargo_pkg("core")]);
        let good = "---\ncore: patch\n---\n";
        let bad = "preamble\n---\ncore: patch\n---\n";
        let loaded = load_bump_files(
            [
                ("README.md", good),
                ("AGENTS.md", good),
                ("CLAUDE.md", good),
                ("GEMINI.md", good),
                ("_config.toml", good),
                ("nested/x.md", good),
                ("broken.md", bad),
                ("ok.md", good),
            ],
            &ws,
        )
        .expect("load");
        assert_eq!(loaded.files.len(), 1);
        assert_eq!(loaded.files[0].id, "ok.md");
        assert_eq!(loaded.malformed.len(), 1);
        assert_eq!(loaded.malformed[0].file, "broken.md");
    }

    #[test]
    fn load_aborts_on_unknown_package() {
        let ws = workspace(vec![cargo_pkg("core")]);
        let err = load_bump_files([("x.md", "---\nnope: patch\n---\n")], &ws).unwrap_err();
        assert_eq!(err.unknown.name, "nope");
        assert_eq!(err.unknown.file, "x.md");
        assert_eq!(err.unknown.reason, UnknownReason::Missing);
        assert!(err.malformed.is_empty(), "{:?}", err.malformed);
    }

    #[test]
    fn load_aborts_on_unknown_even_after_a_good_file_and_keeps_malformed() {
        let ws = workspace(vec![cargo_pkg("core")]);
        let err = load_bump_files(
            [
                ("ok.md", "---\ncore: patch\n---\n"),
                ("broken.md", "preamble\n---\ncore: patch\n---\n"),
                ("bad.md", "---\nnope: patch\n---\n"),
            ],
            &ws,
        )
        .unwrap_err();
        assert_eq!(err.unknown.file, "bad.md");
        assert_eq!(err.malformed.len(), 1);
        assert_eq!(err.malformed[0].file, "broken.md");
        let shown = err.to_string();
        assert!(shown.contains("bad.md") && shown.contains("broken.md"));
    }

    #[test]
    fn unknown_package_display_names_file_and_package() {
        let err = UnknownPackage {
            file: "x.md".into(),
            name: "nope".into(),
            reason: UnknownReason::Missing,
        };
        let s = err.to_string();
        assert!(s.contains("x.md") && s.contains("nope"));
    }

    #[test]
    fn ambiguous_name_across_ecosystems_is_unknown() {
        let ws = workspace(vec![
            cargo_pkg("core"),
            Package::new(
                PackageId::new(Ecosystem::Npm, "core"),
                Version::new(1, 0, 0),
                ResolvesDependenciesAt::Install,
                true,
                vec![],
            ),
        ]);
        let err = resolve_bump_file("x.md", "---\ncore: patch\n---\n", &ws).unwrap_err();
        assert_eq!(
            err,
            LoadError::UnknownPackage(UnknownPackage {
                file: "x.md".to_string(),
                name: "core".to_string(),
                reason: UnknownReason::Ambiguous,
            })
        );
    }

    #[test]
    fn migration_load_collects_missing_and_keeps_known() {
        let ws = workspace(vec![cargo_pkg("core")]);
        let loaded = load_migration_bump_files(
            [
                (
                    "feat.md",
                    "---\n\"core\": minor\nmissing: patch\n---\nnote\n",
                ),
                ("README.md", "---\ncore: patch\n---\n"),
            ],
            &ws,
        )
        .expect("load");
        assert_eq!(loaded.files().len(), 1);
        assert_eq!(
            loaded.unknown_missing(),
            vec![("feat.md".into(), "missing".into())]
        );
        let bump = loaded.bump_files();
        assert_eq!(bump.len(), 1);
        assert_eq!(
            bump[0].entries,
            vec![(PackageId::new(Ecosystem::Cargo, "core"), BumpLevel::Minor)]
        );
        assert_eq!(
            loaded.files()[0].change().entries(),
            &[
                ("core".into(), BumpLevel::Minor),
                ("missing".into(), BumpLevel::Patch),
            ]
        );
    }

    #[test]
    fn migration_load_keeps_known_independently() {
        let ws = workspace(vec![cargo_pkg("core")]);
        let loaded = load_migration_bump_files([("feat.md", "---\n\"core\": minor\n---\n")], &ws)
            .expect("load");
        assert!(
            loaded.unknown_missing().is_empty(),
            "{:?}",
            loaded.unknown_missing()
        );
        assert_eq!(
            loaded.bump_files()[0].entries,
            vec![(PackageId::new(Ecosystem::Cargo, "core"), BumpLevel::Minor)]
        );
    }

    #[test]
    fn migration_load_skips_malformed_and_aborts_ambiguous_with_malformed() {
        let ws = workspace(vec![
            cargo_pkg("core"),
            Package::new(
                PackageId::new(Ecosystem::Npm, "core"),
                Version::new(1, 0, 0),
                ResolvesDependenciesAt::Install,
                true,
                vec![],
            ),
        ]);
        let err = load_migration_bump_files(
            [
                ("broken.md", "not a bump file"),
                ("x.md", "---\ncore: patch\n---\n"),
            ],
            &ws,
        )
        .unwrap_err();
        assert_eq!(err.ambiguous().reason, UnknownReason::Ambiguous);
        assert_eq!(err.malformed().len(), 1);
        assert_eq!(err.malformed()[0].file, "broken.md");
    }

    #[test]
    fn migration_load_aborts_on_ambiguous() {
        let ws = workspace(vec![
            cargo_pkg("core"),
            Package::new(
                PackageId::new(Ecosystem::Npm, "core"),
                Version::new(1, 0, 0),
                ResolvesDependenciesAt::Install,
                true,
                vec![],
            ),
        ]);
        let err =
            load_migration_bump_files([("x.md", "---\ncore: patch\n---\n")], &ws).unwrap_err();
        assert_eq!(err.ambiguous().reason, UnknownReason::Ambiguous);
        assert_eq!(err.ambiguous().name, "core");
    }

    #[test]
    fn migration_load_accepts_path_keys_as_ids() {
        let ws = workspace(vec![cargo_pkg("core")]);
        let loaded =
            load_migration_bump_files([(".changeset/feat.md", "---\ncore: minor\n---\n")], &ws)
                .expect("path key");
        assert_eq!(loaded.malformed(), []);
        assert_eq!(loaded.files().len(), 1);
        assert_eq!(loaded.files()[0].id(), ".changeset/feat.md");
    }
}