repon 0.30.5

A terminal UI for the outer loop: seeing many git repos at once and acting on many in one gesture
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
//! The config entries Repon writes, read-modify-written on the file on disk.
//!
//! [0028](../../../../docs/adr/0028-repon-writes-the-repo-entries-it-owns.md), as amended,
//! bounds what may be written to the `[[repo]]` entries and the `[[set]]` `include` and
//! `exclude` arrays, and nothing else, and
//! [repo-management.md](../../../../docs/spec/repo-management.md)'s "Writing config" fixes the
//! mechanism: every write reads the file, edits the parsed text and writes it back, so a
//! concurrent hand edit loses only the keys both writers touched. Nothing here ever
//! serialises [`super::Document`], which would rewrite the whole file from this crate's own
//! structs and drop every comment the file exists to carry.
//!
//! `toml_edit` rather than the `toml` the schema is deserialised with: a hand-edited
//! document only survives a round trip through a format-preserving parser.

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

use color_eyre::eyre::{Result, WrapErr};
use toml_edit::{DocumentMut, Item, Table, value};

use super::document::expand_home;

/// The array of tables this module's `[[repo]]` writes are bounded to. Named once so no call
/// site below can reach a different one by typo.
const REPO: &str = "repo";

/// The other array of tables this module writes, for the two arrays of paths a Set may bound
/// itself with.
const SET: &str = "set";

/// The one key an entry Repon appends carries besides `path`, and the one key `Unexclude`
/// removes.
const EXCLUDE: &str = "exclude";

const PATH: &str = "path";

/// The `[[set]]` arrays that may name a path, so a path `delete` destroyed stops being named
/// by either of them.
const SET_PATH_ARRAYS: [&str; 2] = ["include", EXCLUDE];

/// What a management operation asks of one `[[repo]]` entry, per
/// [repo-management.md](../../../../docs/spec/repo-management.md)'s operations table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Edit {
    /// `ignore`: `exclude = true`, on the entry the path already has or on one appended
    /// with its provenance comment.
    Exclude,
    /// `Unexclude`: the `exclude` key alone, leaving whatever else the table carries. An
    /// entry left with nothing but `path` goes with it.
    Unexclude,
    /// `delete`: the whole entry, once the working tree is gone, and the path with it from
    /// every `[[set]]` array that named it.
    Remove,
}

/// The comment an entry Repon appends carries on the line above it
/// ([repo-management.md](../../../../docs/spec/repo-management.md)'s "Writing config"): the
/// file's whole value under [0014](../../../../docs/adr/0014-config-is-read-only-and-a-set-bounds-the-work.md)
/// is that its comments say more than its values, so an entry appearing with no explanation
/// is the loss that argument was protecting against.
fn provenance_comment(today: &str) -> String {
    format!("# ignored from Repon on {today}")
}

/// Today's date as `YYYY-MM-DD`, the leading date of [`repon_core::Timestamp`]'s own RFC 3339
/// rendering: UTC, and read from the core's one calendar rather than a second one here.
pub(crate) fn today() -> String {
    let now = repon_core::Timestamp::now().to_string();
    now.split('T').next().unwrap_or(&now).to_string()
}

/// What one write did, which is two facts rather than one: a `delete` may edit a `[[set]]`
/// array for an entity that never had a `[[repo]]` entry at all, so "the file changed" and
/// "the entity's own entry went" are no longer the same answer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Written {
    /// Whether the file's text changed, so a caller can tell an edit that did something from
    /// one that found nothing to do.
    pub(crate) changed: bool,
    /// Whether a `[[repo]]` entry of the entity's own was there and went, which is the fact
    /// `delete`'s receipt names ([repo-management.md](../../../../docs/spec/repo-management.md)'s
    /// "Receipts").
    pub(crate) removed_repo_entry: bool,
}

/// Reads `config_file`, applies `edit` for `path`, and writes the result back. A missing file
/// is read as the empty document it already behaves as ([`super::document::load`]'s own "a
/// missing file is not an error"), so a first `ignore` with no config at all still writes one.
pub(crate) fn write(config_file: &Path, path: &Path, edit: Edit) -> Result<Written> {
    let before = match fs::read_to_string(config_file) {
        Ok(text) => text,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(err) => {
            return Err(err).wrap_err_with(|| format!("could not read {}", config_file.display()));
        }
    };
    // Read before the edit, since afterwards the entry is gone either way. `apply` reports
    // the malformed-document failure for both of us, so a parse that fails here is left to it.
    let removed_repo_entry = edit == Edit::Remove
        && before
            .parse::<DocumentMut>()
            .is_ok_and(|document| find_entry(&document, path).is_some());
    let after = apply(&before, path, edit, &today())?;
    if after == before {
        return Ok(Written {
            changed: false,
            removed_repo_entry,
        });
    }
    if let Some(parent) = config_file.parent() {
        fs::create_dir_all(parent)
            .wrap_err_with(|| format!("could not create {}", parent.display()))?;
    }
    fs::write(config_file, &after)
        .wrap_err_with(|| format!("could not write {}", config_file.display()))?;
    Ok(Written {
        changed: true,
        removed_repo_entry,
    })
}

/// `text` with `edit` applied to the entries naming `path`, and nothing else touched: the
/// `[[repo]]` entry for every edit, and, for [`Edit::Remove`] alone, the `[[set]]` arrays
/// naming it as well ([`remove_from_set_path_arrays`]).
///
/// Matching is by expanded path rather than by the written string, so an entry the user wrote
/// as `~/dev/noisy` is found by the absolute path Repon knows the entity by. An appended
/// entry is written back in the `~`-relative form the file's own examples use, since that is
/// the form a user reading the file afterwards would have written themselves.
pub(crate) fn apply(text: &str, path: &Path, edit: Edit, today: &str) -> Result<String> {
    let mut document: DocumentMut = text
        .parse()
        .wrap_err("could not parse the config file to edit it")?;

    let existing = find_entry(&document, path);
    match (edit, existing) {
        (Edit::Exclude, Some(index)) => {
            entries_mut(&mut document)
                .and_then(|entries| entries.get_mut(index))
                .expect("the index just found still resolves")[EXCLUDE] = value(true);
        }
        (Edit::Exclude, None) => append_entry(&mut document, path, today),
        (Edit::Unexclude, Some(index)) => {
            let Some(entries) = entries_mut(&mut document) else {
                unreachable!("an index was found, so the array of tables is there");
            };
            let entry = entries
                .get_mut(index)
                .expect("the index just found still resolves");
            entry.remove(EXCLUDE);
            if carries_only_a_path(entry) {
                entries.remove(index);
            }
        }
        (Edit::Remove, index) => {
            if let Some(index) = index {
                let Some(entries) = entries_mut(&mut document) else {
                    unreachable!("an index was found, so the array of tables is there");
                };
                entries.remove(index);
            }
            remove_from_set_path_arrays(&mut document, path);
        }
        (Edit::Unexclude, None) => {}
    }
    Ok(document.to_string())
}

/// Removes `path` from every `[[set]]` `include` and `exclude` array that names it, and
/// removes an array its last named path leaves empty.
///
/// A glob that merely would have matched `path` is left alone: it states a class rather than
/// this one entity, so dropping it would change what the Set means for every other row it
/// covers ([repo-management.md](../../../../docs/spec/repo-management.md)'s "Writing
/// config"). An emptied array goes rather than being left as `[]`, on the same reasoning
/// [`carries_only_a_path`] removes an entry with nothing left to say: an empty `include`
/// reads as "nothing" and means "everything" to discovery, which is a worse thing to leave
/// behind than the key's absence.
fn remove_from_set_path_arrays(document: &mut DocumentMut, path: &Path) {
    let Some(sets) = document.get_mut(SET).and_then(Item::as_array_of_tables_mut) else {
        return;
    };
    for set in sets.iter_mut() {
        for key in SET_PATH_ARRAYS {
            let Some(paths) = set.get_mut(key).and_then(Item::as_array_mut) else {
                continue;
            };
            paths.retain(|named| {
                !named
                    .as_str()
                    .is_some_and(|declared| declared_path_matches(declared, path))
            });
            if paths.is_empty() {
                set.remove(key);
            }
        }
    }
}

/// The index of the `[[repo]]` entry whose `path` expands to `path`, if any. A duplicate
/// path cannot reach here: [`super::document::load`] rejects the whole file for one
/// ([`super::document`]'s own `reject_duplicate_names`).
fn find_entry(document: &DocumentMut, path: &Path) -> Option<usize> {
    document
        .get(REPO)?
        .as_array_of_tables()?
        .iter()
        .position(|entry| entry_path_matches(entry, path))
}

fn entry_path_matches(entry: &Table, path: &Path) -> bool {
    entry
        .get(PATH)
        .and_then(Item::as_str)
        .is_some_and(|declared| declared_path_matches(declared, path))
}

/// Whether the string a config entry wrote names `path`. One definition for both the
/// `[[repo]]` `path` key and a `[[set]]` array's own entries, so the two can never disagree
/// about which written form names the entity Repon knows by an absolute path.
fn declared_path_matches(declared: &str, path: &Path) -> bool {
    expand_home(declared) == path
}

fn entries_mut(document: &mut DocumentMut) -> Option<&mut toml_edit::ArrayOfTables> {
    document.get_mut(REPO)?.as_array_of_tables_mut()
}

/// Whether `entry` is left with nothing to say: only its own `path` key, which alone
/// declares no fact at all ([repo-management.md](../../../../docs/spec/repo-management.md)'s
/// "Writing config"). Counts keys rather than naming the ones it knows, so a `[[repo]]` key
/// added to the schema later keeps its own entry alive here without editing this.
///
/// Removing the last such entry is also what removes the array of tables: `toml_edit` renders
/// an emptied `ArrayOfTables` as no text at all, so the array goes with its last entry with
/// no separate step. Measured rather than assumed, and `exclude_then_unexclude_on_a_file_with_no_repo_array_returns_it_byte_for_byte`
/// is what holds it.
fn carries_only_a_path(entry: &Table) -> bool {
    entry.len() == 1 && entry.contains_key(PATH)
}

/// Appends a new `[[repo]]` entry carrying `path`, `exclude = true` and its provenance
/// comment. `toml_edit` lands it after the last existing `[[repo]]` when the array is already
/// there, and at the end of the document when it is not; the blank line in the prefix is what
/// separates it from whatever it lands after, and the trailing comment a document ends with
/// stays after it rather than being captured as this table's own.
fn append_entry(document: &mut DocumentMut, path: &Path, today: &str) {
    let mut entry = Table::new();
    entry[PATH] = value(contract_home(path));
    entry[EXCLUDE] = value(true);
    entry
        .decor_mut()
        .set_prefix(format!("\n{}\n", provenance_comment(today)));

    let entries = document
        .entry(REPO)
        .or_insert(Item::ArrayOfTables(toml_edit::ArrayOfTables::new()));
    if let Some(entries) = entries.as_array_of_tables_mut() {
        entries.push(entry);
    }
}

/// `path` written the way the file's own examples write one: `~`-relative when it is under
/// the home directory, absolute otherwise. The inverse of
/// [`super::document::expand_home`], which is what reads it back.
fn contract_home(path: &Path) -> String {
    if let Ok(home) = etcetera::home_dir()
        && let Ok(rest) = path.strip_prefix(&home)
    {
        if rest.as_os_str().is_empty() {
            return "~".to_string();
        }
        return format!("~/{}", rest.display());
    }
    path.display().to_string()
}

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

    /// This repository's own commented config, in the house style
    /// [config.md](../../../../docs/spec/config.md)'s annotated example fixes: comments above
    /// tables, comments at the end of a line, `[[repo]]` entries carrying `default_branch`
    /// and `exclude`, and a `[[launcher]]` array following them. Read at test time rather
    /// than restated here, so a fixture written to suit these assertions cannot drift from
    /// the one the program actually ships.
    fn commented_fixture() -> String {
        std::fs::read_to_string(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/config/example.toml"),
        )
        .expect("read the shipped annotated example")
    }

    /// Every comment line in `text`, in order: a whole-line comment or the trailing half of
    /// a line that carries one.
    fn comments(text: &str) -> Vec<String> {
        text.lines()
            .filter_map(|line| {
                let trimmed = line.trim();
                if let Some(rest) = trimmed.strip_prefix('#') {
                    return Some(format!("#{rest}"));
                }
                trimmed.find(" # ").map(|at| trimmed[at + 1..].to_string())
            })
            .collect()
    }

    fn path(declared: &str) -> std::path::PathBuf {
        expand_home(declared)
    }

    /// Criterion 1: a comment anywhere in the file survives every write. Every one of the
    /// three edits is run against the same commented fixture, and each is asserted to leave
    /// the file's whole comment list unchanged, except for the one comment an appended entry
    /// adds and the one a removed entry takes with it, which are named rather than tolerated.
    #[test]
    fn every_comment_in_the_commented_fixture_survives_every_write() {
        let before = commented_fixture();
        let original = comments(&before);
        assert!(
            original.len() > 5,
            "the fixture has to actually carry comments for this to prove anything, found {original:?}"
        );

        // `exclude` set on an entry that already exists: nothing is added or removed.
        let after = apply(
            &before,
            &path("~/dev/legacy-api"),
            Edit::Exclude,
            "2026-09-01",
        )
        .expect("the fixture parses");
        assert_eq!(comments(&after), original);

        // `exclude` removed from an entry that still carries `default_branch`: the table
        // stays, so its own comment does too.
        let after = apply(
            &after,
            &path("~/dev/legacy-api"),
            Edit::Unexclude,
            "2026-09-01",
        )
        .expect("the written document parses");
        assert_eq!(comments(&after), original);

        // An appended entry adds exactly its own provenance comment and nothing else. Its
        // position among the others is asserted separately, by
        // `an_appended_entry_lands_after_the_last_existing_repo_entry`.
        let after = apply(&before, &path("~/dev/noisy"), Edit::Exclude, "2026-09-01")
            .expect("the fixture parses");
        let written = comments(&after);
        let mut without_the_new_one = written.clone();
        without_the_new_one.retain(|comment| comment != &provenance_comment("2026-09-01"));
        assert_eq!(without_the_new_one, original);
        assert_eq!(
            written.len(),
            original.len() + 1,
            "an append must add its own comment once and no other"
        );

        // A removed entry takes the comment written above it, which is a comment about the
        // entry being removed, and no other.
        let after = apply(
            &before,
            &path("~/dev/legacy-api"),
            Edit::Remove,
            "2026-09-01",
        )
        .expect("the fixture parses");
        let lost: Vec<&String> = original
            .iter()
            .filter(|comment| !comments(&after).contains(comment))
            .collect();
        assert_eq!(
            lost,
            vec!["# origin/HEAD on this one still says master; pin it."],
            "removing an entry must take its own leading comment and no other"
        );
    }

    /// Criterion 1, sharpened: an `ignore` reaches the one `[[repo]]` entry it names and
    /// nothing else, so nothing the user hand-wrote is reformatted. Every line of the
    /// fixture that is not part of that entry comes back byte for byte.
    #[test]
    fn a_write_reformats_nothing_outside_the_repo_entry_it_edits() {
        let before = commented_fixture();
        let after = apply(
            &before,
            &path("~/dev/legacy-api"),
            Edit::Exclude,
            "2026-09-01",
        )
        .expect("the fixture parses");

        // One line inserted into the one table this edit names, and every other byte of the
        // file identical: taking that single line back out has to give the original exactly.
        assert_eq!(
            after.replacen(
                "default_branch = \"main\"\nexclude = true\n",
                "default_branch = \"main\"\n",
                1
            ),
            before,
            "a write must touch nothing but the `[[repo]]` entry it names, got {after:?}"
        );
    }

    /// Criterion 2: an `Exclude` then an `Unexclude` on a file that had no `[[repo]]` array returns
    /// it byte for byte, the array of tables going with the last entry in it.
    #[test]
    fn exclude_then_unexclude_on_a_file_with_no_repo_array_returns_it_byte_for_byte() {
        let before = "# the whole file's value is its comments\ntheme = \"default\"\n\n\
                      [refresh]\npoll_interval = \"2s\"   # a trailing comment\n\n\
                      # a comment at the end of the file\n";

        let ignored = apply(before, &path("~/dev/noisy"), Edit::Exclude, "2026-09-01")
            .expect("the document parses");
        assert!(
            ignored.contains("[[repo]]"),
            "the ignore has to have written something for the round trip to prove anything: \
             {ignored:?}"
        );
        let unexcluded = apply(
            &ignored,
            &path("~/dev/noisy"),
            Edit::Unexclude,
            "2026-09-01",
        )
        .expect("the written document parses");

        assert_eq!(unexcluded, before);
    }

    /// [0028](../../../../docs/adr/0028-repon-writes-the-repo-entries-it-owns.md)'s measured
    /// claim, made a test: an appended entry lands after the last existing `[[repo]]` and
    /// before the array of tables that follows it, rather than at the end of the file.
    #[test]
    fn an_appended_entry_lands_after_the_last_existing_repo_entry() {
        let before = commented_fixture();

        let after = apply(&before, &path("~/dev/noisy"), Edit::Exclude, "2026-09-01")
            .expect("the fixture parses");

        let lines: Vec<&str> = after.lines().collect();
        let appended = lines
            .iter()
            .position(|line| *line == "path = \"~/dev/noisy\"")
            .expect("the appended entry is there");
        let vendor_mirror = lines
            .iter()
            .position(|line| *line == "path = \"~/dev/vendor-mirror\"")
            .expect("the last existing entry is still there");
        let first_launcher = lines
            .iter()
            .position(|line| *line == "[[launcher]]")
            .expect("the following array of tables is still there");
        assert!(
            vendor_mirror < appended && appended < first_launcher,
            "the appended entry must land after the last `[[repo]]` and before the following \
             `[[launcher]]`, got {after:?}"
        );
    }

    /// Criterion 2's other half: the end-of-file comment stays at the end rather than being
    /// captured by the appended table, which is what the byte-for-byte round trip above
    /// would otherwise hide by restoring either way.
    #[test]
    fn an_appended_entry_lands_after_a_trailing_comment_rather_than_capturing_it() {
        let before = "theme = \"default\"\n\n# a comment at the end of the file\n";

        let after = apply(before, &path("~/dev/noisy"), Edit::Exclude, "2026-09-01")
            .expect("the document parses");

        let end_of_file = after
            .lines()
            .position(|line| line == "# a comment at the end of the file")
            .expect("the trailing comment survives");
        let header = after
            .lines()
            .position(|line| line == "[[repo]]")
            .expect("the appended entry is there");
        assert!(
            header < end_of_file,
            "the trailing comment must stay at the end rather than being captured as the \
             appended table's own leading comment: {after:?}"
        );
    }

    /// Criterion 3: `Unexclude` on an entry carrying `default_branch` removes the `exclude`
    /// key alone and leaves the table, since the table still states a fact.
    #[test]
    fn unexclude_on_an_entry_carrying_default_branch_removes_exclude_alone() {
        let before = "# pinned, and ignored for now\n[[repo]]\npath = \"~/dev/legacy-api\"\n\
                      default_branch = \"main\"\nexclude = true\n";

        let after = apply(
            before,
            &path("~/dev/legacy-api"),
            Edit::Unexclude,
            "2026-09-01",
        )
        .expect("the document parses");

        assert_eq!(
            after,
            "# pinned, and ignored for now\n[[repo]]\npath = \"~/dev/legacy-api\"\n\
             default_branch = \"main\"\n"
        );
    }

    /// Criterion 3's boundary: the same edit on an entry carrying nothing but `path` and
    /// `exclude` takes the whole table, and the array of tables with it.
    #[test]
    fn unexclude_on_an_entry_left_with_nothing_but_path_removes_the_table_and_the_array() {
        let before = "theme = \"default\"\n\n[[repo]]\npath = \"~/dev/noisy\"\nexclude = true\n";

        let after = apply(before, &path("~/dev/noisy"), Edit::Unexclude, "2026-09-01")
            .expect("the document parses");

        assert!(
            !after.contains("[[repo]]") && !after.contains("noisy"),
            "an entry left with nothing but `path` must go entirely: {after:?}"
        );
    }

    /// Criterion 4: an appended entry carries its provenance comment on the line above it,
    /// in the shape repo-management.md's own example shows, and the date it names is the one
    /// it was given.
    #[test]
    fn an_appended_entry_carries_its_provenance_comment_on_the_line_above_it() {
        let after = apply("", &path("~/dev/noisy"), Edit::Exclude, "2026-09-01")
            .expect("an empty document parses");

        let lines: Vec<&str> = after.lines().filter(|line| !line.is_empty()).collect();
        assert_eq!(
            lines,
            vec![
                "# ignored from Repon on 2026-09-01",
                "[[repo]]",
                "path = \"~/dev/noisy\"",
                "exclude = true",
            ],
            "got {after:?}"
        );
    }

    /// Criterion 4, pinned to the specification rather than to this module's own words: the
    /// fenced example in repo-management.md is read at test time and reproduced from
    /// [`apply`]'s own output for the same path and date, so the comment's wording cannot
    /// drift from the document that fixes it.
    #[test]
    fn the_appended_entry_matches_repo_management_mds_own_fenced_example() {
        let spec = std::fs::read_to_string(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("../../docs/spec/repo-management.md"),
        )
        .expect("read docs/spec/repo-management.md");
        let fenced = spec
            .split("```toml\n")
            .nth(1)
            .and_then(|rest| rest.split("```").next())
            .expect("repo-management.md still carries its fenced provenance example");
        let date = fenced
            .lines()
            .next()
            .and_then(|line| line.rsplit(' ').next())
            .expect("the example's comment names a date");

        let written =
            apply("", &path("~/dev/noisy"), Edit::Exclude, date).expect("an empty document parses");

        assert_eq!(written.trim_start_matches('\n'), fenced);
    }

    /// The entry Repon appends is matched again by the absolute path the entity is known by,
    /// not only by the `~`-relative string it was written as, which is what makes an
    /// an `Unexclude` after an `Exclude` find its own entry at all.
    #[test]
    fn an_appended_entry_is_found_again_by_the_absolute_path_it_was_written_for() {
        let absolute = expand_home("~/dev/noisy");
        let written =
            apply("", &absolute, Edit::Exclude, "2026-09-01").expect("an empty document parses");

        assert_eq!(
            find_entry(&written.parse().expect("parses"), &absolute),
            Some(0)
        );
    }

    /// `delete`'s other half: the path it destroyed stops being named by the `[[set]]`
    /// arrays that listed it too, in every Set that listed it, rather than only in the
    /// `[[repo]]` entry it happened to have.
    #[test]
    fn removing_an_entry_also_removes_the_path_from_every_set_include_array_naming_it() {
        let before = "[[set]]\nname = \"one\"\nroots = [\"~/dev\"]\n\
                      include = [\"~/dev/gone\", \"~/dev/kept\"]\n\n\
                      [[set]]\nname = \"two\"\nroots = [\"~/dev\"]\n\
                      include = [\"~/dev/other\", \"~/dev/gone\"]\n";

        let after = apply(before, &path("~/dev/gone"), Edit::Remove, "2026-09-01")
            .expect("the document parses");

        assert!(
            !after.contains("gone"),
            "no Set may go on naming a path `delete` destroyed: {after:?}"
        );
        assert!(
            after.contains("\"~/dev/kept\"") && after.contains("\"~/dev/other\""),
            "every other path a Set names is left alone: {after:?}"
        );
    }

    /// The same for a Set's `exclude` array, which names paths on the identical terms its
    /// `include` does.
    #[test]
    fn removing_an_entry_also_removes_the_path_from_a_set_exclude_array_naming_it() {
        let before = "[[set]]\nname = \"one\"\nroots = [\"~/dev\"]\n\
                      exclude = [\"~/dev/gone\", \"**/node_modules/**\"]\n";

        let after = apply(before, &path("~/dev/gone"), Edit::Remove, "2026-09-01")
            .expect("the document parses");

        assert!(
            !after.contains("gone") && after.contains("\"**/node_modules/**\""),
            "the path goes and the glob beside it stays: {after:?}"
        );
    }

    /// A path Repon knows exactly is removed; a glob that merely would have matched it is
    /// not. The glob states a class, so dropping it would change what the Set means for
    /// every other row it covers.
    #[test]
    fn removing_an_entry_leaves_a_set_glob_that_would_have_matched_the_deleted_path_alone() {
        let before = commented_fixture();

        let after = apply(
            &before,
            &path("~/dev/acme/checkout"),
            Edit::Remove,
            "2026-09-01",
        )
        .expect("the fixture parses");

        assert_eq!(
            after, before,
            "a glob that would have matched the deleted path is not a name for it"
        );
    }

    /// A Set array whose last named path was the deleted one goes with it, rather than being
    /// left as an empty array: an empty `include` reads as "nothing" and means "everything"
    /// to discovery, so the key that says nothing is removed the same way a `[[repo]]` entry
    /// left with nothing but `path` is.
    #[test]
    fn a_set_array_left_empty_by_a_removal_goes_with_the_last_path_in_it() {
        let before = "[[set]]\nname = \"one\"\nroots = [\"~/dev\"]\n\
                      include = [\"~/dev/gone\"]\nexclude = [\"~/dev/gone\"]\n";

        let after = apply(before, &path("~/dev/gone"), Edit::Remove, "2026-09-01")
            .expect("the document parses");

        assert_eq!(after, "[[set]]\nname = \"one\"\nroots = [\"~/dev\"]\n");
    }

    /// A Set names its paths the way a `[[repo]]` entry does, so the absolute path the
    /// entity is known by finds the `~`-relative string the user wrote.
    #[test]
    fn a_set_path_written_relative_to_home_is_found_by_the_absolute_path_it_expands_to() {
        let before = "[[set]]\nname = \"one\"\nroots = [\"~/dev\"]\n\
                      include = [\"~/dev/gone\", \"~/dev/kept\"]\n";

        let after = apply(
            before,
            &expand_home("~/dev/gone"),
            Edit::Remove,
            "2026-09-01",
        )
        .expect("the document parses");

        assert!(!after.contains("gone"), "got {after:?}");
    }

    /// `Exclude` and `Unexclude` state a fact about one `[[repo]]` entry and never about a
    /// Set: only the removal `delete` performs reaches a `[[set]]` array at all.
    #[test]
    fn exclude_and_unexclude_leave_every_set_array_untouched() {
        let before = "[[set]]\nname = \"one\"\nroots = [\"~/dev\"]\n\
                      include = [\"~/dev/noisy\"]\n";

        for edit in [Edit::Exclude, Edit::Unexclude] {
            let after = apply(before, &path("~/dev/noisy"), edit, "2026-09-01")
                .expect("the document parses");

            assert!(
                after.contains("include = [\"~/dev/noisy\"]"),
                "{edit:?} must leave the Set naming it alone: {after:?}"
            );
        }
    }

    /// `Edit::Remove` on a path with no `[[repo]]` entry at all leaves the file alone, which
    /// is the ordinary case for `delete` on a Repo the user never configured.
    #[test]
    fn removing_an_entry_that_was_never_there_changes_nothing() {
        let before = commented_fixture();

        let after = apply(
            &before,
            &path("~/dev/never-configured"),
            Edit::Remove,
            "2026-09-01",
        )
        .expect("the fixture parses");

        assert_eq!(after, before);
    }

    /// The file on disk is what is read and written, never a serialisation of the in-memory
    /// document: a key this crate's schema does not know survives a write it was not part of.
    #[test]
    fn a_key_this_crates_schema_never_reads_survives_a_write() {
        let dir = tempfile::tempdir().expect("temp dir");
        let file = dir.path().join("config.toml");
        std::fs::write(
            &file,
            "# hand-written\nsomething_repon_has_never_heard_of = 3\n",
        )
        .expect("write the config file");

        let written = write(&file, &path("~/dev/noisy"), Edit::Exclude).expect("the write runs");

        assert!(written.changed);
        let after = std::fs::read_to_string(&file).expect("read it back");
        assert!(
            after.contains("something_repon_has_never_heard_of = 3")
                && after.contains("# hand-written"),
            "a read-modify-write of the file on disk must keep what it does not understand: \
             {after:?}"
        );
    }

    /// A first `ignore` with no config file at all writes one rather than failing, the same
    /// way a missing file is not an error to read.
    #[test]
    fn a_write_with_no_config_file_at_all_creates_one() {
        let dir = tempfile::tempdir().expect("temp dir");
        let file = dir.path().join("nested").join("config.toml");

        let written = write(&file, &path("~/dev/noisy"), Edit::Exclude).expect("the write runs");

        assert!(written.changed);
        let after = std::fs::read_to_string(&file).expect("read it back");
        assert!(after.contains("[[repo]]"), "got {after:?}");
    }

    /// [`today`] is the date half of the core's own RFC 3339 rendering, so the provenance
    /// comment cannot carry a second, differently-computed calendar.
    #[test]
    fn today_is_the_date_half_of_the_cores_own_timestamp_rendering() {
        let today = today();

        assert!(
            repon_core::Timestamp::now().to_string().starts_with(&today),
            "expected today's date to lead the core's own timestamp, got {today:?}"
        );
        assert_eq!(today.len(), "2026-09-01".len());
    }
}