skill-evidence 0.9.0

The skill-evidence lifecycle: use records, gate projections, evolution reviews, and the four skill packages that drive 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
//! The skill packages and schemas this crate ships, and the command that writes
//! them into a repository.
//!
//! The lifecycle machinery is useless without the four skill packages that
//! drive it, and those packages were duplicated by hand across repositories for
//! as long as the machinery was. They travel here instead: compiled into the
//! binary, rendered with the host's own names, and written out on request.
//!
//! Two tokens vary per repository — the binary an operator types and the Cargo
//! package that provides it — so the shipped copies carry `{{command}}`,
//! `{{cargo_package}}`, and `{{namespace}}` where those appear. Nothing else in
//! a package is host-specific; a package that needed a third token would be a
//! sign the package, not the template, has the wrong boundary.

use std::{
    collections::HashSet,
    fs,
    path::{Path, PathBuf},
};

use serde::Serialize;

use crate::{Error, Host, refusal, unsafe_failure};

/// One shipped file: where it goes, relative to a repository root, and what it
/// says before the host's names are substituted in.
struct Asset {
    relative_path: &'static str,
    template: &'static str,
}

struct RenderedAsset {
    destination: PathBuf,
    contents: String,
    relative_path: &'static str,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum InstalledAssetState {
    Missing,
    Matching,
    Differing,
}

struct InstalledAssetComparison {
    relative_path: &'static str,
    state: InstalledAssetState,
}

/// Whether the installed Skill Evolution package matches the files this crate ships.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct InstalledSkillEvolutionPackageComparison {
    pub(crate) matches_shipped: bool,
    pub(crate) differing_files: Vec<String>,
}

/// Pairs an installed skill file with the shipped copy that fills it.
///
/// The two live at different paths — `assets/skills/…` here, `.claude/skills/…`
/// in a host — and writing both by hand is how one of them drifts. Each macro
/// derives the source from the destination, so the list below names each file
/// once.
macro_rules! skill_asset {
    ($path:literal) => {
        Asset {
            relative_path: concat!(".claude/skills/", $path),
            template: include_str!(concat!("../assets/skills/", $path)),
        }
    };
}

/// The same, for the versioned contracts under `schemas/skill-evidence/`.
macro_rules! schema_asset {
    ($path:literal) => {
        Asset {
            relative_path: concat!("schemas/skill-evidence/", $path),
            template: include_str!(concat!("../assets/schemas/", $path)),
        }
    };
}

/// Everything this crate installs.
///
/// Listed rather than walked: a build that silently shipped one file fewer
/// because a directory listing changed would be indistinguishable from a
/// working one until an operator hit the gap.
const ASSETS: &[Asset] = &[
    skill_asset!("skill-evidence-capture/SKILL.md"),
    skill_asset!("skill-evidence-capture/agents/openai.yaml"),
    skill_asset!("skill-evolution/SKILL.md"),
    skill_asset!("skill-evolution/agents/openai.yaml"),
    skill_asset!("skill-evolution/references/authorized-review.md"),
    skill_asset!("skill-evolution-status/SKILL.md"),
    skill_asset!("skill-evolution-status/agents/openai.yaml"),
    skill_asset!("method-gap-research-status/SKILL.md"),
    skill_asset!("method-gap-research-status/agents/openai.yaml"),
    skill_asset!("method-gap-research-status/references/lineage-reconstruction.md"),
    skill_asset!("method-gap-research-status/references/selection-rules.md"),
    schema_asset!("event.v1.schema.json"),
    schema_asset!("gate-status.v1.schema.json"),
];

/// Files from packages this crate once installed and can now withdraw.
///
/// Retired assets are deliberately separate from [`ASSETS`]: retaining their
/// last-shipped templates must never make them reachable from `install`.
const RETIRED_ASSETS: &[Asset] = &[
    Asset {
        relative_path: ".claude/skills/legacy-skill-decontamination/SKILL.md",
        template: include_str!("../assets/retired-skills/legacy-skill-decontamination/SKILL.md"),
    },
    Asset {
        relative_path: ".claude/skills/legacy-skill-decontamination/agents/openai.yaml",
        template: include_str!(
            "../assets/retired-skills/legacy-skill-decontamination/agents/openai.yaml"
        ),
    },
    Asset {
        relative_path: ".claude/skills/legacy-skill-decontamination/references/eligible-run.md",
        template: include_str!(
            "../assets/retired-skills/legacy-skill-decontamination/references/eligible-run.md"
        ),
    },
];

/// The skill packages [`ASSETS`] installs, in the order they first appear.
///
/// Derived from the asset list rather than restated, so a package added there
/// gets its discovery link without a second edit here.
fn skill_package_names() -> Vec<&'static str> {
    package_names(ASSETS)
}

/// The retired package names, derived from their retained files rather than
/// maintained as a second registry.
fn retired_skill_package_names() -> Vec<&'static str> {
    package_names(RETIRED_ASSETS)
}

fn package_names(assets: &[Asset]) -> Vec<&'static str> {
    let mut names = Vec::new();
    for asset in assets {
        let Some(rest) = asset.relative_path.strip_prefix(".claude/skills/") else {
            continue;
        };
        let name = rest.split('/').next().expect("a split always yields one");
        if !names.contains(&name) {
            names.push(name);
        }
    }
    names
}

/// What one `install` did.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstallReceipt {
    pub schema_version: u8,
    /// Files this run created.
    pub written: Vec<String>,
    /// Files already byte-identical to what this crate ships.
    pub unchanged: Vec<String>,
    /// Files that exist and differ. Empty unless `force` was set, because a
    /// run that found any of these without `force` refuses instead.
    pub replaced: Vec<String>,
    /// Discovery links under `.agents/skills/` this run created. Empty on a
    /// platform without symlinks, where discovery falls back to
    /// `.claude/skills/` directly.
    pub linked: Vec<String>,
    /// Retired packages still present in the repository. `install` reports
    /// them but never removes them.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub orphaned_packages: Vec<String>,
}

/// One path `withdraw` deliberately retained and why it was outside the
/// operation's authority.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RetainedPath {
    pub path: String,
    pub reason: String,
}

/// What one [`withdraw`] did.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct WithdrawalReceipt {
    pub schema_version: u8,
    /// Retired files removed because they still matched the last shipped copy.
    pub removed_files: Vec<String>,
    /// Removed files that differed and therefore required `force`.
    pub forced_files: Vec<String>,
    /// Empty directories removed below a retired package, including the
    /// package directory itself.
    pub removed_directories: Vec<String>,
    /// Correct discovery links removed from `.agents/skills/`.
    pub removed_links: Vec<String>,
    /// Paths left in place because the crate cannot prove it wrote them.
    pub retained: Vec<RetainedPath>,
}

/// Writes the shipped packages and schemas into `root`.
///
/// Refuses rather than overwrites when a file exists and differs, so a
/// repository that has edited its own copy finds out instead of losing it.
/// `force` converts those into replacements.
pub fn install(root: &Path, host: &Host, force: bool) -> Result<InstallReceipt, Error> {
    let rendered = render_assets(root, ASSETS, host);
    let comparison = compare_rendered_assets(&rendered)?;

    let mut conflicts = Vec::new();
    let mut written = Vec::new();
    let mut unchanged = Vec::new();
    let mut replaced = Vec::new();

    for compared in comparison {
        match compared.state {
            InstalledAssetState::Missing => written.push(compared.relative_path.to_owned()),
            InstalledAssetState::Matching => unchanged.push(compared.relative_path.to_owned()),
            InstalledAssetState::Differing => {
                replaced.push(compared.relative_path.to_owned());
                conflicts.push(compared.relative_path.to_owned());
            }
        }
    }

    if !conflicts.is_empty() && !force {
        return Err(refusal(format!(
            "{} installed file(s) differ from the ones this crate ships: {}. Re-run with --force to replace them.",
            conflicts.len(),
            conflicts.join(", ")
        )));
    }

    // Every decision is made before the first byte lands, so a refusal above
    // leaves the tree exactly as it found it.
    for asset in &rendered {
        if let Some(parent) = asset.destination.parent() {
            fs::create_dir_all(parent).map_err(|error| {
                unsafe_failure(format!(
                    "Could not create {} for {}: {error}",
                    parent.display(),
                    asset.relative_path
                ))
            })?;
        }
        fs::write(&asset.destination, &asset.contents).map_err(|error| {
            unsafe_failure(format!("Could not write {}: {error}", asset.relative_path))
        })?;
    }

    let linked = install_discovery_links(root)?;
    let mut orphaned_packages = Vec::new();
    for name in retired_skill_package_names() {
        let package = root.join(".claude/skills").join(name);
        let link = root.join(".agents/skills").join(name);
        if path_exists_without_following(&package)? || path_exists_without_following(&link)? {
            orphaned_packages.push(name.to_owned());
        }
    }

    Ok(InstallReceipt {
        schema_version: 1,
        written,
        unchanged,
        replaced,
        linked,
        orphaned_packages,
    })
}

/// Compares only the installed Skill Evolution package with this crate's rendered copy.
///
/// Missing shipped files and shipped files with different bytes are both mismatches.
/// The relative paths are the same paths [`install`] reports, and the byte comparison
/// is deliberately shared with that command so the lifecycle gate cannot disagree with
/// the installer about whether a shipped file is current.
pub(crate) fn compare_installed_skill_evolution_package(
    package: &Path,
    host: &Host,
) -> Result<InstalledSkillEvolutionPackageComparison, Error> {
    const PREFIX: &str = ".claude/skills/skill-evolution/";
    let rendered = ASSETS
        .iter()
        .filter_map(|asset| {
            asset
                .relative_path
                .strip_prefix(PREFIX)
                .map(|within_package| RenderedAsset {
                    destination: package.join(within_package),
                    contents: render(asset.template, host),
                    relative_path: asset.relative_path,
                })
        })
        .collect::<Vec<_>>();
    let differing_files = compare_rendered_assets(&rendered)?
        .into_iter()
        .filter(|comparison| comparison.state != InstalledAssetState::Matching)
        .map(|comparison| comparison.relative_path.to_owned())
        .collect::<Vec<_>>();
    Ok(InstalledSkillEvolutionPackageComparison {
        matches_shipped: differing_files.is_empty(),
        differing_files,
    })
}

fn render_assets(root: &Path, assets: &[Asset], host: &Host) -> Vec<RenderedAsset> {
    assets
        .iter()
        .map(|asset| RenderedAsset {
            destination: root.join(asset.relative_path),
            contents: render(asset.template, host),
            relative_path: asset.relative_path,
        })
        .collect()
}

fn compare_rendered_assets(
    rendered: &[RenderedAsset],
) -> Result<Vec<InstalledAssetComparison>, Error> {
    rendered
        .iter()
        .map(|asset| {
            let state = match read_existing(&asset.destination)? {
                None => InstalledAssetState::Missing,
                Some(existing) if existing == asset.contents => InstalledAssetState::Matching,
                Some(_) => InstalledAssetState::Differing,
            };
            Ok(InstalledAssetComparison {
                relative_path: asset.relative_path,
                state,
            })
        })
        .collect()
}

/// Removes every retired package this crate can still identify.
///
/// Every file and discovery-link decision is made before the first removal.
/// A differing retired file therefore refuses atomically unless `force` is
/// set. `force` does not widen the operation to paths the crate never shipped.
pub fn withdraw(root: &Path, host: &Host, force: bool) -> Result<WithdrawalReceipt, Error> {
    let expected_paths: HashSet<PathBuf> = RETIRED_ASSETS
        .iter()
        .map(|asset| PathBuf::from(asset.relative_path))
        .collect();
    let mut files_to_remove = Vec::new();
    let mut forced_files_to_remove = HashSet::new();
    let mut retained = Vec::new();
    let mut conflicts = Vec::new();
    let mut package_directories = Vec::new();

    let mut safe_packages = HashSet::new();
    if safe_directory_boundary(root, ".claude/skills", &mut retained)? {
        for name in retired_skill_package_names() {
            if inspect_foreign_package_entries(
                root,
                name,
                &expected_paths,
                &mut retained,
                &mut package_directories,
            )? {
                safe_packages.insert(name);
            }
        }
    }

    for asset in RETIRED_ASSETS {
        let package_name = asset
            .relative_path
            .strip_prefix(".claude/skills/")
            .and_then(|path| path.split('/').next())
            .expect("every retired asset belongs to a retired skill package");
        if !safe_packages.contains(package_name) {
            continue;
        }
        let destination = root.join(asset.relative_path);
        let metadata = match fs::symlink_metadata(&destination) {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
            Err(error) => {
                return Err(unsafe_failure(format!(
                    "Could not inspect {} before withdrawal: {error}",
                    asset.relative_path
                )));
            }
        };
        if !metadata.file_type().is_file() {
            retained.push(RetainedPath {
                path: asset.relative_path.to_owned(),
                reason: "expected retired path is not a regular file shipped by this crate"
                    .to_owned(),
            });
            continue;
        }

        let existing = fs::read(&destination).map_err(|error| {
            unsafe_failure(format!(
                "Could not read {} to compare it before withdrawal: {error}",
                asset.relative_path
            ))
        })?;
        if existing == render(asset.template, host).as_bytes() {
            files_to_remove.push(asset.relative_path.to_owned());
        } else if force {
            files_to_remove.push(asset.relative_path.to_owned());
            forced_files_to_remove.insert(asset.relative_path.to_owned());
        } else {
            conflicts.push(asset.relative_path.to_owned());
        }
    }

    let mut links_to_remove = Vec::new();
    if safe_directory_boundary(root, ".agents/skills", &mut retained)? {
        for name in retired_skill_package_names() {
            let relative = PathBuf::from(".agents/skills").join(name);
            let link = root.join(&relative);
            let expected = PathBuf::from("../../.claude/skills").join(name);
            match fs::read_link(&link) {
                Ok(destination) if destination == expected => links_to_remove.push(relative),
                Ok(destination) => retained.push(RetainedPath {
                    path: portable_path(&relative),
                    reason: format!(
                        "discovery link points to {} instead of {}",
                        destination.display(),
                        expected.display()
                    ),
                }),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                Err(_) => match fs::symlink_metadata(&link) {
                    Ok(_) => retained.push(RetainedPath {
                        path: portable_path(&relative),
                        reason: "discovery path is not a link created by this crate".to_owned(),
                    }),
                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                    Err(error) => {
                        return Err(unsafe_failure(format!(
                            "Could not inspect {} before withdrawal: {error}",
                            portable_path(&relative)
                        )));
                    }
                },
            }
        }
    }

    retained.sort_by(|left, right| (&left.path, &left.reason).cmp(&(&right.path, &right.reason)));
    if !conflicts.is_empty() {
        return Err(refusal(format!(
            "{} retired installed file(s) differ from the last copies this crate shipped: {}. Re-run with --force to withdraw them.",
            conflicts.len(),
            conflicts.join(", ")
        )));
    }

    let mut receipt = WithdrawalReceipt {
        schema_version: 1,
        removed_files: Vec::new(),
        forced_files: Vec::new(),
        removed_directories: Vec::new(),
        removed_links: Vec::new(),
        retained,
    };

    for relative in files_to_remove {
        if let Err(error) = fs::remove_file(root.join(&relative)) {
            return Err(partial_withdrawal_failure(
                format!("Could not remove {relative}: {error}"),
                &receipt,
            ));
        }
        if forced_files_to_remove.contains(&relative) {
            receipt.forced_files.push(relative.clone());
        }
        receipt.removed_files.push(relative);
    }

    for relative in links_to_remove {
        if let Err(error) = fs::remove_file(root.join(&relative)) {
            return Err(partial_withdrawal_failure(
                format!(
                    "Could not remove discovery link {}: {error}",
                    portable_path(&relative)
                ),
                &receipt,
            ));
        }
        receipt.removed_links.push(portable_path(&relative));
    }

    remove_empty_package_directories(root, package_directories, &mut receipt)?;

    Ok(receipt)
}

fn inspect_foreign_package_entries(
    root: &Path,
    package_name: &str,
    expected_paths: &HashSet<PathBuf>,
    retained: &mut Vec<RetainedPath>,
    package_directories: &mut Vec<PathBuf>,
) -> Result<bool, Error> {
    let package = root.join(".claude/skills").join(package_name);
    let metadata = match fs::symlink_metadata(&package) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(error) => {
            return Err(unsafe_failure(format!(
                "Could not inspect retired package {}: {error}",
                portable_relative(root, &package)
            )));
        }
    };
    if !metadata.file_type().is_dir() {
        retained.push(RetainedPath {
            path: portable_relative(root, &package),
            reason: "retired package path is not a directory created by this crate".to_owned(),
        });
        return Ok(false);
    }

    let mut pending = vec![package];
    while let Some(directory) = pending.pop() {
        package_directories.push(directory.clone());
        let entries = fs::read_dir(&directory).map_err(|error| {
            unsafe_failure(format!(
                "Could not inspect retired package directory {}: {error}",
                portable_relative(root, &directory)
            ))
        })?;
        for entry in entries {
            let entry = entry.map_err(|error| {
                unsafe_failure(format!(
                    "Could not inspect an entry under {}: {error}",
                    portable_relative(root, &directory)
                ))
            })?;
            let path = entry.path();
            let metadata = fs::symlink_metadata(&path).map_err(|error| {
                unsafe_failure(format!(
                    "Could not inspect {} before withdrawal: {error}",
                    portable_relative(root, &path)
                ))
            })?;
            if metadata.file_type().is_dir() {
                pending.push(path);
                continue;
            }

            let relative = path
                .strip_prefix(root)
                .expect("a traversed retired-package path stays below root");
            if !expected_paths.contains(relative) {
                retained.push(RetainedPath {
                    path: portable_path(relative),
                    reason: "path was not shipped by this crate".to_owned(),
                });
            }
        }
    }
    Ok(true)
}

fn safe_directory_boundary(
    root: &Path,
    relative: &str,
    retained: &mut Vec<RetainedPath>,
) -> Result<bool, Error> {
    let path = root.join(relative);
    match fs::symlink_metadata(&path) {
        Ok(metadata) if metadata.file_type().is_dir() => Ok(true),
        Ok(_) => {
            retained.push(RetainedPath {
                path: relative.to_owned(),
                reason: "withdrawal boundary is not a directory created by this crate".to_owned(),
            });
            Ok(false)
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(unsafe_failure(format!(
            "Could not inspect withdrawal boundary {relative}: {error}"
        ))),
    }
}

fn remove_empty_package_directories(
    root: &Path,
    mut directories: Vec<PathBuf>,
    receipt: &mut WithdrawalReceipt,
) -> Result<(), Error> {
    directories.sort_by(|left, right| {
        right
            .components()
            .count()
            .cmp(&left.components().count())
            .then_with(|| left.cmp(right))
    });

    for directory in directories {
        match fs::remove_dir(&directory) {
            Ok(()) => receipt
                .removed_directories
                .push(portable_relative(root, &directory)),
            Err(error) if error.kind() == std::io::ErrorKind::DirectoryNotEmpty => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => {
                return Err(partial_withdrawal_failure(
                    format!(
                        "Could not remove empty retired-package directory {}: {error}",
                        portable_relative(root, &directory)
                    ),
                    receipt,
                ));
            }
        }
    }
    Ok(())
}

fn partial_withdrawal_failure(message: String, receipt: &WithdrawalReceipt) -> Error {
    let receipt = serde_json::to_string(receipt)
        .expect("serializing a withdrawal receipt containing only strings cannot fail");
    unsafe_failure(format!("{message}. Partial withdrawal receipt: {receipt}"))
}

fn portable_relative(root: &Path, path: &Path) -> String {
    portable_path(
        path.strip_prefix(root)
            .expect("an asset operation reports only paths below root"),
    )
}

fn portable_path(path: &Path) -> String {
    path.components()
        .map(|component| component.as_os_str().to_string_lossy())
        .collect::<Vec<_>>()
        .join("/")
}

fn path_exists_without_following(path: &Path) -> Result<bool, Error> {
    match fs::symlink_metadata(path) {
        Ok(_) => Ok(true),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(unsafe_failure(format!(
            "Could not inspect {}: {error}",
            path.display()
        ))),
    }
}

/// Points `.agents/skills/<name>` at each installed package.
///
/// A package is only half-installed without its link: `.claude/skills/` is
/// where the file lives and `.agents/skills/` is where a non-Claude client
/// looks, and the lifecycle itself searches both (see `skill_key`). Returns the
/// links this call created; an existing correct link is left alone and not
/// reported.
fn install_discovery_links(root: &Path) -> Result<Vec<String>, Error> {
    let mut created = Vec::new();
    for name in skill_package_names() {
        let link = root.join(".agents/skills").join(name);
        // Relative, and relative to the link's own directory: an absolute
        // target would break the moment the repository is cloned elsewhere.
        let destination = PathBuf::from("../../.claude/skills").join(name);

        match fs::read_link(&link) {
            Ok(existing) if existing == destination => continue,
            Ok(_) => {
                fs::remove_file(&link).map_err(|error| {
                    unsafe_failure(format!(
                        "Could not replace the discovery link {}: {error}",
                        link.display()
                    ))
                })?;
            }
            // Not a link: either absent, or something else entirely. Creating
            // the link below reports the difference either way.
            Err(_) => {}
        }

        if let Some(parent) = link.parent() {
            fs::create_dir_all(parent).map_err(|error| {
                unsafe_failure(format!(
                    "Could not create {} for discovery links: {error}",
                    parent.display()
                ))
            })?;
        }
        match symlink(&destination, &link) {
            Ok(()) => created.push(format!(".agents/skills/{name}")),
            Err(error) if error.kind() == std::io::ErrorKind::Unsupported => return Ok(Vec::new()),
            Err(error) => {
                return Err(unsafe_failure(format!(
                    "Could not create the discovery link {}: {error}",
                    link.display()
                )));
            }
        }
    }
    Ok(created)
}

#[cfg(unix)]
fn symlink(destination: &Path, link: &Path) -> std::io::Result<()> {
    std::os::unix::fs::symlink(destination, link)
}

/// Windows needs a privilege for directory symlinks that an ordinary user does
/// not have, so discovery there is left to `.claude/skills/` alone rather than
/// failing an otherwise complete install.
#[cfg(not(unix))]
fn symlink(_destination: &Path, _link: &Path) -> std::io::Result<()> {
    Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
}

/// Substitutes the host's names into one shipped file.
fn render(template: &str, host: &Host) -> String {
    template
        .replace("{{cargo_package}}", &host.cargo_package)
        .replace("{{command}}", &host.command)
        .replace("{{namespace}}", &host.namespace)
}

/// The file's current contents, or `None` when it is not there yet.
fn read_existing(path: &Path) -> Result<Option<String>, Error> {
    match fs::read_to_string(path) {
        Ok(contents) => Ok(Some(contents)),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(error) => Err(unsafe_failure(format!(
            "Could not read {} to compare it: {error}",
            path.display()
        ))),
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use super::*;

    fn host() -> Host {
        Host {
            namespace: "demo".to_owned(),
            command: "demo".to_owned(),
            cargo_package: "demo-cli".to_owned(),
            skills_directory: PathBuf::from("/nonexistent/.claude/skills"),
        }
    }

    fn markdown_link_targets(contents: &str) -> Vec<&str> {
        let mut targets = Vec::new();
        let mut remainder = contents;
        while let Some(start) = remainder.find("](") {
            remainder = &remainder[start + 2..];
            let Some(end) = remainder.find(')') else {
                break;
            };
            let target = &remainder[..end];
            if !target.is_empty()
                && !target.starts_with('#')
                && !target.contains("://")
                && !target.starts_with("mailto:")
            {
                targets.push(target);
            }
            remainder = &remainder[end + 1..];
        }
        targets
    }

    fn backticked_package_relative_paths(contents: &str) -> Vec<&str> {
        contents
            .split('`')
            .enumerate()
            .filter_map(|(index, span)| {
                (index % 2 == 1 && (span.starts_with("references/") || span.starts_with("../")))
                    .then_some(span)
            })
            .collect()
    }

    fn resolve_package_relative_path(source: &str, target: &str) -> Option<String> {
        let mut components: Vec<&str> = source.split('/').collect();
        components.pop();

        for component in target.split('/') {
            match component {
                "" | "." => {}
                ".." => {
                    components.pop()?;
                }
                component => components.push(component),
            }
        }

        Some(components.join("/"))
    }

    #[test]
    fn every_shipped_markdown_reference_resolves_within_shipped_assets() {
        let shipped_paths: HashSet<&str> = ASSETS.iter().map(|asset| asset.relative_path).collect();
        let evolution = ASSETS
            .iter()
            .find(|asset| asset.relative_path == ".claude/skills/skill-evolution/SKILL.md")
            .expect("the shipped Skill Evolution package");
        assert_eq!(
            backticked_package_relative_paths(evolution.template),
            vec!["references/authorized-review.md"]
        );
        let authorized_review = ASSETS
            .iter()
            .find(|asset| {
                asset.relative_path
                    == ".claude/skills/skill-evolution/references/authorized-review.md"
            })
            .expect("the shipped authorized-review reference");
        assert!(backticked_package_relative_paths(authorized_review.template).is_empty());

        let mut unresolved = Vec::new();
        for asset in ASSETS
            .iter()
            .filter(|asset| asset.relative_path.ends_with(".md"))
        {
            let targets = markdown_link_targets(asset.template)
                .into_iter()
                .chain(backticked_package_relative_paths(asset.template));
            for target in targets {
                match resolve_package_relative_path(asset.relative_path, target) {
                    Some(path) if shipped_paths.contains(path.as_str()) => {}
                    _ => unresolved.push(format!("{} -> {target}", asset.relative_path)),
                }
            }
        }

        assert_eq!(unresolved, Vec::<String>::new());
    }

    #[test]
    fn every_shipped_file_renders_without_leaving_a_placeholder() {
        for asset in ASSETS {
            let rendered = render(asset.template, &host());
            assert!(
                !rendered.contains("{{"),
                "{} still holds a placeholder after rendering",
                asset.relative_path
            );
        }
    }

    #[test]
    fn install_writes_every_asset_and_reports_them() {
        let root = tempfile::tempdir().expect("temporary repository root");
        let receipt = install(root.path(), &host(), false).expect("install into an empty root");
        assert_eq!(receipt.written.len(), ASSETS.len());
        assert!(receipt.unchanged.is_empty());
        assert!(receipt.replaced.is_empty());
        for asset in ASSETS {
            assert!(
                root.path().join(asset.relative_path).is_file(),
                "{} was not written",
                asset.relative_path
            );
        }
    }

    #[test]
    fn every_skill_package_gets_a_relative_discovery_link() {
        let root = tempfile::tempdir().expect("temporary repository root");
        let receipt = install(root.path(), &host(), false).expect("install into an empty root");
        let names = skill_package_names();
        assert_eq!(names.len(), 4, "the four packages this crate ships");

        #[cfg(unix)]
        {
            assert_eq!(receipt.linked.len(), names.len());
            for name in names {
                assert_eq!(
                    fs::read_link(root.path().join(".agents/skills").join(name))
                        .expect("read discovery link"),
                    PathBuf::from("../../.claude/skills").join(name)
                );
            }
        }
        #[cfg(not(unix))]
        assert!(receipt.linked.is_empty());
    }

    #[test]
    fn reinstalling_leaves_a_correct_discovery_link_alone() {
        let root = tempfile::tempdir().expect("temporary repository root");
        install(root.path(), &host(), false).expect("first install");
        let receipt = install(root.path(), &host(), false).expect("second install");
        assert!(
            receipt.linked.is_empty(),
            "a link that already points where it should is not re-created"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_discovery_link_pointing_somewhere_else_is_repaired() {
        let root = tempfile::tempdir().expect("temporary repository root");
        install(root.path(), &host(), false).expect("first install");
        let link = root.path().join(".agents/skills/skill-evolution");
        fs::remove_file(&link).expect("remove the correct link");
        std::os::unix::fs::symlink("../../elsewhere", &link).expect("point it elsewhere");

        let receipt = install(root.path(), &host(), false).expect("second install");
        assert_eq!(
            receipt.linked,
            vec![".agents/skills/skill-evolution".to_owned()]
        );
        assert_eq!(
            fs::read_link(&link).expect("read repaired link"),
            PathBuf::from("../../.claude/skills/skill-evolution")
        );
    }

    #[test]
    fn reinstalling_the_same_tree_reports_every_file_unchanged() {
        let root = tempfile::tempdir().expect("temporary repository root");
        install(root.path(), &host(), false).expect("first install");
        let receipt = install(root.path(), &host(), false).expect("second install");
        assert_eq!(receipt.unchanged.len(), ASSETS.len());
        assert!(receipt.written.is_empty());
    }

    #[test]
    fn install_refuses_an_edited_file_and_leaves_it_alone() {
        let root = tempfile::tempdir().expect("temporary repository root");
        install(root.path(), &host(), false).expect("first install");
        let edited = root.path().join(".claude/skills/skill-evolution/SKILL.md");
        fs::write(&edited, "Locally edited.\n").expect("edit an installed file");

        let error = install(root.path(), &host(), false).expect_err("refuse the edited file");
        assert_eq!(error.class(), crate::ErrorClass::Refusal);
        assert!(error.to_string().contains("--force"));
        assert_eq!(
            fs::read_to_string(&edited).expect("read back"),
            "Locally edited.\n",
            "a refusal must not have written anything"
        );
    }

    #[test]
    fn force_replaces_an_edited_file_and_names_it() {
        let root = tempfile::tempdir().expect("temporary repository root");
        install(root.path(), &host(), false).expect("first install");
        let edited = root.path().join(".claude/skills/skill-evolution/SKILL.md");
        fs::write(&edited, "Locally edited.\n").expect("edit an installed file");

        let receipt = install(root.path(), &host(), true).expect("force past the edit");
        assert_eq!(
            receipt.replaced,
            vec![".claude/skills/skill-evolution/SKILL.md".to_owned()]
        );
        assert_ne!(
            fs::read_to_string(&edited).expect("read back"),
            "Locally edited.\n"
        );
    }

    #[test]
    fn a_host_installs_its_own_names_not_the_authoring_repositorys() {
        let root = tempfile::tempdir().expect("temporary repository root");
        install(root.path(), &host(), false).expect("install");
        let skill = fs::read_to_string(
            root.path()
                .join(".claude/skills/skill-evidence-capture/SKILL.md"),
        )
        .expect("read the installed skill");
        assert!(skill.contains("`demo skills evidence`"));
        assert!(skill.contains("cargo run --locked -p demo-cli"));
        assert!(!skill.contains("playbench"));
    }
}