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
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
//! Shared `_config.toml` load for CLI commands.

use std::collections::BTreeSet;
use std::io::{self, Read};
use std::path::{Path, PathBuf};

use cap_std::fs::{Dir, File};
use oakum::config::{self, OakumConfig};
use oakum::plan::{BumpLevel, PackageId};
use oakum::state::UnresolvedScope;

use super::coverage::Standing;
use super::fs::{open_read_only, resolve_capability_path};
use super::repository::Repository;
use super::CliError;

pub(super) const CONFIG_PATH: &str = ".changeset/_config.toml";

/// Both keys that could manage the package, in one voice: `status` and `check`
/// meet this state on different paths and must name the same fix.
pub(super) const UNMANAGED_FIX: &str =
    "adjust `include`/`exclude` or set `private-packages.version = true`";

/// Written three times otherwise — by `status` composing a plan, and by `check`
/// printing and then returning the same refusal.
pub(super) fn intent_names_unmanaged(name: &str) -> String {
    format!("`{name}` is named by intent but is not version-managed; {UNMANAGED_FIX}")
}

/// Said by `check` and `version` alike, so the two cannot describe it differently.
pub(super) fn named_by_a_commit(id: &PackageId) -> String {
    format!("{id}: named by a commit but not version-managed; {UNMANAGED_FIX}")
}

/// Said by `status`, `check`, `version` and `generate` alike.
pub(super) fn unresolved_scope_line(unresolved: &UnresolvedScope) -> String {
    let short = unresolved.commit.get(..7).unwrap_or(&unresolved.commit);
    format!(
        "commit {short} asks for a release under scope {}, which names no workspace package, so nothing releases from it; a scope names one package",
        code_span(&unresolved.scope)
    )
}

/// The scope is commit text, and the line reaches a pull-request comment: a
/// backtick in it must not close the span and render the rest as Markdown.
fn code_span(text: &str) -> String {
    let longest = text.split(|c| c != '`').map(str::len).max().unwrap_or(0);
    let fence = "`".repeat(longest + 1);
    let pad = if text.starts_with('`') || text.ends_with('`') {
        " "
    } else {
        ""
    };
    format!("{fence}{pad}{text}{pad}{fence}")
}

/// Stderr line for the readers that keep their defaults (ADR-0007).
pub(super) const DEFAULTS_NOTE: &str =
    "`.changeset/_config.toml` not found; defaults in effect (run `oakum init` or `oakum migrate`)";

/// Stderr line for a config that still carries the retired key (ADR-0038).
const TOOL_VERSION_NOTE: &str =
    "`.changeset/_config.toml` sets `tool-version`, which oakum no longer reads; run `oakum upgrade` to remove it";

/// Said by `check` when it refuses, and by `init` when it has just written a
/// config in that state. One string so the warning and the refusal cannot
/// describe the same condition differently.
pub(super) const ALL_PRIVATE_GUIDANCE: &str =
    "every selected package is private, so no plan can name one and a release \
     would do nothing; set `private-packages.version = true` to version them, \
     and `private-packages.tag = true` to tag them";

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct LoadedConfig {
    inner: OakumConfig,
    /// No `_config.toml`; defaults stand in. ADR-0007 decides which commands
    /// refuse that state.
    from_defaults: bool,
    /// The file's `#:schema` line names the committed `_schema.json`, which
    /// decides whether `check` reports a missing one. Kept from the one read
    /// so `check` does not reread the config to learn it.
    names_committed_schema: bool,
}

/// The parsed config, plus what the CLI learned reading it.
impl std::ops::Deref for LoadedConfig {
    type Target = OakumConfig;

    fn deref(&self) -> &OakumConfig {
        &self.inner
    }
}

/// What feeds the plan (ADR-0029 single-artifact table).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PlanIntentSource {
    ChangeFiles,
    /// Commit-derived intent; never writes a bump file.
    CommitsOnly,
}

impl LoadedConfig {
    /// ADR-0029: `generate` needs both mechanisms enabled.
    pub(super) fn generate_allowed(&self) -> bool {
        self.inner.change_files() && self.inner.conventional_commits()
    }

    /// ADR-0029 plan input.
    ///
    /// # Errors
    ///
    /// When both `change-files` and `conventional-commits` are disabled.
    pub(super) fn plan_intent_source(&self) -> Result<PlanIntentSource, CliError> {
        match (self.inner.change_files(), self.inner.conventional_commits()) {
            (true, _) => Ok(PlanIntentSource::ChangeFiles),
            (false, true) => Ok(PlanIntentSource::CommitsOnly),
            (false, false) => Err(CliError::new(
                "both `change-files` and `conventional-commits` are disabled; enable one so the plan has intent to read (ADR-0019 / ADR-0029)",
            )),
        }
    }

    pub(super) fn is_default(&self) -> bool {
        self.from_defaults
    }

    /// `text` is what `inner` was parsed from, so the `#:schema` line is read
    /// from the same bytes; empty for defaults that no file holds.
    pub(super) fn from_parsed(
        repo: &Repository,
        inner: OakumConfig,
        text: &str,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        contain_template_sources(repo, &inner)?;
        warn_deprecated_keys(&inner);
        Ok(Self {
            inner,
            from_defaults: false,
            names_committed_schema: config::names_committed_schema(text),
        })
    }

    pub(super) fn names_committed_schema(&self) -> bool {
        self.names_committed_schema
    }

    /// Whether a bump-file entry is one `status` and `version` refuse while
    /// planning (`compose_managed`): a release for a package this config does
    /// not version, an excluded one included. `none` plans no change, so it
    /// passes. Must agree with the closure `status` and `version` hand
    /// `compose_managed`, which does not call this.
    pub(super) fn refuses_intent(
        &self,
        workspace: &oakum::plan::Workspace,
        id: &PackageId,
        level: BumpLevel,
    ) -> bool {
        level != BumpLevel::None
            && workspace
                .get(id)
                .is_some_and(|package| !self.version_managed(package))
    }

    /// [`OakumConfig::version_managed`] ANDs the written decision with the
    /// derived one, so it cannot tell an exclusion someone wrote from an opt-in
    /// nobody set.
    pub(super) fn standing(&self, package: &oakum::plan::Package) -> Standing {
        if self.version_managed(package) {
            Standing::Managed
        } else if self.selected(&package.id().name) {
            Standing::Unmanaged
        } else {
            Standing::Excluded
        }
    }

    pub(super) fn validate_selection_names<'a>(
        &self,
        known: impl IntoIterator<Item = &'a str>,
    ) -> Result<(), CliError> {
        self.inner
            .validate_selection_names(known)
            .map_err(|err| CliError::new(err.to_string()))
    }

    /// Every command that reads the selection refuses one naming no package,
    /// and names the file and the packages there are to choose from.
    pub(super) fn validate_workspace_selection(
        &self,
        workspace: &oakum::plan::Workspace,
    ) -> Result<(), CliError> {
        let names: BTreeSet<&str> = workspace
            .packages()
            .map(|package| package.id().name.as_str())
            .collect();
        self.validate_selection_names(names.iter().copied())
            .map_err(|err| {
                let found = names
                    .iter()
                    .take(NAMES_SHOWN)
                    .copied()
                    .collect::<Vec<_>>()
                    .join(", ");
                let more = match names.len().saturating_sub(NAMES_SHOWN) {
                    0 => String::new(),
                    rest => format!(" … and {rest} more"),
                };
                err.recast(format!(
                    "{err} in `{CONFIG_PATH}`; the workspace has: {found}{more}. A removed package needs no entry, since its tags are read as history: delete the name"
                ))
            })
    }
}

/// A large monorepo's package list must not bury the refusal it explains.
const NAMES_SHOWN: usize = 20;

/// Package ids that may own a bare tag / default write shape (ADR-0030).
pub(super) fn tag_managed_ids(
    workspace: &oakum::plan::Workspace,
    config: &LoadedConfig,
) -> BTreeSet<PackageId> {
    workspace
        .packages()
        .filter(|package| config.tag_managed(package))
        .map(|package| package.id().clone())
        .collect()
}

/// One line per read, appended to the file `OAKUM_TEST_CONFIG_READS` names,
/// so a test can count reads per run — `ci pr-status` read the config twice,
/// and nothing else could observe it. Debug builds only; the shipped binary
/// carries no hook.
#[cfg(debug_assertions)]
fn note_config_read() {
    use std::io::Write;
    let Ok(path) = std::env::var("OAKUM_TEST_CONFIG_READS") else {
        return;
    };
    if let Ok(mut log) = std::fs::OpenOptions::new()
        .append(true)
        .create(true)
        .open(path)
    {
        let _ = writeln!(log, "read");
    }
}

/// Missing `.changeset/_config.toml` → both intent mechanisms on.
pub(super) fn load_config(repo: &Repository) -> Result<LoadedConfig, Box<dyn std::error::Error>> {
    #[cfg(debug_assertions)]
    note_config_read();
    let Some(mut file) = open_config(repo.dir(), repo.path())? else {
        return Ok(LoadedConfig {
            inner: OakumConfig::defaults(),
            from_defaults: true,
            names_committed_schema: false,
        });
    };
    let mut text = String::new();
    file.read_to_string(&mut text)
        .map_err(|err| config_error(format!("failed to read `{CONFIG_PATH}`: {err}")))?;
    let inner = config::parse(&text).map_err(|err| {
        config_error(format!(
            "`{CONFIG_PATH}` is not a valid oakum config: {err}"
        ))
    })?;
    LoadedConfig::from_parsed(repo, inner, &text)
}

/// Once per process: `release` loads the config several times in one run.
fn warn_deprecated_keys(inner: &OakumConfig) {
    static WARNED: std::sync::Once = std::sync::Once::new();
    if inner.deprecated_tool_version() {
        WARNED.call_once(|| super::say_err(TOOL_VERSION_NOTE));
    }
}

/// A repository with no config has not adopted oakum; the writers refuse
/// rather than run on defaults.
///
/// # Errors
///
/// `unverified`, naming the file and the commands that write it.
pub(super) fn require_config(config: &LoadedConfig) -> Result<(), CliError> {
    if config.is_default() {
        return Err(CliError::unverified(format!(
            "unverified: `{CONFIG_PATH}` not found; run `oakum init` or `oakum migrate`"
        )));
    }
    Ok(())
}

pub(super) fn contain_template_sources(
    repo: &Repository,
    inner: &OakumConfig,
) -> Result<(), Box<dyn std::error::Error>> {
    for (key, source) in inner.template_sources() {
        super::template::load_template_body(repo.dir(), repo.path(), source)
            .map_err(|err| config_error(format!("{key}: {err}")))?;
    }
    Ok(())
}

fn open_config(dir: &Dir, repo_path: &Path) -> Result<Option<File>, Box<dyn std::error::Error>> {
    open_config_before_open(dir, repo_path, || {})
}

/// Raw config text plus capability-resolved write targets for `upgrade`
/// (ADR-0023). `init` writes the same filenames through the repository `Dir`.
/// Resolution shares the read path's containment rules, so a symlinked
/// config cannot redirect the write outside the repository.
pub(super) struct ConfigSource {
    text: String,
    changeset_path: PathBuf,
    config_path: PathBuf,
}

impl ConfigSource {
    pub(super) fn text(&self) -> &str {
        &self.text
    }

    /// Resolved `.changeset` directory, relative to the repository capability.
    pub(super) fn changeset_path(&self) -> &Path {
        &self.changeset_path
    }

    /// Resolved `_config.toml`, relative to the repository capability.
    pub(super) fn config_path(&self) -> &Path {
        &self.config_path
    }
}

pub(super) fn read_config_source(
    repo: &Repository,
) -> Result<Option<ConfigSource>, Box<dyn std::error::Error>> {
    let dir = repo.dir();
    let repo_path = repo.path();
    let Some(mut file) = open_config(dir, repo_path)? else {
        return Ok(None);
    };
    let mut text = String::new();
    file.read_to_string(&mut text)
        .map_err(|err| config_error(format!("failed to read `{CONFIG_PATH}`: {err}")))?;
    let changeset_path = resolve_capability_path(dir, repo_path, Path::new(".changeset"))?;
    let config_path =
        resolve_capability_path(dir, repo_path, &changeset_path.join("_config.toml"))?;
    Ok(Some(ConfigSource {
        text,
        changeset_path,
        config_path,
    }))
}

/// Capability-resolved location for a file `upgrade` writes next to the
/// config. A missing file resolves to its literal path (it will be created);
/// an existing one goes through symlink containment like every read.
pub(super) fn resolve_sibling_write_target(
    repo: &Repository,
    changeset_path: &Path,
    file_name: &str,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let literal = changeset_path.join(file_name);
    match repo.dir().symlink_metadata(&literal) {
        Ok(_) => resolve_capability_path(repo.dir(), repo.path(), &literal),
        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(literal),
        Err(err) => Err(config_error(format!(
            "failed to inspect `.changeset/{file_name}` within the repository: {err}"
        ))),
    }
}

fn open_config_before_open(
    dir: &Dir,
    repo_path: &Path,
    before_open: impl FnOnce(),
) -> Result<Option<File>, Box<dyn std::error::Error>> {
    let changeset_link = Path::new(".changeset");
    match dir.symlink_metadata(changeset_link) {
        Ok(_) => {}
        Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(err) => {
            return Err(config_error(format!(
                "failed to inspect `.changeset` within the repository: {err}"
            )));
        }
    }
    let changeset_path = resolve_capability_path(dir, repo_path, changeset_link)?;
    let changeset = dir.open_dir(&changeset_path).map_err(|err| {
        config_error(format!(
            "failed to open `.changeset` within the repository: {err}"
        ))
    })?;
    match changeset.symlink_metadata("_config.toml") {
        Ok(_) => {}
        Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(err) => {
            return Err(config_error(format!(
                "failed to inspect `{CONFIG_PATH}` within the repository: {err}"
            )));
        }
    }
    let config_link = changeset_path.join("_config.toml");
    let config_path = resolve_capability_path(dir, repo_path, &config_link)?;
    let metadata = dir.metadata(&config_path).map_err(|err| {
        config_error(format!(
            "failed to inspect `{CONFIG_PATH}` within the repository: {err}"
        ))
    })?;
    if !metadata.is_file() {
        return Err(config_error(format!(
            "`{CONFIG_PATH}` does not resolve to a regular file"
        )));
    }
    before_open();
    let file = open_read_only(dir, &config_path).map_err(|err| {
        config_error(format!(
            "failed to open `{CONFIG_PATH}` within the repository: {err}"
        ))
    })?;
    let metadata = file
        .metadata()
        .map_err(|err| config_error(format!("failed to inspect `{CONFIG_PATH}`: {err}")))?;
    if !metadata.is_file() {
        return Err(config_error(format!(
            "`{CONFIG_PATH}` does not resolve to a regular file"
        )));
    }
    Ok(Some(file))
}

fn config_error(message: impl Into<String>) -> Box<dyn std::error::Error> {
    Box::new(CliError::new(message))
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::io::Read;
    use std::path::{Path, PathBuf};
    #[cfg(unix)]
    use std::process::{Command, Stdio};
    #[cfg(unix)]
    use std::time::{Duration, Instant};

    use cap_std::ambient_authority;

    use crate::test_fixture::Fixture;

    #[test]
    fn a_scope_with_backticks_stays_one_code_span() {
        assert_eq!(super::code_span("gamma"), "`gamma`");
        assert_eq!(super::code_span("x` @y"), "``x` @y``");
        assert_eq!(super::code_span("`a``"), "``` `a`` ```");
        assert_eq!(super::code_span("x`"), "`` x` ``");
        assert_eq!(super::code_span("`x"), "`` `x ``");
    }

    #[cfg(unix)]
    use super::super::repository;
    use super::{open_config, open_config_before_open, Dir};

    fn symlink(original: impl AsRef<Path>, link: impl AsRef<Path>) -> std::io::Result<()> {
        let original = original.as_ref();
        let link = link.as_ref();
        #[cfg(unix)]
        {
            std::os::unix::fs::symlink(original, link)
        }
        #[cfg(windows)]
        {
            // `_config.toml` is the only file symlink this suite creates;
            // every other link is a directory (including dangling `.changeset`).
            if link.file_name().is_some_and(|name| name == "_config.toml") {
                std::os::windows::fs::symlink_file(original, link)
            } else {
                std::os::windows::fs::symlink_dir(original, link)
            }
        }
    }

    /// NTFS directory junction via `mklink /J` — no symlink privilege required.
    #[cfg(windows)]
    fn junction(target: &Path, link: &Path) -> std::io::Result<()> {
        let status = std::process::Command::new("cmd")
            .args(["/C", "mklink", "/J"])
            .arg(link)
            .arg(target)
            .status()?;
        if status.success() {
            Ok(())
        } else {
            Err(std::io::Error::other(format!(
                "mklink /J failed with {status}"
            )))
        }
    }

    fn fixture(label: &str) -> Fixture {
        Fixture::new("open-config", label)
    }

    fn open_root(root: &Path) -> Dir {
        Dir::open_ambient_dir(root, ambient_authority()).expect("repository capability")
    }

    fn canonical_root(root: &Path) -> PathBuf {
        fs::canonicalize(root).expect("canonical root")
    }

    fn read_config(root: &Path) -> String {
        let mut config = open_config(&open_root(root), &canonical_root(root))
            .expect("open config")
            .expect("config file");
        let mut text = String::new();
        config.read_to_string(&mut text).expect("read config");
        text
    }

    #[test]
    fn absent_config_in_existing_changeset_selects_defaults() {
        let root = fixture("absent");
        fs::create_dir(root.join(".changeset")).expect("changeset");

        let config =
            open_config(&open_root(&root), &canonical_root(&root)).expect("inspect config");

        assert!(config.is_none());
    }

    #[test]
    fn a_directory_config_is_not_a_regular_file() {
        let root = fixture("dir-config");
        fs::create_dir(root.join(".changeset")).expect("changeset");
        fs::create_dir(root.join(".changeset/_config.toml")).expect("config dir");

        let error = open_config(&open_root(&root), &canonical_root(&root))
            .expect_err("a directory must not look like a missing config");
        assert!(error.to_string().contains("regular file"), "{error}");
    }

    #[test]
    fn external_changeset_symlink_is_not_missing_config() {
        let root = fixture("external-ancestor");
        let external = fixture("external-target");
        fs::write(
            external.join("_config.toml"),
            "secret = \"must-not-be-read\"\n",
        )
        .expect("external config");
        symlink(&external, root.join(".changeset")).expect("changeset symlink");

        let error = open_config(&open_root(&root), &canonical_root(&root))
            .expect_err("external ancestor must fail");
        // Not the bare word "repository": every wrapper message in this module
        // carries it, so a generic open failure would satisfy that assertion.
        assert!(
            error
                .to_string()
                .contains("resolves outside the repository"),
            "{error}"
        );
    }

    /// The `..`-above-root branch is otherwise reached only from
    /// `cli::template`'s suite, so narrowing that one would strand it here.
    #[test]
    fn changeset_symlink_climbing_above_the_root_is_refused() {
        let root = fixture("climbing-ancestor");
        symlink("../..", root.join(".changeset")).expect("climbing symlink");

        let error = open_config(&open_root(&root), &canonical_root(&root))
            .expect_err("climbing ancestor must fail");
        assert!(
            error
                .to_string()
                .contains("resolves outside the repository"),
            "{error}"
        );
    }

    #[test]
    fn dangling_changeset_symlink_is_not_missing_config() {
        let root = fixture("dangling-ancestor");
        symlink("missing-changeset", root.join(".changeset")).expect("changeset symlink");

        let error = open_config(&open_root(&root), &canonical_root(&root))
            .expect_err("dangling ancestor must fail");
        assert!(error.to_string().contains("failed to"), "{error}");
    }

    #[test]
    fn internal_config_symlink_opens_its_target() {
        let root = fixture("internal-config");
        fs::create_dir(root.join(".changeset")).expect("changeset");
        fs::write(
            root.join("oakum-config.toml"),
            "tool-version = \"0.0.0\"\ntitle = \"leaf-symlink-loaded\"\n",
        )
        .expect("config");
        symlink("../oakum-config.toml", root.join(".changeset/_config.toml"))
            .expect("config symlink");

        let text = read_config(&root);

        assert!(text.contains("leaf-symlink-loaded"), "{text}");
    }

    #[test]
    fn internal_changeset_symlink_opens_its_target() {
        let root = fixture("internal-changeset");
        let changeset = root.join("config/changeset");
        fs::create_dir_all(&changeset).expect("changeset");
        fs::write(
            changeset.join("_config.toml"),
            "tool-version = \"0.0.0\"\ntitle = \"ancestor-symlink-loaded\"\n",
        )
        .expect("config");
        symlink("config/changeset", root.join(".changeset")).expect("changeset symlink");

        let text = read_config(&root);

        assert!(text.contains("ancestor-symlink-loaded"), "{text}");
    }

    #[test]
    fn absolute_internal_config_symlink_opens_its_target() {
        let root = fixture("absolute-internal-config");
        fs::create_dir(root.join(".changeset")).expect("changeset");
        let target = root.join("oakum-config.toml");
        fs::write(
            &target,
            "tool-version = \"0.0.0\"\ntitle = \"absolute-leaf-loaded\"\n",
        )
        .expect("config");
        symlink(&target, root.join(".changeset/_config.toml")).expect("config symlink");

        let text = read_config(&root);

        assert!(text.contains("absolute-leaf-loaded"), "{text}");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn absolute_internal_symlink_accepts_filesystem_alias() {
        let root = fixture("absolute-alias");
        let canonical_root = fs::canonicalize(&root).expect("canonical root");
        fs::create_dir(root.join(".changeset")).expect("changeset");
        let target = root.join("oakum-config.toml");
        fs::write(
            &target,
            "tool-version = \"0.0.0\"\ntitle = \"absolute-alias-loaded\"\n",
        )
        .expect("config");
        symlink(&target, root.join(".changeset/_config.toml")).expect("config symlink");

        let mut config = open_config(&open_root(&root), &canonical_root)
            .expect("open config")
            .expect("config file");
        let mut text = String::new();
        config.read_to_string(&mut text).expect("read config");

        assert!(text.contains("absolute-alias-loaded"), "{text}");
    }

    #[test]
    fn absolute_internal_changeset_symlink_opens_its_target() {
        let root = fixture("absolute-internal-changeset");
        let changeset = root.join("config/changeset");
        fs::create_dir_all(&changeset).expect("changeset");
        fs::write(
            changeset.join("_config.toml"),
            "tool-version = \"0.0.0\"\ntitle = \"absolute-ancestor-loaded\"\n",
        )
        .expect("config");
        symlink(&changeset, root.join(".changeset")).expect("changeset symlink");

        let text = read_config(&root);

        assert!(text.contains("absolute-ancestor-loaded"), "{text}");
    }

    #[test]
    fn changeset_symlink_to_repository_root_opens_its_target() {
        let root = fixture("changeset-to-root");
        fs::write(
            root.join("_config.toml"),
            "tool-version = \"0.0.0\"\ntitle = \"repository-root-loaded\"\n",
        )
        .expect("config");
        symlink(&root, root.join(".changeset")).expect("changeset symlink");

        let text = read_config(&root);

        assert!(text.contains("repository-root-loaded"), "{text}");
    }

    #[test]
    fn nested_absolute_internal_symlink_opens_its_target() {
        let root = fixture("nested-absolute-internal");
        fs::create_dir(root.join(".changeset")).expect("changeset");
        let target = root.join("config-target");
        fs::create_dir(&target).expect("target directory");
        fs::write(
            target.join("oakum.toml"),
            "tool-version = \"0.0.0\"\ntitle = \"nested-absolute-loaded\"\n",
        )
        .expect("config");
        symlink(&target, root.join("absolute-hop")).expect("absolute symlink");
        symlink(
            "../absolute-hop/oakum.toml",
            root.join(".changeset/_config.toml"),
        )
        .expect("config symlink");

        let text = read_config(&root);

        assert!(text.contains("nested-absolute-loaded"), "{text}");
    }

    #[test]
    fn parent_component_applies_after_symlink_resolution() {
        let root = fixture("symlink-parent");
        fs::create_dir(root.join(".changeset")).expect("changeset");
        fs::create_dir_all(root.join("nested/deep")).expect("nested target");
        fs::write(
            root.join("nested/oakum.toml"),
            "tool-version = \"0.0.0\"\ntitle = \"resolved-parent-loaded\"\n",
        )
        .expect("resolved config");
        fs::write(
            root.join("oakum.toml"),
            "tool-version = \"0.0.0\"\ntitle = \"lexical-parent-wrong\"\n",
        )
        .expect("lexical config");
        symlink("nested/deep", root.join("jump")).expect("intermediate symlink");
        symlink(
            "../jump/../oakum.toml",
            root.join(".changeset/_config.toml"),
        )
        .expect("config symlink");

        let text = read_config(&root);

        assert!(text.contains("resolved-parent-loaded"), "{text}");
        assert!(!text.contains("lexical-parent-wrong"), "{text}");
    }

    #[cfg(unix)]
    #[test]
    fn repository_capability_survives_root_replacement() {
        let root = fixture("stable-root");
        fs::create_dir(root.join(".git")).expect("git marker");
        fs::create_dir(root.join(".changeset")).expect("changeset");
        fs::write(
            root.join(".changeset/_config.toml"),
            "tool-version = \"0.0.0\"\ntitle = \"original-root\"\n",
        )
        .expect("original config");
        let repository = repository::discover_from(&root).expect("discover repository");
        // A sibling of the root, so it lands in the fixture's container and is
        // reclaimed with it.
        let moved = root.with_file_name("moved");
        fs::rename(&root, &moved).expect("rename repository");
        fs::create_dir(&root).expect("replacement root");
        fs::create_dir(root.join(".git")).expect("replacement git marker");
        fs::create_dir(root.join(".changeset")).expect("replacement changeset");
        fs::write(
            root.join(".changeset/_config.toml"),
            "tool-version = \"0.0.0\"\ntitle = \"replacement-root\"\n",
        )
        .expect("replacement config");

        let mut config = open_config(repository.dir(), repository.path())
            .expect("open config")
            .expect("config file");
        let mut text = String::new();
        config.read_to_string(&mut text).expect("read config");

        assert!(text.contains("original-root"), "{text}");
        assert!(!text.contains("replacement-root"), "{text}");
    }

    #[test]
    fn raced_external_config_symlink_is_rejected() {
        let root = fixture("raced-external-config");
        fs::create_dir(root.join(".changeset")).expect("changeset");
        let config_path = root.join(".changeset/_config.toml");
        fs::write(&config_path, "tool-version = \"0.0.0\"\n").expect("config");
        let external = fixture("raced-external-config-target");
        let external_config = external.join("config.toml");
        fs::write(
            &external_config,
            "secret = \"raced-external-must-not-be-read\"\n",
        )
        .expect("external config");
        let dir = open_root(&root);

        let result = open_config_before_open(&dir, &canonical_root(&root), || {
            fs::remove_file(&config_path).expect("remove regular config");
            symlink(&external_config, &config_path).expect("external config symlink");
        });

        let error = result.expect_err("external symlink must fail");
        // cap-std's sandbox refuses this one before oakum's own check sees it,
        // so its wording is what proves the refusal was for containment.
        assert!(
            error
                .to_string()
                .contains("a path led outside of the filesystem"),
            "{error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn raced_external_changeset_symlink_is_rejected() {
        let root = fixture("raced-external-changeset");
        fs::create_dir(root.join(".changeset")).expect("changeset");
        fs::write(
            root.join(".changeset/_config.toml"),
            "tool-version = \"0.0.0\"\n",
        )
        .expect("config");
        let external = fixture("raced-external-changeset-target");
        fs::write(
            external.join("_config.toml"),
            "secret = \"raced-ancestor-must-not-be-read\"\n",
        )
        .expect("external config");
        let dir = open_root(&root);

        let result = open_config_before_open(&dir, &canonical_root(&root), || {
            fs::remove_file(root.join(".changeset/_config.toml")).expect("remove config");
            fs::remove_dir(root.join(".changeset")).expect("remove changeset");
            symlink(&external, root.join(".changeset")).expect("external changeset symlink");
        });

        let error = result.expect_err("external ancestor must fail");
        assert!(
            error
                .to_string()
                .contains("a path led outside of the filesystem"),
            "{error}"
        );
    }

    #[test]
    fn symlink_cycle_is_rejected() {
        let root = fixture("symlink-cycle");
        symlink("loop-a", root.join(".changeset")).expect("changeset symlink");
        symlink(".changeset", root.join("loop-a")).expect("loop symlink");

        let error =
            open_config(&open_root(&root), &canonical_root(&root)).expect_err("cycle must fail");

        assert!(
            error.to_string().contains("too many symbolic links"),
            "{error}"
        );
    }

    #[test]
    fn excessive_symlink_depth_is_rejected() {
        let root = fixture("symlink-depth");
        let target = root.join("target");
        fs::create_dir(&target).expect("target");
        fs::write(target.join("_config.toml"), "tool-version = \"0.0.0\"\n").expect("config");
        symlink("link-0", root.join(".changeset")).expect("changeset symlink");
        for index in 0..41 {
            let next = if index == 40 {
                String::from("target")
            } else {
                format!("link-{}", index + 1)
            };
            symlink(next, root.join(format!("link-{index}"))).expect("chain symlink");
        }

        let error = open_config(&open_root(&root), &canonical_root(&root))
            .expect_err("deep chain must fail");

        assert!(
            error.to_string().contains("too many symbolic links"),
            "{error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn raced_fifo_is_opened_nonblocking_and_rejected() {
        let root = fixture("raced-fifo-parent");
        let mut child = Command::new(std::env::current_exe().expect("test binary"))
            .args([
                "--exact",
                "cli::config::tests::raced_fifo_helper",
                "--ignored",
                "--nocapture",
            ])
            .env("OAKUM_RACED_FIFO_ROOT", &root)
            .stdout(Stdio::null())
            .stderr(Stdio::piped())
            .spawn()
            .expect("race helper");
        let deadline = Instant::now() + Duration::from_secs(5);
        let status = loop {
            if let Some(status) = child.try_wait().expect("poll race helper") {
                break status;
            }
            if Instant::now() >= deadline {
                child.kill().expect("kill blocked race helper");
                child.wait().expect("reap race helper");
                panic!("config open blocked after a regular file became a FIFO");
            }
            std::thread::sleep(Duration::from_millis(10));
        };
        let mut stderr = String::new();
        child
            .stderr
            .take()
            .expect("race helper stderr")
            .read_to_string(&mut stderr)
            .expect("read race helper stderr");

        assert!(status.success(), "race helper failed: {stderr}");
    }

    #[cfg(unix)]
    #[test]
    #[ignore = "run by raced_fifo_is_opened_nonblocking_and_rejected"]
    fn raced_fifo_helper() {
        let root = PathBuf::from(std::env::var_os("OAKUM_RACED_FIFO_ROOT").expect("fixture root"));
        fs::create_dir(root.join(".changeset")).expect("changeset");
        let config_path = root.join(".changeset/_config.toml");
        fs::write(&config_path, "tool-version = \"0.0.0\"\n").expect("config");
        let dir = open_root(&root);

        let result = open_config_before_open(&dir, &canonical_root(&root), || {
            fs::remove_file(&config_path).expect("remove regular config");
            let status = Command::new("mkfifo")
                .arg(&config_path)
                .status()
                .expect("mkfifo");
            assert!(status.success(), "mkfifo: {status}");
        });

        let error = result.expect_err("FIFO must fail");
        assert!(error.to_string().contains("regular file"), "{error}");
    }

    #[cfg(windows)]
    fn flipped_drive_case(path: &Path) -> PathBuf {
        let mut text = path.to_string_lossy().into_owned();
        let pos = text
            .char_indices()
            .find_map(|(idx, ch)| ch.is_ascii_alphabetic().then_some(idx))
            .unwrap_or_else(|| panic!("no drive letter in {}", path.display()));
        assert_eq!(
            text.as_bytes().get(pos + 1),
            Some(&b':'),
            "no drive colon in {}",
            path.display()
        );
        let ch = text.as_bytes()[pos];
        let flipped = if ch.is_ascii_uppercase() {
            ch.to_ascii_lowercase()
        } else {
            ch.to_ascii_uppercase()
        };
        text.replace_range(pos..=pos, std::str::from_utf8(&[flipped]).expect("ascii"));
        PathBuf::from(text)
    }

    /// Flip ASCII letter case after the drive (`C:` / `\\?\C:`). NTFS treats
    /// `Users` and `users` as the same path; containment must too (okm-3l8.3).
    #[cfg(windows)]
    fn flipped_path_body_case(path: &Path) -> PathBuf {
        let chars: Vec<char> = path.to_string_lossy().chars().collect();
        let mut out = String::with_capacity(chars.len());
        let mut after_drive = false;
        let mut i = 0;
        while i < chars.len() {
            let ch = chars[i];
            if !after_drive
                && ch == ':'
                && chars
                    .get(i + 1)
                    .is_some_and(|next| *next == '\\' || *next == '/')
            {
                out.push(ch);
                after_drive = true;
            } else if after_drive && ch.is_ascii_alphabetic() {
                out.push(if ch.is_ascii_uppercase() {
                    ch.to_ascii_lowercase()
                } else {
                    ch.to_ascii_uppercase()
                });
            } else {
                out.push(ch);
            }
            i += 1;
        }
        assert!(after_drive, "expected a drive path, got {}", path.display());
        PathBuf::from(out)
    }

    #[cfg(windows)]
    fn verbatim_prefix(path: &Path) -> PathBuf {
        let text = path.to_string_lossy();
        if text.starts_with(r"\\?\") {
            path.to_path_buf()
        } else {
            PathBuf::from(format!(r"\\?\{text}"))
        }
    }

    #[cfg(windows)]
    fn loopback_admin_unc(path: &Path) -> PathBuf {
        let normalized = super::super::fs::normalized_windows_path(path);
        assert!(
            normalized.len() >= 3 && normalized.as_bytes()[1] == b':',
            "expected a drive path, got {normalized}"
        );
        let drive = normalized.chars().next().expect("drive");
        let tail = &normalized[2..];
        PathBuf::from(format!(r"\\localhost\{drive}${tail}"))
    }

    #[cfg(windows)]
    fn read_config_at(root: &Path, repo_path: &Path) -> String {
        let mut config = open_config(&open_root(root), repo_path)
            .expect("open config")
            .expect("config file");
        let mut text = String::new();
        config.read_to_string(&mut text).expect("read config");
        text
    }

    #[cfg(windows)]
    fn write_absolute_internal_config(root: &Path, title: &str) {
        fs::create_dir(root.join(".changeset")).expect("changeset");
        let target = root.join("oakum-config.toml");
        fs::write(
            &target,
            format!("tool-version = \"0.0.0\"\ntitle = \"{title}\"\n"),
        )
        .expect("config");
        symlink(&target, root.join(".changeset/_config.toml")).expect("config symlink");
    }

    #[cfg(windows)]
    #[test]
    fn drive_letter_case_does_not_escape_an_internal_config() {
        let root = fixture("drive-case");
        write_absolute_internal_config(&root, "drive-case-loaded");
        let canonical = canonical_root(&root);
        let flipped = flipped_drive_case(&canonical);
        assert_ne!(
            flipped.to_string_lossy(),
            canonical.to_string_lossy(),
            "need a case difference to exercise ignore-ascii"
        );

        let text = read_config_at(&root, &flipped);
        assert!(text.contains("drive-case-loaded"), "{text}");
    }

    /// NTFS folds path components (`Users` ≡ `users`). The discovery-time
    /// `repo_path` may not match the casing `canonicalize` returns for a
    /// symlink target; containment must still accept the pair (okm-3l8.3).
    #[cfg(windows)]
    #[test]
    fn path_component_case_does_not_escape_an_internal_config() {
        let root = fixture("path-case");
        write_absolute_internal_config(&root, "path-case-loaded");
        let canonical = canonical_root(&root);
        let flipped = flipped_path_body_case(&canonical);
        assert_ne!(
            flipped.to_string_lossy(),
            canonical.to_string_lossy(),
            "need a path-body case difference to exercise NTFS ignore-ascii"
        );

        let text = read_config_at(&root, &flipped);
        assert!(text.contains("path-case-loaded"), "{text}");
    }

    /// Directory junction (mklink /J) is the common Windows stand-in for an
    /// in-repo directory symlink and does not need `SeCreateSymbolicLinkPrivilege`
    /// (okm-3l8.4).
    #[cfg(windows)]
    #[test]
    fn internal_changeset_junction_opens_its_target() {
        let root = fixture("changeset-junction");
        let changeset = root.join("config").join("changeset");
        fs::create_dir_all(&changeset).expect("changeset");
        fs::write(
            changeset.join("_config.toml"),
            "tool-version = \"0.0.0\"\ntitle = \"junction-loaded\"\n",
        )
        .expect("config");
        junction(&changeset, &root.join(".changeset")).expect("changeset junction");

        let text = read_config(&root);
        assert!(text.contains("junction-loaded"), "{text}");

        let resolved = super::super::fs::resolve_capability_path(
            &open_root(&root),
            &canonical_root(&root),
            Path::new(".changeset/_config.toml"),
        )
        .expect("resolve through junction");
        assert_eq!(
            resolved,
            Path::new("config/changeset/_config.toml"),
            "resolve must follow the junction to the real target, got {resolved:?}"
        );
    }

    #[cfg(windows)]
    #[test]
    fn absolute_internal_file_symlink_opens_its_target() {
        let root = fixture("windows-abs-file-symlink");
        write_absolute_internal_config(&root, "windows-abs-file-loaded");

        let text = read_config(&root);
        assert!(text.contains("windows-abs-file-loaded"), "{text}");

        let resolved = super::super::fs::resolve_capability_path(
            &open_root(&root),
            &canonical_root(&root),
            Path::new(".changeset/_config.toml"),
        )
        .expect("resolve through absolute file symlink");
        assert_eq!(
            resolved,
            Path::new("oakum-config.toml"),
            "resolve must follow the absolute file symlink, got {resolved:?}"
        );
    }

    #[cfg(windows)]
    #[test]
    fn verbatim_prefix_does_not_escape_an_internal_config() {
        let root = fixture("verbatim");
        write_absolute_internal_config(&root, "verbatim-loaded");

        let text = read_config_at(&root, &verbatim_prefix(root.as_ref()));
        assert!(text.contains("verbatim-loaded"), "{text}");
    }

    #[cfg(windows)]
    #[test]
    fn absolute_internal_config_survives_a_unc_repo_prefix() {
        let root = fixture("unc-absolute-internal");
        fs::create_dir(root.join(".changeset")).expect("changeset");
        let target = root.join("oakum-config.toml");
        fs::write(
            &target,
            "tool-version = \"0.0.0\"\ntitle = \"unc-absolute-loaded\"\n",
        )
        .expect("config");
        symlink(&target, root.join(".changeset/_config.toml")).expect("config symlink");

        let text = read_config_at(&root, &loopback_admin_unc(&canonical_root(&root)));
        assert!(text.contains("unc-absolute-loaded"), "{text}");
    }

    #[cfg(windows)]
    #[test]
    fn external_unc_target_is_rejected() {
        let root = fixture("unc-external");
        let external = fixture("unc-external-target");
        fs::write(
            external.join("_config.toml"),
            "secret = \"unc-must-not-be-read\"\n",
        )
        .expect("external config");
        symlink(loopback_admin_unc(&external), root.join(".changeset")).expect("changeset symlink");

        let error = open_config(
            &open_root(&root),
            &loopback_admin_unc(&canonical_root(&root)),
        )
        .expect_err("external UNC ancestor must fail");
        assert!(
            error
                .to_string()
                .contains("resolves outside the repository"),
            "{error}"
        );
    }
}