shep 0.2.0

The shep binary: a process manager that keeps a flock of long-running processes alive on macOS, Linux and Windows, with logs, watch and cron restarts, and webhook alerts
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
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
//! Moving `[dog.<name>]` out of `shep.toml` and into `dogs.toml`, once,
//! and the one write path `dogs.toml` has.
//!
//! [`migrate_dog_sections`] runs at the top of every daemon boot and does
//! nothing on all but the first. [`forget_dog_section`] is the other
//! writer, `shep rehome`'s half of forgetting a dog, and it lives here
//! rather than beside that verb because both go through
//! [`write_dogs_config`]: that file holds webhook credentials at `0600`,
//! and one staged-temp-`fsync`-`rename` helper with the reasoning attached
//! is what keeps a second writer from reaching for `std::fs::write`.
//!
//! **Both hold `dogs.toml`'s own [`ConfigLock`] across the whole
//! read-modify-write**, the same discipline [`ShepToml::edit`] applies to
//! `shep.toml` and for the same reason: each rewrites the entire file, so
//! two unserialised writers lose one of each other's edits rather than
//! colliding visibly. Two `shep rehome` calls for two different dogs, out
//! of the sort of provisioning script `docs/dogs.md` tells operators is
//! safe, is the ordinary way to reach that. When both locks are held,
//! `shep.toml`'s is always the outer one. `RawDaemonConfig` keeps its `dog` field so an un-migrated file
//! still parses: deleting it would turn `deny_unknown_fields` into a
//! refused boot for every operator carrying a dog section, with the flock
//! left unsupervised at exactly the moment nobody is watching.

use core::fmt;
use std::collections::{BTreeMap, BTreeSet};
use std::io::Write as _;
use std::path::Path;

use shep_core::config::{DogsConfig, DogsConfigError};
use shep_core::paths::ShepPaths;
use toml_edit::{DocumentMut, Item, TableLike};

use super::shep_toml::{ConfigLock, ShepToml, ShepTomlError, create_config_file};

/// Moves every `[dog.<name>]` section into `dogs.toml`, returning the names
/// moved
///
/// Empty when there was nothing to move, which is every boot after the
/// first. Writes `dogs.toml` before striking `shep.toml`, so a crash
/// between the two leaves the sections readable from the old file rather
/// than from neither. On unix both writes flush the directory holding
/// them, which is what makes that an order at all rather than two renames
/// a power cut can lose independently; on Windows `sync_dir` does nothing
/// and the order holds only against an ordinary crash.
///
/// # Errors
///
/// - [`DogMigrationError::WouldOverwrite`] when a name holds VALUES in
///   BOTH files. Two values for one key is a question shep cannot answer,
///   so it refuses and changes nothing. An empty section is not one of the
///   two on either side: an empty `[dog.<name>]` in the source is skipped
///   (see [`declared_dog_names`]) and an empty `[<name>]` in the
///   destination is written over.
/// - [`DogMigrationError::SectionsUnreadable`] when `shep.toml` declares a
///   name under `[dog]` that did not come back as a section to move.
///   Refused rather than skipped: `take_dog_sections` has already struck
///   the whole `[dog]` table by then, so moving what came back would drop
///   what did not.
/// - [`DogMigrationError::Parse`] when `dogs.toml` is not valid TOML, and
///   [`DogMigrationError::Read`], [`DogMigrationError::ReadDogs`],
///   [`DogMigrationError::Lock`], [`DogMigrationError::Write`] and
///   [`DogMigrationError::Toml`] for the underlying I/O. There is no
///   rendering failure to report: a [`DocumentMut`] always renders.
pub(crate) fn migrate_dog_sections(paths: &ShepPaths) -> Result<Vec<String>, DogMigrationError> {
    let existing_source = match std::fs::read_to_string(&paths.daemon_config) {
        Ok(source) => source,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(err) => return Err(DogMigrationError::Read(err)),
    };
    // One parse of the string already in memory, answering both questions
    // this function has to ask before it may open the document: is there
    // anything to move, and which names. A read-only `toml::Table` parse
    // opens no file and costs nothing next to the boot around it.
    //
    // Not a substring test, which is what this was. `[dog.` and `[dog]`
    // are two of the spellings a `[dog]` header has and TOML allows the
    // others: `[ dog.metrics ]` and `[dog . metrics]` are the same section
    // and matched neither, so the migration reported nothing to do, the
    // section stayed in a file nothing reads any more, and the dog came up
    // on compiled defaults with no warning on any surface. For bark that
    // is every sink gone. A parse knows the spellings; a substring cannot.
    //
    // Skipping the open when there is nothing to move is load-bearing
    // rather than an optimisation. `ShepToml::edit` and `try_edit` both
    // stage a temp file and rename it over the original whenever `save`
    // runs, so opening the document at all would give an untouched
    // `shep.toml` a fresh inode, force `OWNER_ONLY_FILE_MODE` on it, and
    // replace a symlinked path with a plain file. Every boot after the
    // first reaches this line, so that cost would land on everyone.
    //
    // `[dog]` on its own is a header with nothing under it: a section
    // neither to move nor to lose, and refusing on it would leave an
    // operator with a stray `[dog]` line unable to boot at all. A
    // `[dog.metrics]` holding no values is the same shape one level down
    // and is skipped for the same reason -- see [`declared_dog_names`].
    //
    // `None` means this parser could not read the source at all. That is
    // not decided here: the document is opened and it falls through to
    // `ShepToml`, whose own parse error names the file and the line, and
    // the guard inside the closure falls back to the only question it can
    // still answer.
    let declared = existing_source
        .parse::<toml::Table>()
        .ok()
        .map(|table| declared_dog_names(&table));
    if declared.as_ref().is_some_and(BTreeSet::is_empty) {
        return Ok(Vec::new());
    }

    // `try_edit`, never `edit`. `edit` calls `save` unconditionally
    // (shep_toml.rs:173), so refusing from inside it would strike the
    // sections from `shep.toml` and only then fail, leaving them in
    // neither file. `try_edit`'s own `Err` skips `save` entirely and
    // leaves `path` exactly as it was found.
    ShepToml::try_edit(&paths.daemon_config, |doc| {
        // Empty sections dropped here, matching what [`declared_dog_names`]
        // already left out of `declared`, so the two agree on what there
        // was to move. An empty one is not moved and not counted as
        // missing: there is nothing in it to arrive at the other end. It
        // does still go, because `take_dog_sections` removes the whole
        // `[dog]` table, and striking an empty header an older `shep
        // enable` scaffolded is the right outcome anyway. Only the sections
        // beside it are what made this boot open the file at all.
        let incoming: BTreeMap<String, Item> = doc
            .take_dog_sections()
            .into_iter()
            .filter(|(_, section)| !section.as_table_like().is_some_and(TableLike::is_empty))
            .collect();
        // `take_dog_sections` removes the WHOLE `[dog]` table and then
        // decides what to hand back, so anything it drops on the way is
        // gone from the document with nothing written in its place: a
        // failed internal reparse hands back nothing at all, and its filter
        // drops a non-table entry while keeping the tables beside it. That
        // second shape is the one a count cannot see, since `[dog] stray =
        // 5` next to `[dog.metrics]` comes back one entry long and not
        // empty. So the guard is over NAMES, comparing what the source
        // declared against what came back, and it refuses before anything
        // is written: `try_edit`'s own `Err` is what makes that a `save`
        // that never happens.
        //
        // With no readable source there are no names to compare, and the
        // fallback is the weaker question: did anything come back at all.
        let missing: Vec<String> = match &declared {
            Some(names) => names
                .iter()
                .filter(|name| !incoming.contains_key(*name))
                .cloned()
                .collect(),
            None => Vec::new(),
        };
        if !missing.is_empty() || incoming.is_empty() {
            return Err(DogMigrationError::SectionsUnreadable { names: missing });
        }
        // `dogs.toml`'s own lock, taken here rather than at the top of the
        // function so that this whole read-and-merge is one transaction
        // against the other writer of that file,
        // [`forget_dog_section`]. Nested INSIDE `shep.toml`'s lock, which
        // `try_edit` already holds: that is the ordering both call sites
        // keep, and the reason a deadlock is not reachable. This is the
        // only place either lock is nested in the other at all, and it
        // never takes them the other way round.
        let _dogs_lock =
            ConfigLock::acquire(&paths.dogs_config).map_err(DogMigrationError::Lock)?;
        // The destination as a live document, not a `toml::Table`: a
        // second migration writes into a `dogs.toml` an operator has been
        // hand-editing since the first one, and a `toml::to_string` of a
        // parsed map hands that file back with every comment gone (spec
        // decision 1 calls this file hand-editable, and decision 9 promises
        // `toml_edit` for exactly this reason).
        let mut merged = read_dogs_document(&paths.dogs_config)?;
        // Over VALUES on both sides, the same rule `incoming`'s own filter
        // and [`declared_dog_names`] apply to the source. `WouldOverwrite`
        // exists because two values for one key is a question shep cannot
        // answer, and a bare `[metrics]` in `dogs.toml` is not one of the
        // two: there is no second value to guess between, so the section
        // carrying values wins and the header it lands on held nothing to
        // lose. Refusing on it took a boot down over an empty header, the
        // same way the source side did before
        // `an_empty_section_colliding_with_a_configured_one_is_not_a_refusal`.
        //
        // Table-like only, deliberately. A destination `[[metrics]]` is an
        // array of tables and not a section this migration could merge
        // into, so it still refuses rather than being quietly replaced.
        let collides = |name: &String| {
            merged
                .get(name)
                .is_some_and(|item| !item.as_table_like().is_some_and(TableLike::is_empty))
        };
        if let Some(name) = incoming.keys().find(|name| collides(name)) {
            return Err(DogMigrationError::WouldOverwrite { name: name.clone() });
        }
        let mut moved: Vec<String> = incoming.keys().cloned().collect();
        moved.sort();

        // Appended, never wedged into the middle. A table taken out of
        // `shep.toml` still carries the position it held THERE, and
        // `toml_edit` renders tables in position order, so a
        // `[dog.metrics]` that was the first table in `shep.toml` lands
        // between the first and second tables of an operator's `dogs.toml`
        // -- inside the blank line that separated them. Renumbering from
        // one past the destination's own last table is what makes a
        // migration read like an append.
        //
        // Over EVERY positioned table in the destination, not the
        // top-level `Item::Table`s alone, which is what this counted. A
        // `dogs.toml` whose own sections are `[bark.sinks]` (nested under
        // an implicit `bark` that holds no position of its own) and
        // `[[bark.rules]]` (an array of tables, never an `Item::Table`)
        // answered "no positions at all", so the scan said 0, the moved
        // section took 0, and it rendered FIRST and jammed against the
        // section it was supposed to follow. That is the shape a real
        // `dogs.toml` has as soon as bark is configured.
        let mut next = merged
            .iter()
            .filter_map(|(_, item)| last_position(item))
            .max()
            .map_or(0, |last| last + 1);
        for (name, mut section) in incoming {
            renumber_tables(&mut section, &mut next);
            merged.insert(&name, section);
        }
        // Written before this closure returns, so `save` strikes the old
        // sections only once the new file already holds them. A crash
        // between the two leaves them readable from `shep.toml`, which is
        // the direction that loses nothing.
        //
        // "Before" is a claim about durability, not about statement order,
        // and on unix it holds only because `write_dogs_config` flushes the
        // directory it renamed into. Without that the two renames are
        // independent under a power cut, and the interleaving that loses
        // this one while landing the strike leaves the sections in NEITHER
        // file: an operator's webhook URLs gone, from a path whose whole
        // argument was that it could not happen.
        //
        // What the surviving interleaving costs is a refusal, not data.
        // Landing here and losing the strike leaves values under both
        // `[dog.<name>]` and `[<name>]`, which is what `collides` above
        // answers `WouldOverwrite` to, so the next boot stops and says so
        // rather than guessing between two values. Recoverable by hand and
        // loud, which is the trade this order is choosing.
        write_dogs_config(&paths.dogs_config, &merged.to_string())
            .map_err(DogMigrationError::Write)?;
        Ok(moved)
    })
}

/// Removes `name`'s section from `dogs.toml`, answering whether there was
/// one to remove.
///
/// `shep rehome <name>`'s half of the cross-file forget: [`ShepToml`] owns
/// `shep.toml` alone, so `rehome_dog` strikes the registration and this
/// strikes the configuration. A missing `dogs.toml`, or one with no
/// section under `name`, is `Ok(false)` and writes nothing: rehoming a dog
/// that was never configured is an ordinary thing to do, not a fault.
///
/// Called after `shep.toml` has already been rewritten, deliberately. The
/// two writes are not one transaction, and of the two ways a crash between
/// them can land, this is the harmless one: a section nothing reads, since
/// the name is out of `enabled_dogs` and `adopted_dogs` by then. The other
/// order loses an operator's webhook URLs while the dog is still enabled
/// and still running, and says nothing about it.
///
/// Which of the two lands is only decided by the order once each rename is
/// durable by itself. On unix both writers flush the directory they
/// renamed into for that reason: a power cut between them can otherwise
/// lose the `shep.toml` rewrite while keeping this removal, which is the
/// bad order reached by accident. `sync_dir` does nothing on Windows, so
/// there the order survives a crash but not a power cut.
///
/// # Errors
///
/// - [`DogMigrationError::ReadDogs`] when `dogs.toml` exists and cannot be
///   read, and [`DogMigrationError::Parse`] when it is not valid TOML.
///   Refused rather than replaced: a file this verb cannot understand is
///   not one it may overwrite.
/// - [`DogMigrationError::Lock`] when this file's sibling lock could not be
///   taken, and [`DogMigrationError::Write`] when the staged replacement
///   fails.
///
/// The error type is shared with [`migrate_dog_sections`] rather than
/// split: every variant either half can produce says which of the two
/// files failed and how, which is what an operator needs from both.
pub(crate) fn forget_dog_section(path: &Path, name: &str) -> Result<bool, DogMigrationError> {
    // Held across the read, the removal and the rename, and dropped on the
    // way out of this function. Without it, two `shep rehome` calls for two
    // different dogs, backgrounded together out of a provisioning script,
    // both read the file before either writes and the second rename puts
    // one of the two removals back: a whole-file read-modify-write with
    // nothing serialising it. `docs/dogs.md` promises a provisioning script
    // exactly this guarantee. This function takes no other lock, so it can
    // never be the half of a deadlock that holds `dogs.toml` and waits on
    // `shep.toml`.
    let _lock = ConfigLock::acquire(path).map_err(DogMigrationError::Lock)?;
    let mut doc = read_dogs_document(path)?;
    if doc.remove(name).is_none() {
        return Ok(false);
    }
    write_dogs_config(path, &doc.to_string()).map_err(DogMigrationError::Write)?;
    Ok(true)
}

/// Reads `path` as an editable document, treating a missing file as an
/// empty one.
///
/// Both writers of `dogs.toml` read it this way, and both call this with
/// that file's [`ConfigLock`] already held: a read outside the lock is the
/// first half of a lost update, not a cheap shortcut.
///
/// A [`DocumentMut`] rather than a [`DogsConfig`], because both writers
/// rewrite the whole file and an operator is invited to hand-edit it. Every
/// comment, key order and inline table survives a `toml_edit` round trip
/// and none of them survives a `toml::to_string` of a parsed map, which is
/// what one `shep rehome` used to do to a commented file.
///
/// [`DogsConfig::load`] stays as the gate in front of that, unconditional
/// and first. It is strictly the stricter of the two parses -- a stray
/// top-level scalar is a valid document and not a valid `DogsConfig` -- and
/// it is the same call `shep_daemon::dogs` reads this file with, so a file
/// this gate refuses is one the daemon could not have served either.
/// Refusing it here is the rule both writers already followed: a file this
/// verb cannot understand is not one it may overwrite.
///
/// # Errors
///
/// - [`DogMigrationError::ReadDogs`] when the file exists and could not be
///   read, and [`DogMigrationError::Parse`] when it is not valid TOML.
fn read_dogs_document(path: &Path) -> Result<DocumentMut, DogMigrationError> {
    let source = match std::fs::read_to_string(path) {
        Ok(source) => source,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            return Ok(DocumentMut::new());
        }
        Err(err) => return Err(DogMigrationError::ReadDogs(err)),
    };
    DogsConfig::load(Some(&source)).map_err(DogMigrationError::Parse)?;
    source.parse::<DocumentMut>().map_err(|_| {
        // No input reaches this. `toml` 0.8 is a thin layer over
        // `toml_edit`, so a source the gate above accepted parses here as
        // well. Reported rather than `expect`ed all the same: this runs at
        // the top of every daemon boot, and a boot is not a place to
        // panic on a disagreement between two parsers.
        DogMigrationError::ReadDogs(std::io::Error::other(
            "dogs.toml parses as TOML values and not as an editable document",
        ))
    })
}

/// Every name `table` declares a VALUE for under `[dog]`.
///
/// Read from a second parse of a file [`ShepToml`] is about to parse
/// again, and deliberately so: it is the only record of what was there
/// BEFORE [`ShepToml::take_dog_sections`] struck the table, which is what
/// the guard inside [`migrate_dog_sections`] compares against. Read-only,
/// over a string already in memory, and it never opens the file. Empty
/// also means "do not open the file at all", so this is the whole of that
/// caller's gate as well as its record.
///
/// A name holding nothing is left out, and that is the whole of
/// [`declares_nothing`]'s reason to exist. `shep enable metrics` on any
/// binary older than this branch scaffolds an EMPTY `[dog.metrics]`, and
/// this branch's own `enable` no longer does -- but a mixed-version host is
/// ordinary, so the shape keeps arriving. Counting it as a declared name
/// made the new binary refuse to boot against a `dogs.toml` that already
/// held `metrics`, on a `WouldOverwrite` whose own doc says "two values for
/// one key". An empty table is not a value.
fn declared_dog_names(table: &toml::Table) -> BTreeSet<String> {
    match table.get("dog") {
        Some(toml::Value::Table(dog)) => dog
            .iter()
            .filter(|(_, value)| !declares_nothing(value))
            .map(|(name, _)| name.clone())
            .collect(),
        // No `[dog]` at all, or a `dog` that is not a table: either way it
        // declares no dog and there is nothing here to open the document
        // for.
        _ => BTreeSet::new(),
    }
}

/// Whether `value` holds nothing an operator could lose by not moving it.
///
/// An empty table, an empty array, and an array of tables that are all
/// empty. That last one is why this recurses rather than testing
/// `Table::is_empty` directly: `[[dog.metrics]]` with nothing under it used
/// to reach [`DogMigrationError::SectionsUnreadable`], because the name was
/// declared and [`ShepToml::take_dog_sections`] hands back no array. Under
/// the pre-flight that refusal is a boot the operator has to repair by
/// hand, over a header holding nothing.
///
/// A `[[dog.metrics]]` that DOES carry values is a different question and
/// still refuses: there is no one section for it to become, and dropping it
/// silently is the outcome the name guard exists to prevent.
fn declares_nothing(value: &toml::Value) -> bool {
    match value {
        toml::Value::Table(table) => table.is_empty(),
        toml::Value::Array(items) => items.iter().all(declares_nothing),
        _ => false,
    }
}

/// The highest render position any table inside `item` holds, or `None`
/// when it holds no positioned table at all.
///
/// [`renumber_tables`]'s read-only twin, and it walks the same three
/// shapes for the same reason: `toml_edit` positions every table
/// individually, so a nested `[bark.sinks]` and an `[[bark.rules]]` entry
/// each carry one and neither is an `Item::Table` at the top level. A scan
/// that looked only there reported no positions for a `dogs.toml` made
/// entirely of those, and the migration then appended at 0.
///
/// An implicit parent (`bark` itself, when the file only ever wrote
/// `[bark.sinks]`) has no position of its own, hence the descent into
/// children rather than a test on the parent alone.
fn last_position(item: &Item) -> Option<usize> {
    match item {
        Item::Table(table) => table
            .position()
            .into_iter()
            .chain(table.iter().filter_map(|(_, child)| last_position(child)))
            .max(),
        Item::ArrayOfTables(array) => array
            .iter()
            .flat_map(|table| {
                table
                    .position()
                    .into_iter()
                    .chain(table.iter().filter_map(|(_, child)| last_position(child)))
            })
            .max(),
        // Neither holds a positioned table: an inline `metrics = { .. }`
        // is a key/value pair and renders above the tables, with the other
        // pairs.
        Item::Value(_) | Item::None => None,
    }
}

/// Walks `item` depth-first and gives every table it holds the next
/// document position, so a section moved out of `shep.toml` renders after
/// everything already in `dogs.toml` rather than at the index it happened
/// to hold in the file it came from.
///
/// Depth-first and over sub-tables too, because `toml_edit` renders every
/// table by its own position and not by its parent's: renumbering only the
/// top-level `bark` would leave `[bark.sinks]` back at `shep.toml`'s
/// index, split away from the header it belongs under.
///
/// [`Item::Value`] and [`Item::None`] hold no positioned table --- an
/// inline `metrics = { .. }` is a key/value pair and renders with the
/// others, above the tables --- so both are left alone.
fn renumber_tables(item: &mut Item, next: &mut usize) {
    match item {
        Item::Table(table) => {
            table.set_position(*next);
            *next += 1;
            for (_, child) in table.iter_mut() {
                renumber_tables(child, next);
            }
        }
        Item::ArrayOfTables(array) => {
            for table in array.iter_mut() {
                table.set_position(*next);
                *next += 1;
                for (_, child) in table.iter_mut() {
                    renumber_tables(child, next);
                }
            }
        }
        Item::Value(_) | Item::None => {}
    }
}

/// Writes `rendered` to `path`: staged in a sibling temp file at
/// `OWNER_ONLY_FILE_MODE`, `fsync`ed, then `rename`d over `path`.
///
/// The same three steps, through the same helper, that
/// [`ShepToml::save`] writes `shep.toml` with, and for the same two
/// reasons. **Mode**: these bytes are the ones that used to sit inside
/// `shep.toml` at `0600`, and they are where `docs/dogs.md` tells an
/// operator to paste a Discord or Slack webhook URL, which is a bearer
/// token in a path. A `std::fs::write` here would create the file at the
/// ambient umask, typically `0644`, so the migration itself would be the
/// downgrade. `$SHEP_HOME` being `0700` does not answer it: a `tar`, a
/// `cp -p` or a backup carries a file's own mode somewhere no directory
/// mode follows. **Atomicity**: `std::fs::write` opens `O_TRUNC`, so a
/// crash between the truncate and the write leaves a half-written
/// `dogs.toml` behind; the rename installs the whole file or none of it.
/// **Durability**: on unix the rename is then published by flushing the
/// directory that holds it, without which a power cut can lose the rename
/// while keeping the bytes it pointed at. Both callers order this write
/// against a `shep.toml` write and argue from that order, and an order
/// between two renames means nothing until each one is durable on its own.
/// That flush is a no-op on Windows, which is why those two arguments name
/// the platform rather than claiming the order outright.
fn write_dogs_config(path: &Path, rendered: &str) -> std::io::Result<()> {
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    let mut tmp = create_config_file(parent)?;
    tmp.write_all(rendered.as_bytes())?;
    tmp.as_file().sync_all()?;
    // `persist` is `rename(2)`. On failure the `NamedTempFile` comes back
    // inside the error and its `Drop` removes the staging file, so a failed
    // replace leaves nothing behind in `$SHEP_HOME`.
    tmp.persist(path).map_err(|err| err.error)?;

    // The `sync_all` above made the CONTENTS durable; this makes the rename
    // that published them durable. See `shep_core::atomic_file`.
    shep_core::atomic_file::sync_dir(parent)?;
    Ok(())
}

/// Why `[dog.<name>]` could not be moved into `dogs.toml`
///
/// Derived `Debug`, deliberately (IR-41): every variant carries a dog name,
/// an I/O error, or a serializer's complaint, and never a section's
/// contents, so there is nothing here to redact. That is a claim about the
/// two wrapped types that COULD carry a file, and both of them redact their
/// own `Debug` for exactly that reason: [`ShepTomlError`] for `shep.toml`,
/// and [`DogsConfigError`] for `dogs.toml`. The second one did not, for a
/// while, and this comment asserted it anyway -- a derive over
/// `toml::de::Error` prints the parser's `raw` field, which is the whole
/// source document. A derive here is only ever as safe as what it forwards
/// to, so a new variant wrapping a parse error needs the same check.
#[derive(Debug)]
// `#[non_exhaustive]`: the migration is the one writer of `dogs.toml` and
// will grow refusals as operators meet shapes nobody predicted, so a
// seventh variant should be additive rather than breaking (IR-20).
#[non_exhaustive]
pub(crate) enum DogMigrationError {
    /// `shep.toml` itself could not be read.
    Read(std::io::Error),
    /// `dogs.toml` exists and could not be read.
    ///
    /// Its own variant rather than [`Self::Read`]: both are the same I/O
    /// failure, and an operator's next move depends entirely on which of
    /// the two files it was.
    ReadDogs(std::io::Error),
    /// `dogs.toml` already exists and is not valid TOML.
    Parse(DogsConfigError),
    /// `name` has a section carrying values in both files, so the move
    /// would silently pick one of the two.
    ///
    /// An empty section never raises this, on either side. It is not a
    /// value, it is what every `shep enable` before this branch
    /// scaffolded, and refusing on it took a mixed-version host to a
    /// shepherd that would not boot. In the source it is skipped; in
    /// `dogs.toml` it is the header the moved section lands on.
    WouldOverwrite {
        /// The dog named in both `shep.toml` and `dogs.toml`.
        name: String,
    },
    /// `shep.toml` declares names under `[dog]` that did not come back as
    /// sections to move.
    SectionsUnreadable {
        /// The names that were declared and did not come back, empty when
        /// the source could not be parsed closely enough to name them.
        /// Keys, never values: a dog's name is what an operator typed as a
        /// section header, and it is already what `WouldOverwrite` carries.
        names: Vec<String>,
    },
    /// `dogs.toml` could not be written.
    Write(std::io::Error),
    /// `dogs.toml`'s sibling lock file could not be created or locked.
    ///
    /// Refused rather than pressed on without the lock: the guarantee the
    /// dogs page makes to a provisioning script is the whole reason the
    /// lock is taken, and a write that skips it quietly is worse than one
    /// that says it could not run.
    Lock(std::io::Error),
    /// Reading, locking or rewriting `shep.toml` failed.
    Toml(ShepTomlError),
}

impl fmt::Display for DogMigrationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Read(err) => write!(f, "shep.toml could not be read: {err}"),
            Self::ReadDogs(err) => write!(f, "dogs.toml could not be read: {err}"),
            Self::Parse(err) => write!(f, "dogs.toml could not be read: {err}"),
            Self::WouldOverwrite { name } => write!(
                f,
                "dog '{name}' is configured in both shep.toml and dogs.toml; \
                 delete one of the two sections and start the daemon again"
            ),
            Self::SectionsUnreadable { names } if names.is_empty() => write!(
                f,
                "shep.toml has entries under [dog] that are not dog sections; \
                 give each dog a table of its own, or delete them"
            ),
            Self::SectionsUnreadable { names } => write!(
                f,
                "shep.toml has entries under [dog] that are not dog sections ({}); \
                 give each dog a table of its own, or delete them",
                names.join(", ")
            ),
            Self::Write(err) => write!(f, "dogs.toml could not be written: {err}"),
            Self::Lock(err) => write!(f, "dogs.toml could not be locked: {err}"),
            Self::Toml(err) => write!(f, "shep.toml could not be rewritten: {err}"),
        }
    }
}

impl core::error::Error for DogMigrationError {
    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
        match self {
            Self::Read(err) | Self::ReadDogs(err) | Self::Write(err) | Self::Lock(err) => Some(err),
            Self::Parse(err) => Some(err),
            Self::Toml(err) => Some(err),
            Self::WouldOverwrite { .. } | Self::SectionsUnreadable { .. } => None,
        }
    }
}

// `ShepToml::try_edit` is generic as `E: From<ShepTomlError>`: this is what
// lets its own setup failures (home dir, lock, parse) reach the caller as
// this module's error without a second wrapping layer.
impl From<ShepTomlError> for DogMigrationError {
    fn from(source: ShepTomlError) -> Self {
        Self::Toml(source)
    }
}

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

    /// How many times [`two_rehomes_at_once_both_land`] re-runs its race.
    ///
    /// A lost update needs both threads to read before either renames, and
    /// on this write path (stage, `fsync`, rename) that window is wide, so
    /// one round is usually enough. Twenty costs a few milliseconds and
    /// makes the failure a certainty rather than a likelihood, which is
    /// what a test guarding a race has to be to be worth having.
    const ROUNDS_OF_CONTENTION: u32 = 20;

    fn home_with(shep_toml: &str) -> (tempfile::TempDir, ShepPaths) {
        let dir = tempfile::tempdir().expect("tempdir");
        // `ShepPaths` has no temp-directory constructor and does not grow
        // one for a test's convenience: `resolve` with an empty environment
        // puts the home under `dir` and every other test in this crate
        // builds one the same way.
        let paths = ShepPaths::resolve(&|_| None, dir.path());
        std::fs::create_dir_all(&paths.home).expect("home");
        std::fs::write(&paths.daemon_config, shep_toml).expect("write");
        (dir, paths)
    }

    #[test]
    fn sections_move_and_the_original_loses_them() {
        let (_dir, paths) = home_with(
            "# mine\n[daemon]\nenabled_dogs = [\"metrics\"]\n\n[dog.metrics]\nbind = \"127.0.0.1:9615\"\n",
        );

        let moved = migrate_dog_sections(&paths).expect("migrate");

        assert_eq!(moved, vec!["metrics".to_string()]);
        assert_eq!(
            std::fs::read_to_string(&paths.daemon_config).expect("read"),
            "# mine\n[daemon]\nenabled_dogs = [\"metrics\"]\n"
        );
        let written = std::fs::read_to_string(&paths.dogs_config).expect("read");
        let parsed = DogsConfig::load(Some(&written)).expect("valid");
        assert_eq!(
            parsed.dog["metrics"]["bind"].as_str(),
            Some("127.0.0.1:9615")
        );
    }

    #[test]
    fn a_file_with_no_dog_sections_is_not_rewritten() {
        let before = "[daemon]\nlog_level = \"info\"\n";
        let (_dir, paths) = home_with(before);

        let moved = migrate_dog_sections(&paths).expect("migrate");

        assert!(moved.is_empty());
        assert_eq!(
            std::fs::read_to_string(&paths.daemon_config).expect("read"),
            before
        );
        assert!(!paths.dogs_config.exists(), "no sections means no file");
    }

    #[test]
    fn a_second_boot_writes_nothing() {
        let (_dir, paths) = home_with("[dog.metrics]\nbind = \"127.0.0.1:9615\"\n");
        migrate_dog_sections(&paths).expect("first");
        let after_first = std::fs::read_to_string(&paths.dogs_config).expect("read");

        let moved = migrate_dog_sections(&paths).expect("second");

        assert!(moved.is_empty());
        assert_eq!(
            std::fs::read_to_string(&paths.dogs_config).expect("read"),
            after_first
        );
    }

    // `take_dog_sections` answers an empty map on two paths that have
    // already struck the sections from the document: a failed internal
    // reparse, and a value under `[dog]` that is not a table. Both are
    // close to unreachable, and treating either as "nothing to move" would
    // write an empty `dogs.toml` over a `shep.toml` it had just stripped.
    // `metrics = 5` is the reachable half: legal TOML, a non-table under
    // `[dog]`, and dropped by that method's own filter.
    #[test]
    fn entries_under_dog_that_come_back_as_nothing_make_the_migration_refuse() {
        let (_dir, paths) = home_with("[dog]\nmetrics = 5\n");

        let err = migrate_dog_sections(&paths).expect_err("a section that will not travel");

        assert!(matches!(err, DogMigrationError::SectionsUnreadable { .. }));
        assert_eq!(
            std::fs::read_to_string(&paths.daemon_config).expect("read"),
            "[dog]\nmetrics = 5\n",
            "a refused migration strikes nothing"
        );
        assert!(!paths.dogs_config.exists(), "nor writes anything");
    }

    // The counterpart to the refusal above, and the reason it is keyed on
    // what the file actually holds rather than on the substring gate: a
    // header with nothing under it has no section to move and no section to
    // lose, so it is neither migrated nor refused. Refusing it would leave
    // an operator with a `[dog]` line unable to boot at all.
    #[test]
    fn an_empty_dog_table_is_left_exactly_as_it_was() {
        let before = "[daemon]\nlog_level = \"info\"\n\n[dog]\n";
        let (_dir, paths) = home_with(before);

        let moved = migrate_dog_sections(&paths).expect("migrate");

        assert!(moved.is_empty());
        assert_eq!(
            std::fs::read_to_string(&paths.daemon_config).expect("read"),
            before
        );
        assert!(!paths.dogs_config.exists(), "no sections means no file");
    }

    // Partial loss, which a count cannot see and a name can: the whole
    // `[dog]` table is struck, `metrics` comes back, `stray` does not, and
    // a migration that shipped what came back would drop `stray` from disk
    // with no error and no warning. Refused instead, with the name in the
    // message, because nothing else on the machine holds that line.
    #[test]
    fn an_entry_that_comes_back_beside_a_section_but_not_as_one_makes_the_migration_refuse() {
        let (_dir, paths) =
            home_with("[dog]\nstray = 5\n\n[dog.metrics]\nbind = \"127.0.0.1:9615\"\n");

        let err = migrate_dog_sections(&paths).expect_err("stray would be dropped");

        let DogMigrationError::SectionsUnreadable { names } = &err else {
            panic!("expected a refusal naming what would be lost, got {err:?}");
        };
        assert_eq!(names, &vec!["stray".to_string()]);
        assert!(err.to_string().contains("stray"), "{err}");
        assert!(
            std::fs::read_to_string(&paths.daemon_config)
                .expect("read")
                .contains("stray = 5"),
            "a refused migration strikes nothing"
        );
        assert!(!paths.dogs_config.exists(), "nor writes anything");
    }

    /// `dogs.toml` holds the webhook URLs that used to sit inside
    /// `shep.toml` at `0600`, so it is created at `0600` too, at the `open`
    /// rather than by a later `chmod`. Fails if the migration goes back to
    /// `std::fs::write`, which would leave it at the ambient umask.
    #[cfg(unix)]
    #[test]
    fn the_written_file_is_owner_only() {
        use std::os::unix::fs::PermissionsExt as _;

        let (_dir, paths) = home_with("[dog.metrics]\nbind = \"127.0.0.1:9615\"\n");

        migrate_dog_sections(&paths).expect("migrate");

        let mode = std::fs::metadata(&paths.dogs_config)
            .expect("stat")
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(mode, 0o600, "mode was {mode:o}");
    }

    /// The bug the lock exists for, forced rather than hoped for: two
    /// `shep rehome` calls for two DIFFERENT dogs, started together the way
    /// a provisioning script backgrounds them, and both removals have to
    /// land. Each call is a whole-file read, remove, rename, so without a
    /// lock both threads read the two-dog file and the second rename puts
    /// the first one's dog back, with nothing anywhere reporting it.
    ///
    /// Two threads and a barrier, not two processes: `flock(2)` is
    /// per-open-file-description rather than per-process, so two threads
    /// that each open the lock file contend exactly as two `shep`
    /// invocations do, and this needs no re-exec harness to prove it.
    /// Repeated over fresh homes because the losing interleaving is a
    /// race, and one round of a race that happens to serialise itself
    /// proves nothing.
    #[test]
    fn two_rehomes_at_once_both_land() {
        use std::sync::{Arc, Barrier};

        for round in 0..ROUNDS_OF_CONTENTION {
            let (_dir, paths) = home_with("");
            std::fs::write(
                &paths.dogs_config,
                "[otel]\nendpoint = \"127.0.0.1:4317\"\n\n[watchdog]\nevery = \"30s\"\n",
            )
            .expect("write");

            let gate = Arc::new(Barrier::new(2));
            let removals: Vec<_> = ["otel", "watchdog"]
                .into_iter()
                .map(|name| {
                    let gate = Arc::clone(&gate);
                    let path = paths.dogs_config.clone();
                    std::thread::spawn(move || {
                        gate.wait();
                        forget_dog_section(&path, name).expect("rehome")
                    })
                })
                .collect();
            for removal in removals {
                assert!(removal.join().expect("thread"), "each found its own dog");
            }

            let left = read_dogs_document(&paths.dogs_config).expect("read");
            assert!(
                left.is_empty(),
                "round {round}: both removals must survive, {:?} came back",
                left.iter().map(|(name, _)| name).collect::<Vec<_>>()
            );
        }
    }

    /// The other pair of writers, and the reason the migration takes the
    /// same lock rather than only the verb that races itself: a boot
    /// migrating a section INTO `dogs.toml` while an operator's `shep
    /// rehome` takes a different dog's section out. Whoever renames second
    /// wins the whole file, so an unlocked pair either resurrects the
    /// rehomed dog or drops the migrated one, and both are silent.
    ///
    /// The migration holds `shep.toml`'s lock while it takes `dogs.toml`'s.
    /// The rehome half takes only `dogs.toml`'s and holds nothing else, so
    /// there is no second ordering for the two to deadlock across.
    #[test]
    fn a_boot_migration_and_a_rehome_at_once_both_land() {
        use std::sync::{Arc, Barrier};

        for round in 0..ROUNDS_OF_CONTENTION {
            let (_dir, paths) = home_with("[dog.metrics]\nbind = \"127.0.0.1:9615\"\n");
            std::fs::write(
                &paths.dogs_config,
                "[otel]\nendpoint = \"127.0.0.1:4317\"\n",
            )
            .expect("write");

            let gate = Arc::new(Barrier::new(2));
            let migrating = {
                let gate = Arc::clone(&gate);
                let paths = paths.clone();
                std::thread::spawn(move || {
                    gate.wait();
                    migrate_dog_sections(&paths).expect("migrate")
                })
            };
            let rehoming = {
                let gate = Arc::clone(&gate);
                let path = paths.dogs_config.clone();
                std::thread::spawn(move || {
                    gate.wait();
                    forget_dog_section(&path, "otel").expect("rehome")
                })
            };
            let moved = migrating.join().expect("thread");
            // Whether the rehome found a section to strike is the one
            // thing the ordering genuinely decides, so it is not asserted
            // on; the file left behind is the same either way.
            let _removed = rehoming.join().expect("thread");

            let left = read_dogs_document(&paths.dogs_config).expect("read");
            // Which of the two ran first is genuinely undecided, and only
            // one ordering has a section for the rehome to find: if it
            // went first, `otel` was struck before the migration merged
            // `metrics` in beside nothing. Both orderings agree on the
            // file that has to be left behind, which is the property.
            assert_eq!(moved, vec!["metrics".to_string()], "round {round}");
            assert_eq!(
                left.iter().map(|(name, _)| name).collect::<Vec<_>>(),
                vec!["metrics"],
                "round {round}: the migrated section stays and the rehomed one goes"
            );
        }
    }

    /// The whole of spec decision 9, at the writer that reproduced its
    /// absence: `shep rehome` used to turn a commented `dogs.toml` with
    /// inline tables into header-per-key output with every comment gone.
    ///
    /// Exact string, not a parse-and-compare, for the same reason
    /// `taking_dog_sections_leaves_every_other_section_alone` pins one: a
    /// reparse agrees on the values, which is precisely what a wrecked
    /// file also does. The comments, the inline table and the blank lines
    /// are the assertion.
    #[test]
    fn forgetting_a_dog_keeps_every_other_comment_and_shape() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("dogs.toml");
        std::fs::write(
            &path,
            "# hand-written, do not clobber\n[otel]\nendpoint = \"127.0.0.1:4317\"\nheaders = { auth = \"x\" }\n\n[metrics]\nbind = \"127.0.0.1:9615\"\n",
        )
        .expect("write");

        assert!(forget_dog_section(&path, "metrics").expect("forget"));

        assert_eq!(
            std::fs::read_to_string(&path).expect("read"),
            "# hand-written, do not clobber\n[otel]\nendpoint = \"127.0.0.1:4317\"\nheaders = { auth = \"x\" }\n"
        );
    }

    /// The same promise at the other writer, and the case that says the
    /// migration's first write is not the only one it makes: a second
    /// `[dog.<name>]` appearing in `shep.toml` after an operator has spent
    /// months hand-editing the `dogs.toml` the first migration created.
    ///
    /// Two properties in one exact string, because they are two halves of
    /// the same round trip. The destination keeps its own comment and its
    /// inline table, and the moved section arrives carrying the comments
    /// an operator wrote around it in `shep.toml` -- both of which a
    /// `toml::to_string` of a parsed map dropped.
    ///
    /// The moved section lands AFTER everything already there, which is
    /// what `renumber_tables` is for: without it `[metrics]` carries the
    /// position it held in `shep.toml` and renders between the
    /// destination's first and second tables.
    #[test]
    fn migrating_into_a_hand_edited_file_keeps_both_files_comments() {
        let (_dir, paths) = home_with(
            "[daemon]\nlog_level = \"info\"\n\n# scrape target\n[dog.metrics]\nbind = \"127.0.0.1:9615\" # loopback only\n",
        );
        std::fs::write(
            &paths.dogs_config,
            "# hand-written, do not clobber\n[otel]\nendpoint = \"127.0.0.1:4317\"\nheaders = { auth = \"x\" }\n",
        )
        .expect("write");

        let moved = migrate_dog_sections(&paths).expect("migrate");

        assert_eq!(moved, vec!["metrics".to_string()]);
        assert_eq!(
            std::fs::read_to_string(&paths.dogs_config).expect("read"),
            "# hand-written, do not clobber\n[otel]\nendpoint = \"127.0.0.1:4317\"\nheaders = { auth = \"x\" }\n\n# scrape target\n[metrics]\nbind = \"127.0.0.1:9615\" # loopback only\n"
        );
    }

    /// Fails if a moved dog with sub-tables and an array of tables is
    /// split across the destination's own sections.
    ///
    /// `toml_edit` renders every table by its own position, not by its
    /// parent's, so renumbering only the top-level `bark` would leave
    /// `[bark.sinks]` and `[[bark.rules]]` at the indices they held in
    /// `shep.toml` -- interleaved with `[a]`, `[b]` and `[c]` here. The
    /// three destination sections staying consecutive is the property.
    #[test]
    fn a_moved_dog_with_sub_tables_lands_in_one_piece_at_the_end() {
        let (_dir, paths) = home_with(
            "[dog.bark.sinks]\noncall = { url = \"u\" }\n\n[[dog.bark.rules]]\non = \"gave_up\"\n",
        );
        std::fs::write(
            &paths.dogs_config,
            "[a]\nk = 1\n\n[b]\nk = 2\n\n[c]\nk = 3\n",
        )
        .expect("write");

        migrate_dog_sections(&paths).expect("migrate");

        let written = std::fs::read_to_string(&paths.dogs_config).expect("read");
        let headers: Vec<&str> = written
            .lines()
            .filter(|line| line.starts_with('['))
            .collect();
        assert_eq!(
            headers,
            vec!["[a]", "[b]", "[c]", "[bark.sinks]", "[[bark.rules]]"],
            "the migration appends; it does not interleave: {written}"
        );
    }

    /// Fails if a destination whose own sections are nested or an array of
    /// tables sends the moved section to the FRONT of the file.
    ///
    /// The counterpart to
    /// [`a_moved_dog_with_sub_tables_lands_in_one_piece_at_the_end`], which
    /// puts the shapes in the source. Here they are in `dogs.toml`, which
    /// is where the scan for "one past the last table" had to see them and
    /// did not: it read `Item::Table` positions at the top level only, so
    /// `[bark.sinks]` (nested one level under an implicit `bark`) and
    /// `[[bark.rules]]` (an array of tables) both counted as position
    /// nothing. The scan answered 0, the moved `[metrics]` took position 0,
    /// and `toml_edit` rendered it first and jammed against `[bark.sinks]`
    /// with no blank line between them. Reproduced against a real flock on
    /// exactly this fixture.
    ///
    /// TWO `[[bark.rules]]` entries, not one, and that is what makes the
    /// array arm of the scan load-bearing rather than decorative: with one
    /// entry a scan that saw only the nested table answered 1, tied with
    /// the array's own 1, and happened to render correctly anyway. With
    /// two, the same blind scan wedges `[metrics]` between them.
    ///
    /// The exact string is the assertion, blank lines and all: nothing
    /// here is lost either way, so a reparse agrees with a wrecked file
    /// and only the rendering tells them apart.
    #[test]
    fn a_moved_dog_lands_after_a_destination_of_nested_and_array_tables() {
        let (_dir, paths) = home_with(
            "[daemon]\nlog_level = \"info\"\n\n[dog.metrics]\nbind = \"127.0.0.1:19615\"\n",
        );
        let before = "[bark.sinks]\noncall = { url = \"u\" }\n\n[[bark.rules]]\non = \"gave_up\"\n\n[[bark.rules]]\non = \"restarted\"\n";
        std::fs::write(&paths.dogs_config, before).expect("write");

        migrate_dog_sections(&paths).expect("migrate");

        assert_eq!(
            std::fs::read_to_string(&paths.dogs_config).expect("read"),
            format!("{before}\n[metrics]\nbind = \"127.0.0.1:19615\"\n")
        );
    }

    /// Fails if an empty `[dog.<name>]` can stop a shepherd booting.
    ///
    /// Reproduced with a pre-branch `0.1.30` binary: its `shep enable
    /// metrics` scaffolds an empty `[dog.metrics]`, and the new binary then
    /// refused the whole migration on `WouldOverwrite` against a
    /// `dogs.toml` that already held `metrics` -- so `shep start` exited 5
    /// on a daemon that exited 4. This branch stopped the new `enable` from
    /// scaffolding, but every older binary still on a box does it and a
    /// mixed-version host is ordinary.
    ///
    /// Nothing written on either side is the assertion: the configured
    /// `dogs.toml` is the one that wins, untouched, and `shep.toml` keeps
    /// its stray header rather than being rewritten to strike it.
    #[test]
    fn an_empty_section_colliding_with_a_configured_one_is_not_a_refusal() {
        let before = "[daemon]\nenabled_dogs = [\"metrics\"]\n\n[dog.metrics]\n";
        let (_dir, paths) = home_with(before);
        let dogs = "[metrics]\nbind = \"127.0.0.1:19616\"\n";
        std::fs::write(&paths.dogs_config, dogs).expect("write");

        let moved = migrate_dog_sections(&paths).expect("an empty table is not a second value");

        assert!(moved.is_empty());
        assert_eq!(
            std::fs::read_to_string(&paths.daemon_config).expect("read"),
            before
        );
        assert_eq!(
            std::fs::read_to_string(&paths.dogs_config).expect("read"),
            dogs
        );
    }

    /// The item this subsumes: `[[dog.metrics]]` with nothing under it.
    ///
    /// `take_dog_sections` hands back no array, so the name guard used to
    /// call it `SectionsUnreadable` -- which under the reload pre-flight is
    /// a refused boot over a header holding nothing.
    #[test]
    fn an_empty_array_of_tables_under_dog_is_skipped_rather_than_refused() {
        let before = "[[dog.metrics]]\n";
        let (_dir, paths) = home_with(before);

        let moved = migrate_dog_sections(&paths).expect("nothing declared, nothing to lose");

        assert!(moved.is_empty());
        assert_eq!(
            std::fs::read_to_string(&paths.daemon_config).expect("read"),
            before
        );
    }

    /// The other half of the same ruling, and the reason the skip is over
    /// values rather than over the spelling: an array of tables that DOES
    /// carry values has no one section to become, and dropping it silently
    /// is what the name guard exists to prevent.
    #[test]
    fn an_array_of_tables_with_values_still_makes_the_migration_refuse() {
        let before = "[[dog.metrics]]\nbind = \"127.0.0.1:9615\"\n";
        let (_dir, paths) = home_with(before);

        let err = migrate_dog_sections(&paths).expect_err("values with nowhere to go");

        assert!(matches!(
            err,
            DogMigrationError::SectionsUnreadable { ref names } if names == &["metrics".to_string()]
        ));
        assert_eq!(
            std::fs::read_to_string(&paths.daemon_config).expect("read"),
            before
        );
    }

    /// An empty section beside a real one still lets the real one move, and
    /// the empty header goes with it: `take_dog_sections` strikes the whole
    /// `[dog]` table, and an empty scaffold is not something to preserve.
    #[test]
    fn an_empty_section_beside_a_real_one_does_not_block_it() {
        let (_dir, paths) =
            home_with("[dog.metrics]\n\n[dog.bark.sinks]\noncall = { url = \"u\" }\n");

        let moved = migrate_dog_sections(&paths).expect("migrate");

        assert_eq!(moved, vec!["bark".to_string()]);
        assert_eq!(
            std::fs::read_to_string(&paths.daemon_config).expect("read"),
            ""
        );
        let written = std::fs::read_to_string(&paths.dogs_config).expect("read");
        assert!(
            !written.contains("metrics"),
            "an empty scaffold is not carried across: {written}"
        );
    }

    /// Fails if a bare header in `dogs.toml` can refuse a section that
    /// carries values.
    ///
    /// The mirror of
    /// [`an_empty_section_colliding_with_a_configured_one_is_not_a_refusal`],
    /// which made this exemption on the source side and left the
    /// destination side alone. `WouldOverwrite` exists because two values
    /// for one key is a question shep cannot answer; a bare `[metrics]`
    /// holds no value, so there is no second answer and nothing to guess
    /// between. Refusing on it took a boot down over a header.
    #[test]
    fn a_bare_header_in_dogs_toml_does_not_refuse_a_configured_section() {
        let (_dir, paths) = home_with("[dog.metrics]\nbind = \"127.0.0.1:19615\"\n");
        std::fs::write(&paths.dogs_config, "[metrics]\n").expect("write");

        let moved = migrate_dog_sections(&paths).expect("an empty destination is not a value");

        assert_eq!(moved, vec!["metrics".to_string()]);
        let written = std::fs::read_to_string(&paths.dogs_config).expect("read");
        let parsed = DogsConfig::load(Some(&written)).expect("valid");
        assert_eq!(
            parsed.dog["metrics"]["bind"].as_str(),
            Some("127.0.0.1:19615"),
            "the section that had values is the one left standing: {written}"
        );
    }

    /// Fails if a header an operator spelled with spaces inside the
    /// brackets strands its section in `shep.toml` forever.
    ///
    /// `[ dog.metrics ]` is ordinary TOML and means exactly what
    /// `[dog.metrics]` means. A substring test for `"[dog."` matched
    /// neither it nor `[dog . metrics]`, so the migration returned "nothing
    /// to do", the section stayed where nothing reads it any more, and the
    /// dog came up on its compiled defaults with no warning on any surface.
    /// For bark that is every sink gone and alerting silently off.
    #[test]
    fn a_header_spelled_with_whitespace_still_migrates() {
        let (_dir, paths) = home_with(
            "[daemon]\nenabled_dogs = [\"metrics\"]\n\n[ dog.metrics ]\nbind = \"127.0.0.1:19615\"\n",
        );

        let moved = migrate_dog_sections(&paths).expect("migrate");

        assert_eq!(moved, vec!["metrics".to_string()]);
        assert_eq!(
            std::fs::read_to_string(&paths.daemon_config).expect("read"),
            "[daemon]\nenabled_dogs = [\"metrics\"]\n",
            "the section leaves shep.toml"
        );
        let written = std::fs::read_to_string(&paths.dogs_config).expect("read");
        let parsed = DogsConfig::load(Some(&written)).expect("valid");
        assert_eq!(
            parsed.dog["metrics"]["bind"].as_str(),
            Some("127.0.0.1:19615")
        );
    }

    /// Fails if a boot with nothing to migrate opens `shep.toml` for
    /// editing anyway.
    ///
    /// The inode is the assertion, not the bytes, because the bytes are
    /// identical either way. `ShepToml::edit` and `try_edit` stage a temp
    /// file and rename it over the original whenever `save` runs, so
    /// opening the document on an idle boot would hand an untouched
    /// `shep.toml` a fresh inode, force `OWNER_ONLY_FILE_MODE` onto it, and
    /// turn a symlinked path into a plain file. Every boot after the first
    /// takes this path, so the cost lands on every operator.
    #[cfg(unix)]
    #[test]
    fn a_boot_with_nothing_to_move_never_reopens_the_file() {
        use std::os::unix::fs::MetadataExt as _;

        let (_dir, paths) = home_with("[daemon]\nlog_level = \"info\"\n\n[dog]\n");
        let before = std::fs::metadata(&paths.daemon_config).expect("stat").ino();

        assert!(migrate_dog_sections(&paths).expect("migrate").is_empty());

        let after = std::fs::metadata(&paths.daemon_config).expect("stat").ino();
        assert_eq!(before, after, "an idle boot must not rewrite shep.toml");
    }

    // The one case that must never silently merge: an operator who already
    // hand-wrote dogs.toml and still has a stale section in shep.toml. Two
    // values for one key, and picking either would be shep guessing. The
    // destination holding a VALUE is what makes it two, which is the half
    // `a_bare_header_in_dogs_toml_does_not_refuse_a_configured_section`
    // does not have.
    #[test]
    fn an_existing_dogs_file_makes_the_migration_refuse() {
        let (_dir, paths) = home_with("[dog.metrics]\nbind = \"127.0.0.1:9615\"\n");
        std::fs::write(&paths.dogs_config, "[metrics]\nbind = \"0.0.0.0:9615\"\n").expect("write");

        let err = migrate_dog_sections(&paths).expect_err("both files hold metrics");

        assert!(matches!(
            err,
            DogMigrationError::WouldOverwrite { ref name } if name == "metrics"
        ));
        assert!(
            std::fs::read_to_string(&paths.daemon_config)
                .expect("read")
                .contains("[dog.metrics]"),
            "a refused migration strikes nothing"
        );
    }
}