release-kit 0.9.1

A canonical release workflow: a technology-agnostic method, per-technology bindings, and the rk CLI that lands and serves them.
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
//! Install the embedded skills into the agent skill directories.
//!
//! Two references decide what a destination holds: the skills this binary
//! carries, and the record of what a previous apply wrote there. Bytes
//! matching either are the tool's own and may be replaced; anything else is
//! the user's and refuses.
//!
//! Preview by default, list every conflict at once, and restore on failure —
//! the same conventions `rk init` follows, and for a sharper reason: an apply
//! crosses two roots, so a failure partway leaves one agent reading this
//! version of a skill and another agent reading the last one.
//!
//! The installer reports what it did as typed [`Action`]s and renders
//! nothing; the handler in `commands::skill` owns both renderings.

use std::collections::{BTreeMap, BTreeSet};
use std::fs;

use camino::{Utf8Path, Utf8PathBuf};
use serde::Serialize;

use crate::atomic;
use crate::error::RkError;
use crate::skills::record::Record;
use crate::skills::{Digest, Package};

/// One thing an install or uninstall did, or — in a preview — would do.
#[derive(Debug, Serialize, PartialEq, Eq)]
#[serde(tag = "action", rename_all = "kebab-case")]
pub enum Action {
    /// The embedded bytes land at this destination.
    Write {
        /// The package file written.
        destination: Utf8PathBuf,
    },
    /// The destination already holds the embedded bytes.
    Unchanged {
        /// The package file left alone.
        destination: Utf8PathBuf,
    },
    /// A recorded leftover the embedded skills no longer name is removed.
    Sweep {
        /// The leftover taken back.
        destination: Utf8PathBuf,
    },
    /// A leftover could not be removed; it stays for the operator.
    SweepFailed {
        /// The leftover still in place.
        destination: Utf8PathBuf,
        /// Why the removal failed.
        error: String,
    },
    /// An installed destination is removed.
    Remove {
        /// The package file removed.
        destination: Utf8PathBuf,
    },
    /// A destination holding bytes neither the embedded skills nor the record
    /// accounts for is the user's now: an uninstall leaves it, and so does
    /// the sweep of the root an earlier release shared the gates from.
    KeptEdited {
        /// The edited file left in place.
        destination: Utf8PathBuf,
    },
    /// A directory survives a removal because something else lives in it.
    KeptDirectory {
        /// The directory kept.
        directory: Utf8PathBuf,
    },
    /// The record could not be written; a later install may ask for
    /// `--force` it should not need.
    RecordUnwritten {
        /// The record path that did not write.
        record: Utf8PathBuf,
    },
}

/// One planned write: where, and which bytes.
struct Planned {
    /// The path this run writes.
    destination: Utf8PathBuf,
    /// The embedded bytes that belong there.
    bytes: &'static [u8],
}

/// Where one run writes: the agent roots and the record, plus the root an
/// earlier release shared the gates from.
///
/// Each package carries its own copy of the gates, so no install writes
/// outside the agent roots. The legacy root is scanned only so the copies an
/// earlier release wrote there are swept, and only by a run that covers
/// every agent root: an older manual under a root the run leaves alone
/// still reads the gates there.
#[derive(Debug, Clone)]
pub struct Layout {
    /// The agent skill roots this run was asked to touch.
    pub roots: Vec<Utf8PathBuf>,
    /// The root an earlier release installed the shared gates to, where
    /// this run sweeps it.
    pub legacy_shared: Option<Utf8PathBuf>,
    /// The user-scope digest record.
    pub record: Utf8PathBuf,
}

/// Every package file under `roots`, root by root, skill by skill, and
/// file by file.
fn plan_roots(roots: &[Utf8PathBuf], packages: &[Package]) -> Vec<Planned> {
    let mut planned = Vec::new();
    for root in roots {
        for package in packages {
            for file in &package.files {
                planned.push(Planned {
                    destination: root.join(&package.name).join(&file.path),
                    bytes: file.bytes,
                });
            }
        }
    }
    planned
}

/// Refuse a legacy shared root reached through a symlink this installer
/// would follow.
///
/// The chain from the state directory down to that root is this tool's own:
/// nothing here ever creates a symlink in it, so one found there redirects
/// every sweep somewhere else, and [`check_destination`] cannot see it,
/// because the final component it checks is not itself a link. The
/// directories above the state directory are the user's layout and stay
/// unjudged.
fn check_legacy_root(legacy: Option<&Utf8Path>, record: &Utf8Path) -> Result<(), RkError> {
    let (Some(legacy), Some(state_dir)) = (legacy, record.parent()) else {
        return Ok(());
    };
    let mut current = Some(legacy);
    while let Some(dir) = current {
        if !dir.starts_with(state_dir) {
            break;
        }
        if dir.is_symlink() {
            return Err(RkError::Refused(format!(
                "the shared root is reached through a symlink, and nothing was written: {dir}"
            )));
        }
        current = dir.parent();
    }
    Ok(())
}

/// Files under the legacy shared root that the record cannot vouch for.
///
/// The sweep takes back only bytes the record says this tool wrote. Anything
/// else there is the user's, so it stays, and the run names it rather than
/// leaving it unexplained.
fn legacy_kept(legacy: Option<&Utf8Path>, swept: &[Utf8PathBuf]) -> Vec<Utf8PathBuf> {
    let Some(legacy) = legacy else {
        return Vec::new();
    };
    crate::skills::shared()
        .into_iter()
        .map(|artifact| legacy.join(&artifact.path))
        .filter(|path| path.is_file() && !path.is_symlink() && !swept.contains(path))
        .collect()
}

/// Refuse a destination this installer must not write through or replace.
///
/// A symlink is never followed: the skill would land wherever it points,
/// which is outside the home this command was asked to touch.
fn check_destination(destination: &Utf8Path) -> Result<(), RkError> {
    if destination.is_symlink() {
        return Err(RkError::Refused(format!(
            "destination is a symlink, and nothing was written: {destination}"
        )));
    }
    if destination.exists() && !destination.is_file() {
        return Err(RkError::Refused(format!(
            "destination is not a regular file, and nothing was written: {destination}"
        )));
    }
    Ok(())
}

/// Destinations holding bytes neither the embedded skills nor the record account for.
///
/// A destination the record vouches for carries a copy this tool wrote and a
/// later release has since changed. That is an upgrade, not a conflict, and
/// naming it one would make every skill-touching release refuse on files
/// nobody edited.
fn conflicts(planned: &[Planned], record: &Record) -> Result<Vec<String>, RkError> {
    let mut conflicts = Vec::new();
    for entry in planned {
        if !entry.destination.is_file() {
            continue;
        }
        // An unreadable destination raises instead of passing as clean: a
        // comparison that cannot run must never license an overwrite.
        let found = fs::read(&entry.destination)?;
        if found == entry.bytes || record.wrote(&entry.destination, &Digest::of(&found)) {
            continue;
        }
        conflicts.push(entry.destination.to_string());
    }
    Ok(conflicts)
}

/// Recorded destinations under `roots` that this run no longer covers.
///
/// A skill the canon renamed or dropped leaves its file behind otherwise, and
/// a stale name is not inert: an agent keys its picker on the name, so the
/// leftover keeps showing up beside the skill that replaced it. Only bytes the
/// record still vouches for are swept — a leftover the user has since edited
/// is theirs, and a symlink is never followed.
fn leftovers(roots: &[Utf8PathBuf], record: &Record, keep: &[Utf8PathBuf]) -> Vec<Utf8PathBuf> {
    let kept: BTreeSet<&Utf8Path> = keep.iter().map(Utf8PathBuf::as_path).collect();
    record
        .written
        .iter()
        .filter(|(destination, digest)| {
            !kept.contains(destination.as_path())
                && roots.iter().any(|root| destination.starts_with(root))
                && !destination.is_symlink()
                && destination.is_file()
                && fs::read(destination).is_ok_and(|found| Digest::of(&found) == **digest)
        })
        .map(|(destination, _)| destination.clone())
        .collect()
}

/// Write `bytes` at `path` through the temp-plus-rename writer, creating
/// the directories it needs.
fn write_file(path: &Utf8Path, bytes: &[u8]) -> std::io::Result<()> {
    atomic::write(path.as_std_path(), bytes)
}

/// Remove installed files, then every directory they leave empty.
///
/// A directory is pruned up to, and never including, the root that holds
/// it: an agent root or the state directory. Returns the parent directories
/// kept because something else lives in them, so whatever a user put beside
/// a skill survives its removal. A removal that fails stops the run at that
/// file.
fn remove_installed(
    destinations: &[Utf8PathBuf],
    stops: &[Utf8PathBuf],
) -> Result<Vec<Utf8PathBuf>, (Utf8PathBuf, std::io::Error)> {
    let mut parents: BTreeSet<Utf8PathBuf> = BTreeSet::new();
    for destination in destinations {
        fs::remove_file(destination).map_err(|source| (destination.clone(), source))?;
        if let Some(parent) = destination.parent() {
            parents.insert(parent.to_owned());
        }
    }
    // Deepest first, so a package's `references/` empties before the skill
    // directory holding it is judged.
    let mut candidates: Vec<Utf8PathBuf> = Vec::new();
    for parent in &parents {
        let mut current = Some(parent.as_path());
        while let Some(dir) = current {
            if stops.iter().any(|stop| stop == dir)
                || !stops.iter().any(|stop| dir.starts_with(stop))
            {
                break;
            }
            if !candidates.iter().any(|seen| seen == dir) {
                candidates.push(dir.to_owned());
            }
            current = dir.parent();
        }
    }
    candidates.sort_by_key(|dir| std::cmp::Reverse(dir.components().count()));
    for dir in &candidates {
        if fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) {
            let _ = fs::remove_dir(dir);
        }
    }
    Ok(parents.into_iter().filter(|dir| dir.is_dir()).collect())
}

/// Restore every backed-up destination, returning those that would not go back.
///
/// A destination already holding what it held counts as restored, whatever a
/// write to it would do. Nothing else distinguishes the two ways an apply
/// reaches here — the write loop stopped before this destination, or a
/// read-only root refused every write including this one — and reporting the
/// second as unrestored sends the operator to verify files no write reached.
fn rollback(backups: &BTreeMap<Utf8PathBuf, Option<Vec<u8>>>) -> Vec<Utf8PathBuf> {
    let mut unrestored = Vec::new();
    for (destination, previous) in backups {
        let restored = previous.as_ref().map_or_else(
            || !destination.exists() || fs::remove_file(destination).is_ok(),
            |bytes| {
                fs::read(destination).is_ok_and(|found| &found == bytes)
                    || write_file(destination, bytes).is_ok()
            },
        );
        if !restored {
            unrestored.push(destination.clone());
        }
    }
    unrestored
}

/// The refusal a failed apply carries, naming the cause and what it restored.
fn abort(unrestored: &[Utf8PathBuf], cause: &str) -> RkError {
    if unrestored.is_empty() {
        return RkError::Refused(format!(
            "the install was aborted and the destinations were restored: {cause}"
        ));
    }
    let paths: Vec<&str> = unrestored.iter().map(|p| p.as_str()).collect();
    RkError::Refused(format!(
        "the install was aborted and restoration is incomplete; verify these by hand: {}: {cause}",
        paths.join(", ")
    ))
}

/// Install every embedded skill package under each root, previewing by
/// default.
///
/// `record_path` names the user-scope digest record: read to tell a stale copy
/// this tool wrote from a file the user edited, and rewritten after a
/// successful apply. Failing to write it is not a failure of the install — the
/// files landed — so it costs only the benefit of the doubt next time.
///
/// The first apply after the shared gates moved into each package takes back
/// the copies an earlier release wrote to the legacy shared root, where the
/// record vouches for them, and names any it cannot vouch for.
///
/// # Errors
///
/// Returns [`RkError::Refused`] when the legacy shared root is reached
/// through a symlink, when a destination cannot be touched, when one holds
/// bytes neither reference accounts for and `force` is unset, or when a write
/// fails partway, in which case the destinations are restored first.
/// Returns [`RkError::Io`] when a destination exists but cannot be read.
pub fn install(layout: &Layout, apply: bool, force: bool) -> Result<Vec<Action>, RkError> {
    check_legacy_root(layout.legacy_shared.as_deref(), &layout.record)?;
    let record_path = layout.record.as_path();
    let packages = crate::skills::packages()?;
    let planned = plan_roots(&layout.roots, &packages);
    for entry in &planned {
        check_destination(&entry.destination)?;
    }

    let mut record = Record::load(record_path);
    let covered: Vec<Utf8PathBuf> = planned
        .iter()
        .map(|entry| entry.destination.clone())
        .collect();
    let mut scanned = layout.roots.clone();
    scanned.extend(layout.legacy_shared.clone());
    let stale = leftovers(&scanned, &record, &covered);
    let kept = legacy_kept(layout.legacy_shared.as_deref(), &stale);

    if !apply {
        let mut actions: Vec<Action> = covered
            .into_iter()
            .map(|destination| Action::Write { destination })
            .collect();
        actions.extend(
            stale
                .into_iter()
                .map(|destination| Action::Sweep { destination }),
        );
        actions.extend(
            kept.into_iter()
                .map(|destination| Action::KeptEdited { destination }),
        );
        return Ok(actions);
    }

    if !force {
        let conflicts = conflicts(&planned, &record)?;
        if !conflicts.is_empty() {
            return Err(RkError::Refused(format!(
                "these destinations hold bytes this tool did not write, and nothing was written: {}; re-run with --force to overwrite",
                conflicts.join(", ")
            )));
        }
    }

    // Back up every destination before the first write, so a failure on the
    // second root cannot leave the first one upgraded.
    let backups = back_up(&planned)?;

    let mut actions = Vec::new();
    for entry in &planned {
        let held = backups.get(&entry.destination).and_then(Option::as_ref);
        if held.is_some_and(|previous| previous == entry.bytes) {
            actions.push(Action::Unchanged {
                destination: entry.destination.clone(),
            });
            continue;
        }
        if let Err(source) = write_file(&entry.destination, entry.bytes) {
            return Err(abort(
                &rollback(&backups),
                &format!("writing {} failed: {source}", entry.destination),
            ));
        }
        actions.push(Action::Write {
            destination: entry.destination.clone(),
        });
    }

    // Sweep after the writes, never before: a refusal must leave the home
    // exactly as it found it, and a leftover is harmless until the install
    // superseding it has actually landed.
    let stops = sweep_stops(layout);
    for destination in &stale {
        match remove_installed(std::slice::from_ref(destination), &stops) {
            Ok(kept_dirs) => {
                actions.push(Action::Sweep {
                    destination: destination.clone(),
                });
                actions.extend(
                    kept_dirs
                        .into_iter()
                        .map(|directory| Action::KeptDirectory { directory }),
                );
                record.written.remove(destination);
            }
            Err((_, source)) => actions.push(Action::SweepFailed {
                destination: destination.clone(),
                error: source.to_string(),
            }),
        }
    }
    actions.extend(
        kept.into_iter()
            .map(|destination| Action::KeptEdited { destination }),
    );

    for entry in &planned {
        record
            .written
            .insert(entry.destination.clone(), Digest::of(entry.bytes));
    }
    if write_file(record_path, record.to_text().as_bytes()).is_err() {
        actions.push(Action::RecordUnwritten {
            record: record_path.to_owned(),
        });
    }
    Ok(actions)
}

/// The bytes each planned destination holds before an apply, or `None` for
/// one that does not exist yet.
fn back_up(planned: &[Planned]) -> Result<BTreeMap<Utf8PathBuf, Option<Vec<u8>>>, RkError> {
    let mut backups = BTreeMap::new();
    for entry in planned {
        let previous = if entry.destination.is_file() {
            Some(fs::read(&entry.destination).map_err(|source| {
                RkError::Refused(format!(
                    "cannot back up {}, and nothing was written: {source}",
                    entry.destination
                ))
            })?)
        } else {
            None
        };
        backups.insert(entry.destination.clone(), previous);
    }
    Ok(backups)
}

/// The directories a removal never prunes: every agent root this run
/// touches, and the state directory above the legacy shared root.
fn sweep_stops(layout: &Layout) -> Vec<Utf8PathBuf> {
    let mut stops = layout.roots.clone();
    if let Some(state_dir) = layout.record.parent() {
        stops.push(state_dir.to_owned());
    }
    stops
}

/// Remove every installed skill package under each root, previewing by
/// default.
///
/// Only bytes this tool can vouch for go: a destination holding the embedded
/// bytes or bytes the record says it wrote, plus the recorded leftovers, and a
/// directory only once nothing else lives in it. A destination the user has
/// edited is theirs now and stays, reported rather than removed. An absent
/// destination is a no-op, so a re-run succeeds. Removed destinations leave
/// the record too; what is gone cannot be vouched for.
///
/// Each package carries its own gates, so an uninstall of one agent family
/// takes that family's copies and leaves the other's.
///
/// # Errors
///
/// Returns [`RkError::Refused`] when the legacy shared root is reached
/// through a symlink, or when a destination is a symlink or not a regular
/// file, and [`RkError::Io`] when a removal fails.
pub fn uninstall(layout: &Layout, apply: bool) -> Result<Vec<Action>, RkError> {
    check_legacy_root(layout.legacy_shared.as_deref(), &layout.record)?;
    let record_path = layout.record.as_path();
    let packages = crate::skills::packages()?;
    let record_found = Record::load(record_path);
    let mut removable: Vec<Utf8PathBuf> = Vec::new();
    let mut edited: Vec<Utf8PathBuf> = Vec::new();
    for entry in &plan_roots(&layout.roots, &packages) {
        check_destination(&entry.destination)?;
        if !entry.destination.is_file() {
            continue;
        }
        // The same two references an install trusts decide what goes: the
        // bytes, or bytes the record vouches this tool wrote.
        // Anything else is the user's edit, and removing it would destroy
        // work an install refuses to even overwrite.
        let found = fs::read(&entry.destination)?;
        if found == entry.bytes || record_found.wrote(&entry.destination, &Digest::of(&found)) {
            removable.push(entry.destination.clone());
        } else {
            edited.push(entry.destination.clone());
        }
    }

    let mut record = record_found;
    let mut scanned = layout.roots.clone();
    scanned.extend(layout.legacy_shared.clone());
    // A skill this binary has since dropped is still ours to take back, and an
    // uninstall leaving it behind is the leftover an agent keeps offering. The
    // record is what names it; the embedded skills no longer can.
    let stale = leftovers(&scanned, &record, &removable);
    edited.extend(legacy_kept(layout.legacy_shared.as_deref(), &stale));

    if !apply {
        let mut actions: Vec<Action> = removable
            .into_iter()
            .map(|destination| Action::Remove { destination })
            .collect();
        actions.extend(
            stale
                .into_iter()
                .map(|destination| Action::Sweep { destination }),
        );
        actions.extend(
            edited
                .into_iter()
                .map(|destination| Action::KeptEdited { destination }),
        );
        return Ok(actions);
    }

    removable.extend(stale);
    let kept_dirs = remove_installed(&removable, &sweep_stops(layout))
        .map_err(|(_, source)| RkError::Io(source))?;
    let mut actions: Vec<Action> = Vec::new();
    for destination in &removable {
        actions.push(Action::Remove {
            destination: destination.clone(),
        });
        record.written.remove(destination);
    }
    actions.extend(
        kept_dirs
            .into_iter()
            .map(|directory| Action::KeptDirectory { directory }),
    );
    actions.extend(
        edited
            .into_iter()
            .map(|destination| Action::KeptEdited { destination }),
    );

    let recorded = if record.written.is_empty() {
        fs::remove_file(record_path).or_else(|source| {
            if source.kind() == std::io::ErrorKind::NotFound {
                Ok(())
            } else {
                Err(source)
            }
        })
    } else {
        write_file(record_path, record.to_text().as_bytes())
    };
    if recorded.is_err() {
        actions.push(Action::RecordUnwritten {
            record: record_path.to_owned(),
        });
    }
    Ok(actions)
}

#[cfg(test)]
mod tests {
    use camino::Utf8PathBuf;

    use super::{Action, Layout, install, leftovers, uninstall};
    use crate::skills::record::{RECORD_PATH, Record};
    use crate::skills::{Digest, all, packages};

    /// A scratch home, plus the roots and record path it implies.
    struct Home {
        dir: tempfile::TempDir,
    }

    impl Home {
        fn new() -> Self {
            Self {
                dir: tempfile::tempdir().expect("a scratch home exists"),
            }
        }

        fn path(&self) -> Utf8PathBuf {
            Utf8PathBuf::from_path_buf(self.dir.path().to_path_buf())
                .expect("the temp path is UTF-8")
        }

        fn roots(&self) -> Vec<Utf8PathBuf> {
            let home = self.path();
            vec![home.join(".claude/skills"), home.join(".agents/skills")]
        }

        fn record(&self) -> Utf8PathBuf {
            self.path().join(RECORD_PATH)
        }

        fn destination(&self, root: &str, skill: &str) -> Utf8PathBuf {
            self.path().join(root).join(skill).join("SKILL.md")
        }

        fn legacy_shared(&self) -> Utf8PathBuf {
            self.path().join(".local/state/release-kit/skills/shared")
        }

        /// A gate copy inside one installed package.
        fn gate(&self, root: &str, skill: &str) -> Utf8PathBuf {
            self.path()
                .join(root)
                .join(skill)
                .join("references/plan-gate.md")
        }

        /// The layout for every agent root.
        fn layout(&self) -> Layout {
            self.layout_for(self.roots())
        }

        /// The layout for a subset of the agent roots, which sweeps the
        /// legacy root only when the subset is every root.
        fn layout_for(&self, roots: Vec<Utf8PathBuf>) -> Layout {
            let every = roots == self.roots();
            Layout {
                roots,
                legacy_shared: every.then(|| self.legacy_shared()),
                record: self.record(),
            }
        }
    }

    /// How many files every package carries together, per agent root.
    fn package_files() -> usize {
        packages()
            .expect("the packages compose")
            .iter()
            .map(|package| package.files.len())
            .sum()
    }

    fn first_skill() -> String {
        all().expect("the skills read").swap_remove(0).name
    }

    #[test]
    fn a_preview_lists_every_destination_and_writes_nothing() {
        let home = Home::new();
        let actions = install(&home.layout(), false, false).unwrap();
        assert_eq!(actions.len(), package_files() * 2, "{actions:?}");
        assert!(
            actions
                .iter()
                .all(|action| matches!(action, Action::Write { .. })),
            "{actions:?}"
        );
        assert!(!home.path().join(".claude").exists());
        assert!(!home.record().exists());
    }

    #[test]
    fn an_apply_is_idempotent_and_records_what_it_wrote() {
        let home = Home::new();
        let first = install(&home.layout(), true, false).unwrap();
        assert!(
            first
                .iter()
                .all(|action| matches!(action, Action::Write { .. })),
            "{first:?}"
        );
        let second = install(&home.layout(), true, false).unwrap();
        assert!(
            second
                .iter()
                .all(|action| matches!(action, Action::Unchanged { .. })),
            "{second:?}"
        );
        let record = Record::load(&home.record());
        assert_eq!(record.written.len(), package_files() * 2);
    }

    /// The defect the record exists for: bytes a previous release wrote are
    /// not the user's, and refusing on them makes every skill-touching release
    /// break the install recipe.
    #[test]
    fn a_copy_a_previous_release_wrote_is_replaced_without_force() {
        let home = Home::new();
        install(&home.layout(), true, false).unwrap();

        // Stand in for an older release: rewrite each destination and record
        // its digest, exactly as that release's apply would have left it.
        let mut stale = Record::default();
        for destination in Record::load(&home.record()).written.into_keys() {
            std::fs::write(&destination, "older canon bytes\n").unwrap();
            stale
                .written
                .insert(destination, Digest::of(b"older canon bytes\n"));
        }
        std::fs::write(home.record(), stale.to_text()).unwrap();

        install(&home.layout(), true, false).unwrap();
        let text =
            std::fs::read_to_string(home.destination(".claude/skills", &first_skill())).unwrap();
        assert!(text.contains(&format!("name: {}", first_skill())));
    }

    /// A record vouching for one destination says nothing about another.
    #[test]
    fn an_edit_refuses_and_names_every_conflict() {
        let home = Home::new();
        install(&home.layout(), true, false).unwrap();
        let edited: Vec<Utf8PathBuf> = all()
            .unwrap()
            .iter()
            .map(|skill| home.destination(".claude/skills", &skill.name))
            .collect();
        for destination in &edited {
            std::fs::write(destination, "the user wrote this").unwrap();
        }

        let message = install(&home.layout(), true, false)
            .unwrap_err()
            .to_string();
        for destination in &edited {
            assert!(message.contains(destination.as_str()), "{message}");
        }
        for destination in &edited {
            assert_eq!(
                std::fs::read_to_string(destination).unwrap(),
                "the user wrote this",
                "a refused install must not overwrite"
            );
        }
        install(&home.layout(), true, true).unwrap();
        assert!(
            std::fs::read_to_string(&edited[0])
                .unwrap()
                .starts_with("---")
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_symlinked_destination_refuses_before_anything_is_written() {
        let home = Home::new();
        let skill = first_skill();
        let destination = home.destination(".claude/skills", &skill);
        std::fs::create_dir_all(destination.parent().unwrap()).unwrap();
        let elsewhere = home.path().join("elsewhere");
        std::fs::write(&elsewhere, "the user's file\n").unwrap();
        std::os::unix::fs::symlink(&elsewhere, &destination).unwrap();

        let message = install(&home.layout(), true, true).unwrap_err().to_string();
        assert!(message.contains("symlink"), "{message}");
        assert_eq!(
            std::fs::read_to_string(&elsewhere).unwrap(),
            "the user's file\n"
        );
        assert!(!home.path().join(".agents").exists());
    }

    /// A failure on the second root must not leave the first one upgraded.
    #[test]
    fn a_failed_write_restores_every_destination() {
        let home = Home::new();
        install(&home.layout(), true, false).unwrap();
        let first = home.destination(".claude/skills", &first_skill());
        std::fs::write(&first, "older canon bytes\n").unwrap();
        let mut record = Record::load(&home.record());
        record
            .written
            .insert(first.clone(), Digest::of(b"older canon bytes\n"));
        std::fs::write(home.record(), record.to_text()).unwrap();

        // A regular file where the second root's skill directory belongs: the
        // directory cannot be created, so that root's write fails.
        let blocked = home.path().join(".agents/skills").join(first_skill());
        std::fs::remove_dir_all(&blocked).unwrap();
        std::fs::write(&blocked, "in the way\n").unwrap();

        let message = install(&home.layout(), true, false)
            .unwrap_err()
            .to_string();
        assert!(message.contains("aborted"), "{message}");
        assert_eq!(
            std::fs::read_to_string(&first).unwrap(),
            "older canon bytes\n",
            "the first root must be restored"
        );
    }

    #[test]
    fn an_install_sweeps_a_destination_the_binary_dropped() {
        let home = Home::new();
        install(&home.layout(), true, false).unwrap();
        let dropped = home.destination(".claude/skills", "rk-retired");
        std::fs::create_dir_all(dropped.parent().unwrap()).unwrap();
        std::fs::write(&dropped, "a skill a later release dropped\n").unwrap();
        let mut record = Record::load(&home.record());
        record.written.insert(
            dropped.clone(),
            Digest::of(b"a skill a later release dropped\n"),
        );
        std::fs::write(home.record(), record.to_text()).unwrap();

        let actions = install(&home.layout(), true, false).unwrap();
        assert!(
            actions.contains(&Action::Sweep {
                destination: dropped.clone()
            }),
            "{actions:?}"
        );
        assert!(!dropped.exists());
        assert!(!dropped.parent().unwrap().exists());
        assert!(!Record::load(&home.record()).written.contains_key(&dropped));
    }

    /// A leftover the user has since edited is theirs, not ours to remove.
    #[test]
    fn a_sweep_leaves_an_edited_leftover_alone() {
        let home = Home::new();
        install(&home.layout(), true, false).unwrap();
        let dropped = home.destination(".claude/skills", "rk-retired");
        std::fs::create_dir_all(dropped.parent().unwrap()).unwrap();
        std::fs::write(&dropped, "the user rewrote this\n").unwrap();
        let mut record = Record::load(&home.record());
        record
            .written
            .insert(dropped.clone(), Digest::of(b"what we wrote\n"));
        std::fs::write(home.record(), record.to_text()).unwrap();

        assert!(
            !leftovers(&home.roots(), &record, &[]).contains(&dropped),
            "a leftover whose bytes differ from the record is the user's"
        );
        install(&home.layout(), true, false).unwrap();
        assert_eq!(
            std::fs::read_to_string(&dropped).unwrap(),
            "the user rewrote this\n"
        );
    }

    /// A destination the user edited after installing is theirs: an
    /// uninstall reports it and leaves it, exactly as an install refuses
    /// to overwrite it.
    #[test]
    fn an_uninstall_keeps_an_edited_destination() {
        let home = Home::new();
        install(&home.layout(), true, false).unwrap();
        let edited = home.destination(".claude/skills", &first_skill());
        std::fs::write(&edited, "the user rewrote this\n").unwrap();

        let preview = uninstall(&home.layout(), false).unwrap();
        assert!(
            preview.contains(&Action::KeptEdited {
                destination: edited.clone()
            }),
            "{preview:?}"
        );
        assert!(
            !preview.contains(&Action::Remove {
                destination: edited.clone()
            }),
            "{preview:?}"
        );

        let actions = uninstall(&home.layout(), true).unwrap();
        assert!(
            actions.contains(&Action::KeptEdited {
                destination: edited.clone()
            }),
            "{actions:?}"
        );
        assert_eq!(
            std::fs::read_to_string(&edited).unwrap(),
            "the user rewrote this\n",
            "an uninstall must never delete a user's edit"
        );
        // Everything the tool can vouch for is still removed.
        assert!(!home.destination(".agents/skills", &first_skill()).exists());
    }

    #[test]
    fn an_uninstall_removes_what_it_wrote_and_keeps_the_rest() {
        let home = Home::new();
        install(&home.layout(), true, false).unwrap();
        let skill = first_skill();
        let beside = home
            .destination(".claude/skills", &skill)
            .parent()
            .unwrap()
            .join("notes.md");
        std::fs::write(&beside, "the user's notes\n").unwrap();

        let actions = uninstall(&home.layout(), true).unwrap();
        assert!(
            actions
                .iter()
                .any(|action| matches!(action, Action::KeptDirectory { .. })),
            "{actions:?}"
        );
        assert!(!home.destination(".claude/skills", &skill).exists());
        assert!(beside.is_file(), "a file beside a skill must survive");
        assert!(!home.record().exists(), "an empty record is removed");
        // A re-run over an emptied home is a no-op, not a failure.
        uninstall(&home.layout(), true).unwrap();
    }

    #[test]
    fn one_root_installs_and_uninstalls_without_touching_the_other() {
        let home = Home::new();
        let claude = home.layout_for(vec![home.path().join(".claude/skills")]);
        install(&claude, true, false).unwrap();
        assert!(home.destination(".claude/skills", &first_skill()).is_file());
        assert!(!home.path().join(".agents").exists());

        uninstall(&claude, true).unwrap();
        assert!(!home.destination(".claude/skills", &first_skill()).exists());
    }

    /// Each package carries its own gates, so an install for either agent
    /// family lands them inside that family's packages and nowhere else.
    #[test]
    fn either_agent_alone_lands_the_gates_in_its_packages() {
        for (root, other) in [
            (".claude/skills", ".agents/skills"),
            (".agents/skills", ".claude/skills"),
        ] {
            let home = Home::new();
            let one = home.layout_for(vec![home.path().join(root)]);
            install(&one, true, false).unwrap();
            for skill in all().unwrap() {
                assert!(
                    home.gate(root, &skill.name).is_file(),
                    "{root}/{}: the gate did not land",
                    skill.name
                );
                assert!(!home.gate(other, &skill.name).exists());
            }
            assert!(!home.legacy_shared().exists());
        }
    }

    /// The defect a shared root had: one family's uninstall had to keep the
    /// gates for the other. A package owns its copies, so each family's
    /// uninstall takes its own and leaves the other's.
    #[test]
    fn an_uninstall_of_one_family_leaves_the_other_family_its_gates() {
        let home = Home::new();
        install(&home.layout(), true, false).unwrap();
        let codex = home.layout_for(vec![home.path().join(".agents/skills")]);
        uninstall(&codex, true).unwrap();
        assert!(
            !home
                .path()
                .join(".agents/skills")
                .join(first_skill())
                .exists()
        );
        assert!(home.gate(".claude/skills", &first_skill()).is_file());
    }

    /// The first install after the gates moved into the packages takes back
    /// the copies an earlier release wrote to the shared root, and the
    /// directories they leave empty.
    #[test]
    fn an_install_sweeps_the_legacy_shared_root_it_vouches_for() {
        let home = Home::new();
        let legacy = home.legacy_shared().join("plan-gate.md");
        std::fs::create_dir_all(home.legacy_shared()).unwrap();
        std::fs::write(&legacy, "an earlier release's gate\n").unwrap();
        let mut record = Record::default();
        record
            .written
            .insert(legacy.clone(), Digest::of(b"an earlier release's gate\n"));
        std::fs::create_dir_all(home.record().parent().unwrap()).unwrap();
        std::fs::write(home.record(), record.to_text()).unwrap();

        let preview = install(&home.layout(), false, false).unwrap();
        assert!(
            preview.contains(&Action::Sweep {
                destination: legacy.clone()
            }),
            "{preview:?}"
        );
        install(&home.layout(), true, false).unwrap();
        assert!(!legacy.exists());
        assert!(!home.legacy_shared().exists());
        assert!(
            !home.legacy_shared().parent().unwrap().exists(),
            "the emptied skills directory goes too"
        );
        assert!(!Record::load(&home.record()).written.contains_key(&legacy));
    }

    /// A run limited to one agent family leaves the legacy root alone,
    /// because an older manual under the other family's root still reads
    /// the gates there; the uninstall of that family leaves it too.
    #[test]
    fn a_one_family_install_keeps_the_legacy_gates() {
        let home = Home::new();
        let legacy = home.legacy_shared().join("plan-gate.md");
        std::fs::create_dir_all(home.legacy_shared()).unwrap();
        std::fs::write(&legacy, "an earlier release's gate\n").unwrap();
        let mut record = Record::default();
        record
            .written
            .insert(legacy.clone(), Digest::of(b"an earlier release's gate\n"));
        std::fs::create_dir_all(home.record().parent().unwrap()).unwrap();
        std::fs::write(home.record(), record.to_text()).unwrap();
        let codex = home.layout_for(vec![home.path().join(".agents/skills")]);

        let preview = install(&codex, false, false).unwrap();
        assert!(
            !preview.iter().any(|action| matches!(
                action,
                Action::Sweep { destination } if destination == &legacy
            )),
            "{preview:?}"
        );
        install(&codex, true, false).unwrap();
        assert!(legacy.is_file());
        uninstall(&codex, true).unwrap();
        assert!(legacy.is_file());
        assert!(Record::load(&home.record()).written.contains_key(&legacy));
    }

    /// Bytes under the legacy root the record cannot vouch for are the
    /// user's: the sweep leaves them and names them.
    #[test]
    fn an_install_leaves_and_names_an_unvouched_legacy_gate() {
        let home = Home::new();
        let legacy = home.legacy_shared().join("plan-gate.md");
        std::fs::create_dir_all(home.legacy_shared()).unwrap();
        std::fs::write(&legacy, "the user's own gate\n").unwrap();

        let actions = install(&home.layout(), true, false).unwrap();
        assert!(
            actions.contains(&Action::KeptEdited {
                destination: legacy.clone()
            }),
            "{actions:?}"
        );
        assert_eq!(
            std::fs::read_to_string(&legacy).unwrap(),
            "the user's own gate\n"
        );
    }

    /// A gate copy the user edited is theirs, exactly as a skill is.
    #[test]
    fn an_edited_gate_copy_refuses_an_install_and_survives_an_uninstall() {
        let home = Home::new();
        install(&home.layout(), true, false).unwrap();
        let gate = home.gate(".claude/skills", &first_skill());
        std::fs::write(&gate, b"mine now").unwrap();

        let message = install(&home.layout(), true, false)
            .expect_err("an edited gate refuses")
            .to_string();
        assert!(message.contains("plan-gate.md"), "{message}");

        let actions = uninstall(&home.layout(), true).unwrap();
        assert!(
            actions.iter().any(|action| matches!(
                action,
                Action::KeptEdited { destination } if destination == &gate
            )),
            "{actions:?}"
        );
        assert_eq!(std::fs::read(&gate).unwrap(), b"mine now");
    }

    /// A symlinked gate copy refuses before anything is written, the same as
    /// a symlinked skill.
    #[test]
    fn a_symlinked_gate_copy_refuses_before_writing() {
        let home = Home::new();
        let gate = home.gate(".agents/skills", &first_skill());
        std::fs::create_dir_all(gate.parent().unwrap()).unwrap();
        std::os::unix::fs::symlink("/etc/passwd", &gate).unwrap();

        let message = install(&home.layout(), true, false)
            .expect_err("a symlink refuses")
            .to_string();
        assert!(message.contains("symlink"), "{message}");
        assert!(
            !home.destination(".claude/skills", &first_skill()).exists(),
            "the refusal must come before the first write"
        );
    }

    /// A legacy shared root reached through a symlinked directory refuses
    /// both verbs: the sweep would delete wherever the link points, and no
    /// per-destination check can see it.
    #[test]
    fn a_symlinked_shared_root_refuses_install_and_uninstall() {
        for symlinked in ["skills", "skills/shared"] {
            let home = Home::new();
            let elsewhere = home.path().join("elsewhere");
            std::fs::create_dir_all(&elsewhere).unwrap();
            let state_dir = home.record().parent().unwrap().to_path_buf();
            let linked = state_dir.join(symlinked);
            std::fs::create_dir_all(linked.parent().unwrap()).unwrap();
            std::os::unix::fs::symlink(&elsewhere, &linked).unwrap();

            let message = install(&home.layout(), true, false)
                .expect_err("a symlinked shared root refuses an install")
                .to_string();
            assert!(message.contains("symlink"), "{message}");
            assert!(
                !elsewhere.join("plan-gate.md").exists(),
                "an install must never write through a symlinked shared root"
            );
            assert!(!home.path().join(".claude").exists());

            std::fs::write(elsewhere.join("plan-gate.md"), "theirs\n").unwrap();
            let message = uninstall(&home.layout(), true)
                .expect_err("a symlinked shared root refuses an uninstall")
                .to_string();
            assert!(message.contains("symlink"), "{message}");
            assert!(
                elsewhere.join("plan-gate.md").exists(),
                "an uninstall must never remove through a symlinked shared root"
            );
        }
    }
}