Skip to main content

spec_driven_docs/services/
skill_installer.rs

1//! Install the embedded skills into agent skill directories, as packages.
2//!
3//! The destinations live outside any instance — under the invoking user's
4//! home — so nothing here touches an instance manifest. The unit is the
5//! package: one directory per skill, holding `SKILL.md` and every shared
6//! artifact under `references/`, which is what the Agent Skills format and
7//! every documented host resolve against.
8//!
9//! Three references decide every destination: the payload, the receipt, and
10//! the disk. Bytes matching the payload are current. Bytes the receipt
11//! vouches for are this tool's and may be replaced or taken back. Every
12//! other byte is the user's: an install refuses it without `--force`, and
13//! an uninstall leaves it and names it.
14//!
15//! Every apply holds the user-scope lock for its whole run, stages each
16//! write beside its destination, replaces one file at a time, and writes the
17//! receipt last. A run the process does not finish leaves whole files and
18//! the previous receipt, reports what it wrote, and is safe to run again.
19
20use std::collections::BTreeSet;
21
22use camino::{Utf8Path, Utf8PathBuf};
23
24use crate::domain::ownership::Sha256;
25use crate::domain::paths::HOME_VAR;
26use crate::domain::skill_record::SkillRecord;
27use crate::error::AppError;
28use crate::transaction::lock::Lock;
29use crate::transaction::stage::Stage;
30
31// The roots are declared in `domain::paths` and reach their callers from
32// here, so that what a destination is stays one statement and what an
33// install does with it stays another.
34pub use crate::domain::paths::{AGENTS_ROOT, CLAUDE_ROOT, LEGACY_SHARED_ROOT};
35
36/// The invoking user's home directory.
37///
38/// # Errors
39///
40/// [`AppError::Usage`] when `HOME` is unset or empty.
41pub fn home() -> Result<Utf8PathBuf, AppError> {
42    crate::domain::paths::UserEnv::from_process()
43        .home
44        .ok_or_else(|| AppError::Usage(format!("{HOME_VAR} is not set")))
45}
46
47/// Where one run writes: the agent roots, the state root, and the receipt.
48#[derive(Debug, Clone)]
49pub struct Layout {
50    /// The agent skill roots this run was asked to touch, deduplicated.
51    pub roots: Vec<Utf8PathBuf>,
52    /// Where this tool keeps state that outlives a command.
53    pub state_root: Utf8PathBuf,
54    /// The receipt vouching for every user-scope file this tool wrote.
55    pub receipt: Utf8PathBuf,
56    /// The receipt at the home-relative path, read once as a fallback.
57    pub legacy_receipt: Utf8PathBuf,
58    /// The retired shared root, swept rather than written. Only a run over
59    /// every agent root sweeps it, because an older manual under a root the
60    /// run leaves alone still reads its gates.
61    pub legacy_shared: Option<Utf8PathBuf>,
62}
63
64impl Layout {
65    /// The lock every apply holds for its whole run.
66    #[must_use]
67    pub fn lock_path(&self) -> Utf8PathBuf {
68        self.state_root.join(crate::domain::paths::SKILL_LOCK_FILE)
69    }
70
71    /// Every location a sweep reads: the selected roots, and the retired one
72    /// where this run sweeps it.
73    fn scanned(&self) -> Vec<Utf8PathBuf> {
74        let mut scanned = self.roots.clone();
75        scanned.extend(self.legacy_shared.clone());
76        scanned
77    }
78}
79
80/// One planned file: where, which bytes, and their digest.
81#[derive(Debug, Clone)]
82struct Planned {
83    destination: Utf8PathBuf,
84    bytes: &'static [u8],
85    digest: Sha256,
86}
87
88/// A destination this tool refuses to write through, whatever `--force` says.
89#[derive(Debug, Clone, PartialEq, Eq)]
90struct Blocked {
91    path: Utf8PathBuf,
92    kind: &'static str,
93}
94
95impl std::fmt::Display for Blocked {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        write!(f, "{} is {}", self.path, self.kind)
98    }
99}
100
101/// How a run ends when a test interrupts it.
102///
103/// `Abandoned` stands in for the process dying partway, which leaves the
104/// files written so far and the previous receipt.
105enum Failure {
106    Error(AppError),
107    Abandoned,
108}
109
110impl From<AppError> for Failure {
111    fn from(error: AppError) -> Self {
112        Self::Error(error)
113    }
114}
115
116impl From<std::io::Error> for Failure {
117    fn from(error: std::io::Error) -> Self {
118        Self::Error(AppError::Io(error))
119    }
120}
121
122/// Where a run stops, counted in boundaries of the persistence order.
123///
124/// Production never sets it. The recovery tests walk it from one upward and
125/// assert that the next invocation puts every destination back before it
126/// writes anything new.
127#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
128struct Interrupt {
129    /// Stop after this many boundaries, without rolling back.
130    after: Option<usize>,
131}
132
133fn reached(passed: &mut usize, interrupt: Interrupt) -> Result<(), Failure> {
134    *passed += 1;
135    if interrupt.after == Some(*passed) {
136        return Err(Failure::Abandoned);
137    }
138    Ok(())
139}
140
141/// Every file of every package under `roots`, root by root and skill by skill.
142fn plan(roots: &[Utf8PathBuf]) -> Result<Vec<Planned>, AppError> {
143    let mut planned = Vec::new();
144    for root in roots {
145        for name in crate::embedded::skill_names() {
146            let package = crate::embedded::skill_package(name).map_err(anyhow::Error::from)?;
147            for (relative, bytes) in package {
148                planned.push(Planned {
149                    destination: root.join(name).join(relative),
150                    bytes,
151                    digest: Sha256::of(bytes),
152                });
153            }
154        }
155    }
156    Ok(planned)
157}
158
159/// The first component of `destination` under `root` this tool will not
160/// write through.
161///
162/// Every component is inspected without following links, from the agent
163/// root down. Directories above the root are the user's layout and stay
164/// unjudged: this tool did not create them and does not police them.
165fn blocked_by(root: &Utf8Path, destination: &Utf8Path) -> Option<Blocked> {
166    let relative = destination.strip_prefix(root).ok()?;
167    let mut current = root.to_owned();
168    if let Ok(meta) = std::fs::symlink_metadata(&current) {
169        if meta.file_type().is_symlink() {
170            return Some(Blocked {
171                path: current,
172                kind: "a symlink",
173            });
174        }
175        if !meta.is_dir() {
176            return Some(Blocked {
177                path: current,
178                kind: "a file where a directory is needed",
179            });
180        }
181    }
182    let components: Vec<&str> = relative.as_str().split('/').collect();
183    let last = components.len().saturating_sub(1);
184    for (index, part) in components.iter().enumerate() {
185        current = current.join(part);
186        let Ok(meta) = std::fs::symlink_metadata(&current) else {
187            // Absent, so nothing below it exists either.
188            return None;
189        };
190        if meta.file_type().is_symlink() {
191            return Some(Blocked {
192                path: current,
193                kind: "a symlink",
194            });
195        }
196        if index == last {
197            if !meta.is_file() {
198                return Some(Blocked {
199                    path: current,
200                    kind: if meta.is_dir() {
201                        "a directory"
202                    } else {
203                        "not a regular file"
204                    },
205                });
206            }
207        } else if !meta.is_dir() {
208            return Some(Blocked {
209                path: current,
210                kind: "a file where a directory is needed",
211            });
212        }
213    }
214    None
215}
216
217/// Which root a destination sits under, for the chain check.
218fn owning_root<'a>(layout: &'a Layout, destination: &Utf8Path) -> Option<&'a Utf8Path> {
219    layout
220        .roots
221        .iter()
222        .chain(std::iter::once(&layout.state_root))
223        // The retired root is swept rather than written, and a sweep
224        // unlinks. A destination under it that no root claimed would reach
225        // the removal with no component checked at all.
226        .chain(&layout.legacy_shared)
227        .map(Utf8PathBuf::as_path)
228        .find(|root| destination.starts_with(root))
229}
230
231/// Every destination this run will not write through.
232fn blocked(layout: &Layout, destinations: &[Utf8PathBuf]) -> Vec<Blocked> {
233    let mut found = Vec::new();
234    for destination in destinations {
235        let Some(root) = owning_root(layout, destination) else {
236            continue;
237        };
238        if let Some(one) = blocked_by(root, destination)
239            && !found.contains(&one)
240        {
241            found.push(one);
242        }
243    }
244    found
245}
246
247/// What a destination currently holds, judged against the two references.
248#[cfg(test)]
249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
250enum Standing {
251    /// Nothing is there.
252    Absent,
253    /// The payload's own bytes.
254    Current,
255    /// Bytes the receipt vouches for, from an earlier release.
256    Recorded,
257    /// Bytes neither reference accounts for.
258    Foreign,
259}
260
261#[cfg(test)]
262fn standing(
263    destination: &Utf8Path,
264    intended: &Sha256,
265    record: &SkillRecord,
266) -> Result<Standing, AppError> {
267    if !destination.is_file() {
268        return Ok(Standing::Absent);
269    }
270    // An unreadable destination raises instead of passing as clean: a
271    // comparison that cannot run must never license an overwrite.
272    let found = Sha256::of(&std::fs::read(destination)?);
273    if &found == intended {
274        return Ok(Standing::Current);
275    }
276    if record.wrote(destination, &found) {
277        return Ok(Standing::Recorded);
278    }
279    Ok(Standing::Foreign)
280}
281
282/// Recorded destinations under a scanned root that this run no longer plans.
283///
284/// Only bytes the receipt still vouches for are swept: a leftover the user
285/// edited is theirs. This is also what sweeps the retired shared root, whose
286/// two files an earlier release wrote and recorded.
287fn leftovers(
288    scanned: &[Utf8PathBuf],
289    record: &SkillRecord,
290    keep: &BTreeSet<Utf8PathBuf>,
291) -> Vec<(Utf8PathBuf, Sha256, bool)> {
292    record
293        .written
294        .iter()
295        .filter(|(destination, _)| {
296            !keep.contains(*destination) && scanned.iter().any(|root| destination.starts_with(root))
297        })
298        .map(|(destination, digest)| {
299            let ours = !destination.is_symlink()
300                && destination.is_file()
301                && std::fs::read(destination).is_ok_and(|found| Sha256::of(&found) == *digest);
302            (destination.clone(), digest.clone(), ours)
303        })
304        .collect()
305}
306
307/// Remove the directories a removal emptied, deepest first, up to `stop`.
308fn prune_empty(directories: &BTreeSet<Utf8PathBuf>, stop: &[Utf8PathBuf], lines: &mut Vec<String>) {
309    let mut deepest: Vec<&Utf8PathBuf> = directories.iter().collect();
310    deepest.sort_by_key(|path| std::cmp::Reverse(path.components().count()));
311    for directory in deepest {
312        if stop.iter().any(|root| root == directory) {
313            continue;
314        }
315        let Ok(mut entries) = std::fs::read_dir(directory) else {
316            continue;
317        };
318        if entries.next().is_none() {
319            let _ = std::fs::remove_dir(directory);
320        } else {
321            lines.push(format!("kept (not empty): {directory}"));
322        }
323    }
324}
325
326/// The receipt this run intends to leave.
327fn next_receipt(record: &SkillRecord, written: &[Planned], removed: &[Utf8PathBuf]) -> SkillRecord {
328    let mut next = record.clone();
329    next.schema_version = crate::domain::skill_record::SCHEMA_VERSION;
330    next.engine_version = env!("CARGO_PKG_VERSION").to_string();
331    for destination in removed {
332        next.written.remove(destination);
333    }
334    for entry in written {
335        next.written
336            .insert(entry.destination.clone(), entry.digest.clone());
337    }
338    // A run that changed nothing leaves the receipt alone, timestamp
339    // included. A record rewritten on every invocation would make a second
340    // install write a file, and idempotence is what tells an operator that
341    // the home is already current.
342    if next.written == record.written
343        && next.engine_version == record.engine_version
344        && record.schema_version == crate::domain::skill_record::SCHEMA_VERSION
345    {
346        return record.clone();
347    }
348    next.installed_at = jiff::Timestamp::now().to_string();
349    next
350}
351
352/// Read the receipt, falling back to the home-relative path once.
353fn load_receipt(layout: &Layout) -> SkillRecord {
354    SkillRecord::load_with_fallback(&layout.receipt, &layout.legacy_receipt)
355}
356
357/// Install every embedded skill package under each root, previewing by default.
358///
359/// # Errors
360///
361/// [`AppError::Refused`] when a destination is reached through a link or
362/// holds bytes neither reference accounts for without `--force`,
363/// [`AppError::Busy`] when another process holds the lock,
364/// [`AppError::Unrecovered`] when an unfinished run cannot be put back, and
365/// [`AppError::Receipt`] when the apply cannot record what it wrote.
366#[cfg(test)]
367pub(crate) fn install(layout: &Layout, apply: bool, force: bool) -> Result<Vec<String>, AppError> {
368    settle(install_with(layout, apply, force, Interrupt::default()))
369}
370
371/// The line an uninstall writes for a path it cannot remove through, such
372/// as a link below an agent root. The caller counts these lines and exits
373/// with the refusal code once the rest is removed.
374pub const KEPT_BLOCKED: &str = "kept (blocked): ";
375
376/// Remove every installed skill package under each root, previewing by default.
377///
378/// A root that is itself a link is read at its target, because the
379/// operator placed that link. A path below a root that cannot be removed
380/// through, such as a link, stays and is named with [`KEPT_BLOCKED`], and
381/// every other recorded file still goes.
382///
383/// # Errors
384///
385/// As [`install`], except that nothing here refuses on foreign bytes or on
386/// a blocked path: a file the receipt cannot vouch for stays and is named.
387pub fn uninstall(layout: &Layout, apply: bool) -> Result<Vec<String>, AppError> {
388    settle(uninstall_with(layout, apply, Interrupt::default()))
389}
390
391fn settle(result: Result<Vec<String>, Failure>) -> Result<Vec<String>, AppError> {
392    result.map_err(|failure| match failure {
393        Failure::Error(error) => error,
394        Failure::Abandoned => AppError::Other(anyhow::anyhow!(
395            "the run was interrupted; the next invocation recovers it"
396        )),
397    })
398}
399
400/// The lock an applied run holds for the whole of its own reasoning.
401///
402/// A preview takes none: it writes nothing, and a preview that refused
403/// because somebody else was installing would fail for a reason the
404/// operator cannot act on. An applied run takes it before it reads a
405/// receipt or scans a destination, so every decision it makes is one the
406/// world still agrees with when it executes. A run that derived its
407/// removals before the lock could remove files a newer install had just
408/// written.
409///
410/// # Errors
411///
412/// [`AppError::Busy`] when another process holds it.
413fn held(layout: &Layout, apply: bool, purpose: &str) -> Result<Option<Lock>, Failure> {
414    if !apply {
415        return Ok(None);
416    }
417    let lock = Lock::exclusive(&layout.lock_path(), purpose)?;
418    Ok(Some(lock))
419}
420
421/// The install, with the recovery tests' interruption point. Only the
422/// tests run it: they build the homes earlier releases left.
423#[cfg(test)]
424fn install_with(
425    layout: &Layout,
426    apply: bool,
427    force: bool,
428    interrupt: Interrupt,
429) -> Result<Vec<String>, Failure> {
430    let _lock = held(layout, apply, "skill install")?;
431    let planned = plan(&layout.roots)?;
432    let mut lines: Vec<String> = planned
433        .iter()
434        .map(|entry| entry.destination.to_string())
435        .collect();
436
437    let record = load_receipt(layout);
438    let kept: BTreeSet<Utf8PathBuf> = planned
439        .iter()
440        .map(|entry| entry.destination.clone())
441        .collect();
442    let stale = leftovers(&layout.scanned(), &record, &kept);
443    for (destination, _, ours) in &stale {
444        if *ours {
445            lines.push(format!(
446                "to sweep (no longer in the payload): {destination}"
447            ));
448        } else {
449            lines.push(format!("kept (edited): {destination}"));
450        }
451    }
452
453    let mut destinations: Vec<Utf8PathBuf> = planned
454        .iter()
455        .map(|entry| entry.destination.clone())
456        .collect();
457    destinations.push(layout.receipt.clone());
458    let refused = blocked(layout, &destinations);
459    for one in &refused {
460        lines.push(format!("conflict: {one}"));
461    }
462
463    let mut foreign: Vec<Utf8PathBuf> = Vec::new();
464    let mut writes: Vec<Planned> = Vec::new();
465    // What the receipt will vouch for is every destination that holds the
466    // payload's bytes once this run ends, not only the ones this run wrote.
467    // A previous run that stopped partway left files written and unrecorded,
468    // and a record that skipped them would never take them back.
469    let mut vouched: Vec<Planned> = Vec::new();
470    for entry in &planned {
471        if refused
472            .iter()
473            .any(|one| entry.destination.starts_with(&one.path))
474        {
475            continue;
476        }
477        vouched.push(entry.clone());
478        match standing(&entry.destination, &entry.digest, &record)? {
479            Standing::Current => {}
480            Standing::Foreign => {
481                foreign.push(entry.destination.clone());
482                writes.push(entry.clone());
483            }
484            Standing::Absent | Standing::Recorded => writes.push(entry.clone()),
485        }
486    }
487    for destination in &foreign {
488        lines.push(format!(
489            "conflict: {destination} holds bytes this tool did not write"
490        ));
491    }
492
493    if !apply {
494        lines.push("DRY RUN: no files written".to_string());
495        return Ok(lines);
496    }
497    if !refused.is_empty() {
498        return Err(refuse_blocked(&refused).into());
499    }
500    if !force && !foreign.is_empty() {
501        let paths: Vec<&str> = foreign.iter().map(|path| path.as_str()).collect();
502        return Err(AppError::Refused(format!(
503            "destinations hold bytes this tool did not write: {}; re-run with --force to overwrite",
504            paths.join(", ")
505        ))
506        .into());
507    }
508
509    let swept: Vec<Utf8PathBuf> = stale
510        .iter()
511        .filter(|(_, _, ours)| *ours)
512        .map(|(destination, _, _)| destination.clone())
513        .collect();
514    let receipt = next_receipt(&record, &vouched, &swept);
515    run_transaction(
516        layout,
517        &writes,
518        &stale
519            .into_iter()
520            .filter(|(_, _, ours)| *ours)
521            .map(|(destination, digest, _)| (destination, digest))
522            .collect::<Vec<_>>(),
523        &receipt,
524        &mut lines,
525        interrupt,
526    )?;
527    Ok(lines)
528}
529
530/// The uninstall, with the recovery tests' interruption point.
531/// A layout whose roots are read at their targets, and the moves that took
532/// each root there.
533struct Resolved {
534    layout: Layout,
535    aliases: Vec<(Utf8PathBuf, Utf8PathBuf)>,
536}
537
538/// Read each root at the directory it reaches, and drop a root that reaches
539/// one already held.
540///
541/// A configuration directory often holds its skill root as a link to the
542/// user's own, and judged without following links that root would block
543/// every file under it.
544fn resolve(layout: &Layout) -> Resolved {
545    let mut aliases: Vec<(Utf8PathBuf, Utf8PathBuf)> = Vec::new();
546    let mut resolve_one = |root: &Utf8Path| -> Utf8PathBuf {
547        match std::fs::canonicalize(root)
548            .ok()
549            .and_then(|found| Utf8PathBuf::from_path_buf(found).ok())
550        {
551            Some(target) if target != root => {
552                aliases.push((root.to_owned(), target.clone()));
553                target
554            }
555            _ => root.to_owned(),
556        }
557    };
558    let mut roots: Vec<Utf8PathBuf> = Vec::new();
559    for root in &layout.roots {
560        let target = resolve_one(root);
561        if !roots.contains(&target) {
562            roots.push(target);
563        }
564    }
565    let legacy_shared = layout.legacy_shared.as_deref().map(&mut resolve_one);
566    Resolved {
567        layout: Layout {
568            roots,
569            legacy_shared,
570            ..layout.clone()
571        },
572        aliases,
573    }
574}
575
576/// The receipt with each path recorded under a root's former spelling moved
577/// to the directory that root reaches, so a file an install wrote through a
578/// link is still the file it vouches for.
579fn rebased(mut record: SkillRecord, aliases: &[(Utf8PathBuf, Utf8PathBuf)]) -> SkillRecord {
580    if aliases.is_empty() {
581        return record;
582    }
583    record.written = std::mem::take(&mut record.written)
584        .into_iter()
585        .map(|(path, digest)| {
586            let moved = aliases.iter().find_map(|(former, target)| {
587                path.strip_prefix(former).ok().map(|rest| target.join(rest))
588            });
589            (moved.unwrap_or(path), digest)
590        })
591        .collect();
592    record
593}
594
595fn uninstall_with(
596    layout: &Layout,
597    apply: bool,
598    interrupt: Interrupt,
599) -> Result<Vec<String>, Failure> {
600    // SATISFIES distribution:skill-uninstall-removes-only-what-it-wrote
601    let resolved = resolve(layout);
602    let layout = &resolved.layout;
603    // A home with no receipt has nothing this tool wrote, so an uninstall
604    // there removes nothing and takes no lock: creating the lock file
605    // would itself be the write that home was promised it would not get.
606    let _lock = held(layout, apply && layout.receipt.exists(), "skill uninstall")?;
607    let planned = plan(&layout.roots)?;
608    let record = rebased(load_receipt(layout), &resolved.aliases);
609    let mut lines: Vec<String> = Vec::new();
610    let mut removals: Vec<(Utf8PathBuf, Sha256)> = Vec::new();
611
612    let mut refused = blocked(
613        layout,
614        &planned
615            .iter()
616            .map(|entry| entry.destination.clone())
617            .collect::<Vec<_>>(),
618    );
619    for one in &refused {
620        lines.push(format!("{KEPT_BLOCKED}{one}"));
621    }
622
623    for entry in &planned {
624        if refused
625            .iter()
626            .any(|one| entry.destination.starts_with(&one.path))
627        {
628            continue;
629        }
630        if !entry.destination.is_file() {
631            continue;
632        }
633        let found = Sha256::of(&std::fs::read(&entry.destination)?);
634        if record.wrote(&entry.destination, &found) {
635            lines.push(entry.destination.to_string());
636            removals.push((entry.destination.clone(), found));
637        } else if found == entry.digest {
638            // The payload's own bytes with no receipt behind them: this
639            // tool cannot tell its copy from one the user placed there.
640            lines.push(format!("kept (not this tool's): {}", entry.destination));
641        } else {
642            lines.push(format!("kept (edited): {}", entry.destination));
643        }
644    }
645
646    let keep: BTreeSet<Utf8PathBuf> = removals
647        .iter()
648        .map(|(destination, _)| destination.clone())
649        .collect();
650    for (destination, digest, ours) in leftovers(&layout.scanned(), &record, &keep) {
651        // A leftover below a link is never removed through it.
652        if let Some(one) =
653            owning_root(layout, &destination).and_then(|root| blocked_by(root, &destination))
654        {
655            if !refused.contains(&one) {
656                lines.push(format!("{KEPT_BLOCKED}{one}"));
657                refused.push(one);
658            }
659            continue;
660        }
661        if ours {
662            lines.push(format!("sweep (no longer in the payload): {destination}"));
663            removals.push((destination, digest));
664        } else if destination.exists() {
665            lines.push(format!("kept (edited): {destination}"));
666        }
667    }
668
669    if !apply {
670        lines.push("DRY RUN: no files removed".to_string());
671        return Ok(lines);
672    }
673    // A home this tool never wrote into has nothing to take back, and an
674    // uninstall there must leave it exactly as it found it — no state root,
675    // no lock file, nothing.
676    if removals.is_empty() && !layout.receipt.exists() {
677        return Ok(lines);
678    }
679
680    let gone: Vec<Utf8PathBuf> = removals
681        .iter()
682        .map(|(destination, _)| destination.clone())
683        .collect();
684    let receipt = next_receipt(&record, &[], &gone);
685    run_transaction(layout, &[], &removals, &receipt, &mut lines, interrupt)?;
686    Ok(lines)
687}
688
689fn refuse_blocked(refused: &[Blocked]) -> AppError {
690    let named: Vec<String> = refused.iter().map(Blocked::to_string).collect();
691    AppError::Refused(format!(
692        "destinations cannot be written through: {}; move them aside and run this again",
693        named.join("; ")
694    ))
695}
696
697/// Replace each file, remove what is gone, and record it last.
698///
699/// Each destination is replaced in its own directory, one rename at a time,
700/// and the receipt is written after all of them. There is no journal and no
701/// backup store: a run that stops partway leaves whole files, the previous
702/// receipt, and a report naming what it finished, and running it again
703/// finishes the rest.
704fn run_transaction(
705    layout: &Layout,
706    writes: &[Planned],
707    removals: &[(Utf8PathBuf, Sha256)],
708    receipt: &SkillRecord,
709    lines: &mut Vec<String>,
710    interrupt: Interrupt,
711) -> Result<(), Failure> {
712    // A receipt that vouches for nothing is removed rather than written:
713    // an empty record is a file that says the tool wrote something here,
714    // and it did not.
715    let empty = receipt.written.is_empty();
716    let receipt_bytes = receipt.to_json().into_bytes();
717    let receipt_current = if empty {
718        !layout.receipt.exists()
719    } else {
720        std::fs::read(&layout.receipt).is_ok_and(|held| held == receipt_bytes)
721    };
722    if writes.is_empty() && removals.is_empty() && receipt_current {
723        return Ok(());
724    }
725
726    let mut passed = 0usize;
727    let mut completed: Vec<Utf8PathBuf> = Vec::new();
728    // What the run meant to remove and did not, because the bytes there
729    // are no longer the ones the receipt vouches for. The record keeps
730    // them, so the doctor can still name what is left behind.
731    let mut kept: Vec<Utf8PathBuf> = Vec::new();
732
733    for entry in writes {
734        replace_one(layout, &entry.destination, entry.bytes)
735            .map_err(|failure| stopped(failure, &completed))?;
736        completed.push(entry.destination.clone());
737        reached(&mut passed, interrupt)?;
738    }
739    for (destination, vouched) in removals {
740        // A component swapped since the run was planned is refused rather
741        // than followed: a removal through a link would unlink somebody
742        // else's file.
743        //
744        if let Some(root) = owning_root(layout, destination)
745            && let Some(one) = blocked_by(root, destination)
746        {
747            return Err(stopped(
748                Failure::Error(refuse_blocked(std::slice::from_ref(&one))),
749                &completed,
750            ));
751        }
752        // The receipt authorizes these bytes, not this path. Re-read them
753        // here rather than trusting the read that planned the run: a file
754        // edited since then is the user's, and a removal would be a silent
755        // loss.
756        match std::fs::read(destination) {
757            Ok(held) if &Sha256::of(&held) == vouched => {}
758            _ => {
759                kept.push(destination.clone());
760                continue;
761            }
762        }
763        match std::fs::remove_file(destination) {
764            Ok(()) => crate::transaction::sync_parent(destination)?,
765            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
766            Err(source) => {
767                return Err(stopped(Failure::Error(AppError::Io(source)), &completed));
768            }
769        }
770        lines.push(format!("swept: {destination}"));
771        completed.push(destination.clone());
772        reached(&mut passed, interrupt)?;
773    }
774
775    let mut directories: BTreeSet<Utf8PathBuf> = BTreeSet::new();
776    for (destination, _) in removals {
777        let mut parent = destination.parent();
778        while let Some(directory) = parent {
779            if !layout.roots.iter().any(|root| directory.starts_with(root))
780                && !directory.starts_with(&layout.state_root)
781                && !layout
782                    .legacy_shared
783                    .as_ref()
784                    .is_some_and(|legacy| directory.starts_with(legacy))
785            {
786                break;
787            }
788            directories.insert(directory.to_owned());
789            parent = directory.parent();
790        }
791    }
792    let mut stop = layout.roots.clone();
793    stop.push(layout.state_root.clone());
794    prune_empty(&directories, &stop, lines);
795
796    // A removal the byte check skipped leaves a file behind, so the record
797    // keeps vouching for it. Dropping it would make the leftover
798    // unrecorded, and the doctor could no longer name what is there.
799    let mut receipt = receipt.clone();
800    for destination in &kept {
801        if let Some((_, digest)) = removals.iter().find(|(path, _)| path == destination) {
802            receipt.written.insert(destination.clone(), digest.clone());
803        }
804        lines.push(format!("kept (changed since the record): {destination}"));
805    }
806    let empty = receipt.written.is_empty();
807    let receipt_bytes = receipt.to_json().into_bytes();
808
809    // The receipt is last. Until it lands, the previous one still describes
810    // the home, and what this run wrote is reported rather than vouched for.
811    if empty {
812        match std::fs::remove_file(&layout.receipt) {
813            Ok(()) => crate::transaction::sync_parent(&layout.receipt)?,
814            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
815            Err(source) => {
816                return Err(Failure::Error(AppError::Receipt(format!(
817                    "{}: {source}",
818                    layout.receipt
819                ))));
820            }
821        }
822    } else {
823        replace_one(layout, &layout.receipt, &receipt_bytes).map_err(|failure| match failure {
824            Failure::Error(cause) => Failure::Error(AppError::Receipt(format!(
825                "{}: {cause}; the files above are written and the previous receipt still stands, so run this again",
826                layout.receipt
827            ))),
828            abandoned @ Failure::Abandoned => abandoned,
829        })?;
830    }
831    reached(&mut passed, interrupt)?;
832    Ok(())
833}
834
835/// The refusal a run that stopped partway carries.
836fn stopped(failure: Failure, completed: &[Utf8PathBuf]) -> Failure {
837    let Failure::Error(cause) = failure else {
838        return failure;
839    };
840    let done: Vec<String> = completed.iter().map(ToString::to_string).collect();
841    let finished = if done.is_empty() {
842        "no destination was written".to_string()
843    } else {
844        format!("these destinations are written: {}", done.join(", "))
845    };
846    Failure::Error(AppError::Refused(format!(
847        "skill install stopped: {cause}; {finished}, the previous receipt still stands, and running this again finishes the rest"
848    )))
849}
850
851/// Stage one destination and rename it into place.
852///
853/// The chain is inspected again immediately before the rename, so a link
854/// substituted between the plan and the write is refused rather than
855/// followed.
856fn replace_one(layout: &Layout, destination: &Utf8Path, bytes: &[u8]) -> Result<(), Failure> {
857    let refuse = || {
858        owning_root(layout, destination)
859            .and_then(|root| blocked_by(root, destination))
860            .map(|one| Failure::Error(refuse_blocked(std::slice::from_ref(&one))))
861    };
862    // Before the scratch file is created, so nothing is written through a
863    // component that already refuses.
864    if let Some(refusal) = refuse() {
865        return Err(refusal);
866    }
867    let scratch = Stage::write(destination, bytes)?;
868    // And again before the rename, so a component swapped in between is
869    // refused rather than followed.
870    if let Some(refusal) = refuse() {
871        Stage::discard(&scratch);
872        return Err(refusal);
873    }
874    Stage::replace(&scratch, destination)?;
875    Ok(())
876}
877
878#[cfg(test)]
879mod tests {
880    #![allow(
881        clippy::unwrap_used,
882        reason = "a test panics as its failure signal, not as control flow"
883    )]
884
885    use std::collections::BTreeMap;
886
887    use super::*;
888
889    fn root(dir: &tempfile::TempDir) -> Utf8PathBuf {
890        Utf8PathBuf::from(dir.path().to_str().unwrap())
891    }
892
893    /// A digest of every file a run is answerable for, under one scratch
894    /// home.
895    ///
896    /// The lock and the holder note are the run's own workings rather than
897    /// destinations, so a comparison that counted them would report a run as
898    /// having changed the home when it changed only its own scaffolding.
899    fn tree(dir: &tempfile::TempDir) -> BTreeMap<String, Sha256> {
900        walkdir::WalkDir::new(dir.path())
901            .into_iter()
902            .filter_map(Result::ok)
903            .filter(|entry| entry.file_type().is_file())
904            .filter_map(|entry| {
905                let path = entry.path().to_str()?.to_string();
906                let bytes = std::fs::read(entry.path()).ok()?;
907                Some((path, Sha256::of(&bytes)))
908            })
909            .filter(|(path, _)| {
910                !path.contains("/backups/")
911                    && !["lock", "holder"].iter().any(|suffix| {
912                        std::path::Path::new(path)
913                            .extension()
914                            .is_some_and(|found| found == *suffix)
915                    })
916            })
917            .collect()
918    }
919
920    /// The layout a home directory implies, selecting both agent roots.
921    fn home(dir: &tempfile::TempDir) -> Layout {
922        let home = root(dir);
923        let state = home.join(crate::domain::paths::STATE_ROOT);
924        Layout {
925            roots: vec![home.join(AGENTS_ROOT), home.join(CLAUDE_ROOT)],
926            receipt: state.join(crate::domain::paths::SKILL_RECEIPT_FILE),
927            legacy_receipt: home.join(crate::domain::paths::LEGACY_SKILL_RECEIPT_PATH),
928            legacy_shared: Some(home.join(LEGACY_SHARED_ROOT)),
929            state_root: state,
930        }
931    }
932
933    /// The same layout narrowed to one selected root, which leaves the
934    /// retired root alone.
935    fn select(layout: &Layout, index: usize) -> Layout {
936        Layout {
937            roots: vec![layout.roots[index].clone()],
938            legacy_shared: None,
939            ..layout.clone()
940        }
941    }
942
943    /// The retired root of a layout that sweeps it.
944    fn legacy(layout: &Layout) -> &Utf8Path {
945        layout.legacy_shared.as_deref().unwrap()
946    }
947
948    fn package_files(root: &Utf8Path, name: &str) -> Vec<Utf8PathBuf> {
949        crate::embedded::skill_package(name)
950            .unwrap()
951            .into_iter()
952            .map(|(relative, _)| root.join(name).join(relative))
953            .collect()
954    }
955
956    #[test]
957    fn a_package_is_skill_md_plus_its_references_and_every_shared_artifact() {
958        let package = crate::embedded::skill_package("sdd-setup").unwrap();
959        let names: Vec<&str> = package.iter().map(|(path, _)| path.as_str()).collect();
960        assert!(names.contains(&"SKILL.md"));
961        for (shared, _) in crate::embedded::shared_artifacts() {
962            assert!(names.contains(&format!("references/{shared}").as_str()));
963        }
964        assert!(names.contains(&"references/landing.md"));
965        assert!(
966            names
967                .iter()
968                .all(|name| *name == "SKILL.md" || name.starts_with("references/"))
969        );
970        assert!(crate::embedded::skill_package("no-such-skill").is_err());
971    }
972
973    #[test]
974    fn an_install_lands_every_package_file_and_records_each_digest() {
975        let dir = tempfile::tempdir().unwrap();
976        let layout = home(&dir);
977        install(&layout, true, false).unwrap();
978        let record = SkillRecord::load(&layout.receipt);
979        assert_eq!(record.schema_version, 2);
980        assert_eq!(record.engine_version, env!("CARGO_PKG_VERSION"));
981        for root in &layout.roots {
982            for name in crate::embedded::skill_names() {
983                for path in package_files(root, name) {
984                    assert!(path.is_file(), "{path} did not land");
985                    let digest = Sha256::of(&std::fs::read(&path).unwrap());
986                    assert!(record.wrote(&path, &digest), "{path} was not recorded");
987                }
988            }
989        }
990    }
991
992    #[test]
993    fn a_preview_lists_every_destination_and_writes_nothing() {
994        let dir = tempfile::tempdir().unwrap();
995        let layout = home(&dir);
996        let lines = install(&layout, false, false).unwrap();
997        assert_eq!(lines.last().unwrap(), "DRY RUN: no files written");
998        let packages: usize = crate::embedded::skill_names()
999            .into_iter()
1000            .map(|name| crate::embedded::skill_package(name).unwrap().len())
1001            .sum();
1002        assert_eq!(lines.len(), packages * 2 + 1);
1003        assert!(!layout.roots[0].exists());
1004        assert!(!layout.receipt.exists());
1005    }
1006
1007    #[test]
1008    fn a_second_install_is_idempotent_and_writes_nothing() {
1009        let dir = tempfile::tempdir().unwrap();
1010        let layout = home(&dir);
1011        install(&layout, true, false).unwrap();
1012        let before = std::fs::metadata(layout.roots[0].join("sdd-setup/SKILL.md"))
1013            .unwrap()
1014            .modified()
1015            .unwrap();
1016        let receipt_before = std::fs::read(&layout.receipt).unwrap();
1017        install(&layout, true, false).unwrap();
1018        assert_eq!(
1019            std::fs::metadata(layout.roots[0].join("sdd-setup/SKILL.md"))
1020                .unwrap()
1021                .modified()
1022                .unwrap(),
1023            before
1024        );
1025        assert_eq!(std::fs::read(&layout.receipt).unwrap(), receipt_before);
1026    }
1027
1028    #[test]
1029    fn the_retired_root_is_a_root_the_component_check_knows() {
1030        let dir = tempfile::tempdir().unwrap();
1031        let mut layout = home(&dir);
1032        // The retired root is home-relative and the state root follows
1033        // `XDG_STATE_HOME`, so a moved state root leaves the retired root
1034        // outside it. A sweep there would otherwise unlink through
1035        // components nothing inspected.
1036        layout.state_root = root(&dir).join("moved/state");
1037        let leftover = legacy(&layout).join("plan-gate.md");
1038        assert_eq!(owning_root(&layout, &leftover), Some(legacy(&layout)));
1039    }
1040
1041    #[test]
1042    fn a_stale_package_file_the_receipt_vouches_for_is_replaced_without_force() {
1043        let dir = tempfile::tempdir().unwrap();
1044        let layout = home(&dir);
1045        install(&layout, true, false).unwrap();
1046
1047        let mut stale = SkillRecord::load(&layout.receipt);
1048        let destination = layout.roots[0].join("sdd-setup/references/plan-gate.md");
1049        std::fs::write(&destination, "older canon bytes\n").unwrap();
1050        stale
1051            .written
1052            .insert(destination.clone(), Sha256::of(b"older canon bytes\n"));
1053        crate::adapters::fs::write_file(&layout.receipt, stale.to_json().as_bytes()).unwrap();
1054
1055        install(&layout, true, false).unwrap();
1056        assert!(
1057            std::fs::read_to_string(&destination)
1058                .unwrap()
1059                .contains("# The plan gate")
1060        );
1061    }
1062
1063    #[test]
1064    fn an_edited_reference_refuses_the_install_naming_every_conflict() {
1065        let dir = tempfile::tempdir().unwrap();
1066        let layout = home(&dir);
1067        install(&layout, true, false).unwrap();
1068        let edited = layout.roots[1].join("sdd-setup/references/plan-gate.md");
1069        std::fs::write(&edited, "mine\n").unwrap();
1070        let message = install(&layout, true, false).unwrap_err().to_string();
1071        assert!(message.contains(edited.as_str()), "{message}");
1072        assert_eq!(std::fs::read_to_string(&edited).unwrap(), "mine\n");
1073    }
1074
1075    #[test]
1076    fn force_replaces_an_edited_file_and_records_the_new_digest() {
1077        let dir = tempfile::tempdir().unwrap();
1078        let layout = home(&dir);
1079        install(&layout, true, false).unwrap();
1080        let edited = layout.roots[1].join("sdd-setup/SKILL.md");
1081        std::fs::write(&edited, "mine\n").unwrap();
1082        install(&layout, true, true).unwrap();
1083        let held = std::fs::read(&edited).unwrap();
1084        assert!(String::from_utf8_lossy(&held).contains("name: sdd-setup"));
1085        assert!(SkillRecord::load(&layout.receipt).wrote(&edited, &Sha256::of(&held)));
1086    }
1087
1088    /// The defect this phase closes: an uninstall that consulted the payload
1089    /// and not the receipt deleted a skill the operator had edited.
1090    #[test]
1091    fn an_edited_skill_md_survives_uninstall_and_is_named_as_kept() {
1092        let dir = tempfile::tempdir().unwrap();
1093        let layout = home(&dir);
1094        install(&layout, true, false).unwrap();
1095        let edited = layout.roots[0].join("sdd-setup/SKILL.md");
1096        std::fs::write(&edited, "mine\n").unwrap();
1097
1098        let lines = uninstall(&layout, true).unwrap();
1099        assert_eq!(std::fs::read_to_string(&edited).unwrap(), "mine\n");
1100        assert!(
1101            lines
1102                .iter()
1103                .any(|line| line == &format!("kept (edited): {edited}")),
1104            "{lines:?}"
1105        );
1106    }
1107
1108    #[test]
1109    fn an_edited_reference_survives_uninstall_and_its_directory_stays() {
1110        let dir = tempfile::tempdir().unwrap();
1111        let layout = home(&dir);
1112        install(&layout, true, false).unwrap();
1113        let edited = layout.roots[0].join("sdd-setup/references/plan-gate.md");
1114        std::fs::write(&edited, "mine\n").unwrap();
1115        uninstall(&layout, true).unwrap();
1116        assert_eq!(std::fs::read_to_string(&edited).unwrap(), "mine\n");
1117        assert!(layout.roots[0].join("sdd-setup/references").is_dir());
1118    }
1119
1120    #[test]
1121    fn an_uninstall_removes_a_directory_only_when_nothing_recorded_or_foreign_remains() {
1122        let dir = tempfile::tempdir().unwrap();
1123        let layout = home(&dir);
1124        install(&layout, true, false).unwrap();
1125        let mine = layout.roots[1].join("sdd-setup/notes.md");
1126        std::fs::write(&mine, "mine").unwrap();
1127
1128        let lines = uninstall(&layout, true).unwrap();
1129        assert!(!layout.roots[1].join("sdd-write-docs").exists());
1130        assert!(!layout.roots[1].join("sdd-setup/SKILL.md").exists());
1131        assert!(!layout.roots[1].join("sdd-setup/references").exists());
1132        assert_eq!(std::fs::read_to_string(&mine).unwrap(), "mine");
1133        assert!(
1134            lines
1135                .iter()
1136                .any(|line| line.starts_with("kept (not empty):"))
1137        );
1138        // A re-run on the emptied roots is a no-op, not an error.
1139        uninstall(&layout, true).unwrap();
1140    }
1141
1142    #[test]
1143    fn the_retired_shared_root_is_swept_when_the_receipt_vouches_for_it() {
1144        let dir = tempfile::tempdir().unwrap();
1145        let layout = home(&dir);
1146        // Stand in for a 0.8.0 home: two gate files under the retired root,
1147        // each vouched for by the receipt that release wrote.
1148        let mut older = SkillRecord::new();
1149        for (name, bytes) in crate::embedded::shared_artifacts() {
1150            let destination = legacy(&layout).join(&name);
1151            crate::adapters::fs::write_file(&destination, bytes).unwrap();
1152            older.written.insert(destination, Sha256::of(bytes));
1153        }
1154        crate::adapters::fs::write_file(&layout.receipt, older.to_json().as_bytes()).unwrap();
1155
1156        install(&layout, true, false).unwrap();
1157        assert!(
1158            !legacy(&layout).exists(),
1159            "the retired shared root survived"
1160        );
1161        assert!(
1162            layout.roots[0]
1163                .join("sdd-setup/references/plan-gate.md")
1164                .is_file()
1165        );
1166    }
1167
1168    #[test]
1169    fn a_one_family_install_keeps_the_legacy_gates() {
1170        let dir = tempfile::tempdir().unwrap();
1171        let both = home(&dir);
1172        let mut older = SkillRecord::new();
1173        for (name, bytes) in crate::embedded::shared_artifacts() {
1174            let destination = legacy(&both).join(&name);
1175            crate::adapters::fs::write_file(&destination, bytes).unwrap();
1176            older.written.insert(destination, Sha256::of(bytes));
1177        }
1178        crate::adapters::fs::write_file(&both.receipt, older.to_json().as_bytes()).unwrap();
1179
1180        for index in 0..both.roots.len() {
1181            let one = select(&both, index);
1182            install(&one, true, false).unwrap();
1183            uninstall(&one, true).unwrap();
1184        }
1185        for (name, bytes) in crate::embedded::shared_artifacts() {
1186            assert_eq!(std::fs::read(legacy(&both).join(&name)).unwrap(), bytes);
1187        }
1188    }
1189
1190    #[test]
1191    fn an_unrecorded_file_at_the_retired_shared_root_is_kept() {
1192        let dir = tempfile::tempdir().unwrap();
1193        let layout = home(&dir);
1194        let leftover = legacy(&layout).join("plan-gate.md");
1195        crate::adapters::fs::write_file(&leftover, b"mine\n").unwrap();
1196        install(&layout, true, false).unwrap();
1197        assert_eq!(std::fs::read(&leftover).unwrap(), b"mine\n");
1198    }
1199
1200    #[test]
1201    fn a_symlinked_package_directory_skill_md_reference_or_parent_is_a_typed_conflict() {
1202        for linked in ["sdd-setup", "sdd-setup/SKILL.md", "sdd-setup/references"] {
1203            let dir = tempfile::tempdir().unwrap();
1204            let layout = home(&dir);
1205            let elsewhere = root(&dir).join("elsewhere");
1206            std::fs::create_dir_all(&elsewhere).unwrap();
1207            let target = layout.roots[0].join(linked);
1208            std::fs::create_dir_all(target.parent().unwrap()).unwrap();
1209            std::os::unix::fs::symlink(&elsewhere, target.as_std_path()).unwrap();
1210
1211            for force in [false, true] {
1212                let message = install(&layout, true, force).unwrap_err().to_string();
1213                assert!(
1214                    message.contains("symlink"),
1215                    "{linked} with force {force}: {message}"
1216                );
1217                assert!(message.contains(target.as_str()), "{message}");
1218            }
1219            assert!(!elsewhere.join("SKILL.md").exists());
1220            assert!(target.is_symlink(), "the link itself was replaced");
1221        }
1222    }
1223
1224    #[test]
1225    fn a_symlink_whose_target_matches_the_recorded_digest_is_still_a_conflict() {
1226        let dir = tempfile::tempdir().unwrap();
1227        let layout = home(&dir);
1228        install(&layout, true, false).unwrap();
1229        let destination = layout.roots[0].join("sdd-setup/SKILL.md");
1230        let elsewhere = root(&dir).join("copy.md");
1231        std::fs::copy(&destination, &elsewhere).unwrap();
1232        std::fs::remove_file(&destination).unwrap();
1233        std::os::unix::fs::symlink(&elsewhere, destination.as_std_path()).unwrap();
1234
1235        let message = install(&layout, true, true).unwrap_err().to_string();
1236        assert!(message.contains("symlink"), "{message}");
1237        let lines = uninstall(&layout, true).unwrap();
1238        assert!(
1239            lines
1240                .iter()
1241                .any(|line| line.starts_with(KEPT_BLOCKED) && line.contains(destination.as_str())),
1242            "{lines:?}"
1243        );
1244        assert!(destination.is_symlink());
1245    }
1246
1247    /// The layout with its Claude root spelled through a link, the way a
1248    /// configuration directory holds its skill root, and the link itself.
1249    fn through_a_link(dir: &tempfile::TempDir, layout: &Layout) -> (Layout, Utf8PathBuf) {
1250        let config = root(dir).join("config");
1251        std::fs::create_dir_all(&config).unwrap();
1252        let link = config.join("skills");
1253        std::os::unix::fs::symlink(&layout.roots[1], link.as_std_path()).unwrap();
1254        let mut linked = layout.clone();
1255        linked.roots[1] = link.clone();
1256        (linked, link)
1257    }
1258
1259    #[test]
1260    fn a_root_that_is_a_link_is_emptied_through_its_target() {
1261        let dir = tempfile::tempdir().unwrap();
1262        let layout = home(&dir);
1263        install(&layout, true, false).unwrap();
1264        let (linked, link) = through_a_link(&dir, &layout);
1265        uninstall(&linked, true).unwrap();
1266        for root in &layout.roots {
1267            assert!(
1268                !root.join("sdd-setup/SKILL.md").exists(),
1269                "kept under {root}"
1270            );
1271        }
1272        assert!(link.is_symlink(), "the operator's link was removed");
1273        assert!(!layout.receipt.exists());
1274    }
1275
1276    #[test]
1277    fn a_receipt_recorded_under_the_link_still_vouches_for_the_files() {
1278        let dir = tempfile::tempdir().unwrap();
1279        let layout = home(&dir);
1280        install(&layout, true, false).unwrap();
1281        let (linked, link) = through_a_link(&dir, &layout);
1282        let mut record = load_receipt(&layout);
1283        record.written = std::mem::take(&mut record.written)
1284            .into_iter()
1285            .map(|(path, digest)| match path.strip_prefix(&layout.roots[1]) {
1286                Ok(rest) => (link.join(rest), digest),
1287                Err(_) => (path, digest),
1288            })
1289            .collect();
1290        crate::adapters::fs::write_file(&layout.receipt, record.to_json().as_bytes()).unwrap();
1291        uninstall(&linked, true).unwrap();
1292        assert!(!layout.roots[1].join("sdd-setup/SKILL.md").exists());
1293        assert!(!layout.receipt.exists());
1294    }
1295
1296    #[test]
1297    fn two_roots_that_reach_one_directory_list_each_file_once() {
1298        let dir = tempfile::tempdir().unwrap();
1299        let layout = home(&dir);
1300        install(&layout, true, false).unwrap();
1301        let (mut linked, link) = through_a_link(&dir, &layout);
1302        linked.roots = vec![layout.roots[1].clone(), link];
1303        let lines = uninstall(&linked, false).unwrap();
1304        let listed = lines
1305            .iter()
1306            .filter(|line| line.ends_with("sdd-setup/SKILL.md"))
1307            .count();
1308        assert_eq!(listed, 1, "{lines:?}");
1309    }
1310
1311    #[test]
1312    fn a_linked_package_is_kept_while_every_other_file_goes() {
1313        let dir = tempfile::tempdir().unwrap();
1314        let layout = home(&dir);
1315        install(&layout, true, false).unwrap();
1316        let package = layout.roots[1].join("sdd-setup");
1317        let elsewhere = root(&dir).join("elsewhere");
1318        std::fs::rename(&package, &elsewhere).unwrap();
1319        std::os::unix::fs::symlink(&elsewhere, package.as_std_path()).unwrap();
1320
1321        let lines = uninstall(&layout, true).unwrap();
1322        assert!(
1323            lines
1324                .iter()
1325                .any(|line| line.starts_with(KEPT_BLOCKED) && line.contains(package.as_str())),
1326            "{lines:?}"
1327        );
1328        assert!(package.is_symlink());
1329        assert!(
1330            elsewhere.join("SKILL.md").is_file(),
1331            "removed through the link"
1332        );
1333        assert!(!layout.roots[0].join("sdd-setup/SKILL.md").exists());
1334        assert!(!layout.roots[1].join("sdd-write-docs/SKILL.md").exists());
1335        assert!(layout.receipt.exists(), "the kept files left the receipt");
1336    }
1337
1338    #[test]
1339    fn two_roots_resolving_to_one_path_are_written_once() {
1340        let dir = tempfile::tempdir().unwrap();
1341        let mut layout = home(&dir);
1342        layout.roots = vec![layout.roots[0].clone()];
1343        let lines = install(&layout, false, false).unwrap();
1344        let landed = lines
1345            .iter()
1346            .filter(|line| line.ends_with("sdd-setup/SKILL.md"))
1347            .count();
1348        assert_eq!(landed, 1);
1349    }
1350
1351    #[test]
1352    fn a_second_installer_refuses_while_the_lock_is_held_naming_the_holder() {
1353        let dir = tempfile::tempdir().unwrap();
1354        let layout = home(&dir);
1355        // The home holds packages first, so the uninstall below has work to
1356        // do and reaches the lock rather than returning early.
1357        install(&layout, true, false).unwrap();
1358        age(&layout);
1359        let _held = Lock::exclusive(&layout.lock_path(), "skill install").unwrap();
1360        let error = install(&layout, true, false).unwrap_err();
1361        assert_eq!(error.kind(), "Busy");
1362        assert_eq!(error.exit_code(), 73);
1363        assert!(error.to_string().contains("skill install"));
1364        let error = uninstall(&layout, true).unwrap_err();
1365        assert_eq!(error.kind(), "Busy");
1366    }
1367
1368    /// A run the process did not finish is put back before the next one
1369    /// writes anything, at every boundary of the persistence order.
1370    /// Stand in for a home an older release left: every package file holds
1371    /// its bytes, and the receipt vouches for each, so the next install has
1372    /// a replacement at every boundary.
1373    fn age(layout: &Layout) {
1374        let mut older = SkillRecord::new();
1375        for root in &layout.roots {
1376            for name in crate::embedded::skill_names() {
1377                for path in package_files(root, name) {
1378                    crate::adapters::fs::write_file(&path, b"older\n").unwrap();
1379                    older.written.insert(path, Sha256::of(b"older\n"));
1380                }
1381            }
1382        }
1383        crate::adapters::fs::write_file(&layout.receipt, older.to_json().as_bytes()).unwrap();
1384    }
1385
1386    /// A run the process did not finish leaves whole files, the previous
1387    /// receipt, and a home the next run finishes, at every boundary of the
1388    /// persistence order.
1389    #[test]
1390    fn an_interrupted_install_leaves_whole_files_and_a_rerun_finishes() {
1391        let mut boundaries = 0usize;
1392        for after in 1..200 {
1393            let dir = tempfile::tempdir().unwrap();
1394            // One root, because the matrix walks every boundary and the
1395            // second root doubles the walk without adding a kind of
1396            // boundary to it.
1397            let layout = select(&home(&dir), 0);
1398            age(&layout);
1399            let aged = std::fs::read(&layout.receipt).unwrap();
1400
1401            let outcome = install_with(&layout, true, false, Interrupt { after: Some(after) });
1402            let Err(Failure::Abandoned) = outcome else {
1403                // The run finished before this boundary, so every earlier
1404                // boundary has already been walked.
1405                break;
1406            };
1407            boundaries = after;
1408
1409            // Every file the interrupted run left is whole: it holds either
1410            // the bytes it had before or the bytes the payload carries, and
1411            // never a fragment of the replacement.
1412            for name in crate::embedded::skill_names() {
1413                for path in package_files(&layout.roots[0], name) {
1414                    let held = std::fs::read(&path).unwrap();
1415                    assert!(
1416                        held == b"older\n" || !held.is_empty(),
1417                        "after {after}: {path} is not a whole file"
1418                    );
1419                }
1420            }
1421            // Until the run reaches its last write, the receipt the previous
1422            // run left still describes the home.
1423            let receipt = std::fs::read(&layout.receipt).unwrap();
1424            assert!(
1425                receipt == aged || !SkillRecord::load(&layout.receipt).written.is_empty(),
1426                "after {after}: the receipt is neither the old one nor a new one"
1427            );
1428
1429            // Every few boundaries, take the home all the way, so the matrix
1430            // proves an interrupted run leaves one an install still lands
1431            // into rather than only one that reads back whole.
1432            if after % 3 == 0 {
1433                install(&layout, true, false).unwrap();
1434                let record = SkillRecord::load(&layout.receipt);
1435                for path in package_files(&layout.roots[0], "sdd-setup") {
1436                    let digest = Sha256::of(&std::fs::read(&path).unwrap());
1437                    assert!(record.wrote(&path, &digest), "after {after}: {path}");
1438                }
1439            }
1440        }
1441        assert!(boundaries > 5, "only {boundaries} boundaries were walked");
1442    }
1443
1444    #[test]
1445    fn a_second_interruption_still_leaves_a_home_a_rerun_finishes() {
1446        let dir = tempfile::tempdir().unwrap();
1447        let layout = home(&dir);
1448        age(&layout);
1449        for after in [3, 5] {
1450            let Err(Failure::Abandoned) =
1451                install_with(&layout, true, false, Interrupt { after: Some(after) })
1452            else {
1453                panic!("the run was not interrupted after {after}");
1454            };
1455        }
1456        install(&layout, true, false).unwrap();
1457        let record = SkillRecord::load(&layout.receipt);
1458        for path in package_files(&layout.roots[0], "sdd-setup") {
1459            let digest = Sha256::of(&std::fs::read(&path).unwrap());
1460            assert!(record.wrote(&path, &digest), "{path}");
1461        }
1462    }
1463
1464    #[test]
1465    fn a_receipt_write_failure_reports_what_the_run_wrote() {
1466        let dir = tempfile::tempdir().unwrap();
1467        // The receipt sits in its own directory, so denying writes there
1468        // stops the receipt alone and leaves the lock beside it reachable.
1469        let mut layout = home(&dir);
1470        let vault = layout.state_root.join("receipt");
1471        layout.receipt = vault.join("skills.json");
1472        age(&layout);
1473        let aged = std::fs::read(&layout.receipt).unwrap();
1474
1475        let mut permissions = std::fs::metadata(&vault).unwrap().permissions();
1476        std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o500);
1477        std::fs::set_permissions(&vault, permissions.clone()).unwrap();
1478
1479        let error = install(&layout, true, false).unwrap_err();
1480
1481        std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o700);
1482        std::fs::set_permissions(&vault, permissions).unwrap();
1483
1484        let message = error.to_string();
1485        assert!(message.contains(layout.receipt.as_str()), "{message}");
1486        assert!(message.contains("run this again"), "{message}");
1487
1488        // The package files are written and the previous receipt still
1489        // stands, which is what the next run reads.
1490        assert_eq!(std::fs::read(&layout.receipt).unwrap(), aged);
1491        assert_ne!(
1492            std::fs::read(layout.roots[0].join("sdd-setup/SKILL.md")).unwrap(),
1493            b"older\n"
1494        );
1495
1496        // Running it again finishes the work the failure left.
1497        install(&layout, true, false).unwrap();
1498        let record = SkillRecord::load(&layout.receipt);
1499        for path in package_files(&layout.roots[0], "sdd-setup") {
1500            let digest = Sha256::of(&std::fs::read(&path).unwrap());
1501            assert!(record.wrote(&path, &digest), "{path}");
1502        }
1503    }
1504
1505    #[test]
1506    fn a_schema_one_receipt_reads_through_the_adapter() {
1507        let dir = tempfile::tempdir().unwrap();
1508        let layout = home(&dir);
1509        let destination = layout.roots[0].join("sdd-setup/SKILL.md");
1510        crate::adapters::fs::write_file(&destination, b"older\n").unwrap();
1511        crate::adapters::fs::write_file(
1512            &layout.receipt,
1513            format!(
1514                "{{\"schema_version\":1,\"written\":{{\"{destination}\":\"{}\"}}}}",
1515                Sha256::of(b"older\n")
1516            )
1517            .as_bytes(),
1518        )
1519        .unwrap();
1520        // The stale copy is the tool's, so the install replaces it without
1521        // asking, which only happens if the adapter read the old shape.
1522        install(&layout, true, false).unwrap();
1523        assert!(
1524            String::from_utf8_lossy(&std::fs::read(&destination).unwrap())
1525                .contains("name: sdd-setup")
1526        );
1527        assert_eq!(SkillRecord::load(&layout.receipt).schema_version, 2);
1528    }
1529
1530    #[test]
1531    fn a_receipt_at_the_legacy_path_is_read_once_and_rewritten_at_the_resolved_one() {
1532        let dir = tempfile::tempdir().unwrap();
1533        let mut layout = home(&dir);
1534        layout.state_root = root(&dir).join("xdg/spec-driven-docs");
1535        layout.receipt = layout
1536            .state_root
1537            .join(crate::domain::paths::SKILL_RECEIPT_FILE);
1538
1539        let destination = layout.roots[0].join("sdd-setup/SKILL.md");
1540        crate::adapters::fs::write_file(&destination, b"older\n").unwrap();
1541        let mut legacy = SkillRecord::new();
1542        legacy
1543            .written
1544            .insert(destination.clone(), Sha256::of(b"older\n"));
1545        crate::adapters::fs::write_file(&layout.legacy_receipt, legacy.to_json().as_bytes())
1546            .unwrap();
1547
1548        install(&layout, true, false).unwrap();
1549        assert!(layout.receipt.is_file());
1550        assert!(
1551            String::from_utf8_lossy(&std::fs::read(&destination).unwrap())
1552                .contains("name: sdd-setup")
1553        );
1554    }
1555
1556    #[test]
1557    fn a_write_that_fails_partway_reports_what_it_finished() {
1558        let dir = tempfile::tempdir().unwrap();
1559        let layout = home(&dir);
1560        install(&layout, true, false).unwrap();
1561
1562        // Every destination carries recognisable bytes, then one package
1563        // directory in the second root denies writes, so the failure lands
1564        // after the first root is already rewritten.
1565        for root in &layout.roots {
1566            for name in crate::embedded::skill_names() {
1567                for path in package_files(root, name) {
1568                    std::fs::write(&path, format!("previous {name}\n")).unwrap();
1569                }
1570            }
1571        }
1572        let blocked = layout.roots[1].join("sdd-write-docs");
1573        let mut permissions = std::fs::metadata(&blocked).unwrap().permissions();
1574        std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o500);
1575        std::fs::set_permissions(&blocked, permissions.clone()).unwrap();
1576
1577        let message = install(&layout, true, true).unwrap_err().to_string();
1578
1579        std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o700);
1580        std::fs::set_permissions(&blocked, permissions).unwrap();
1581
1582        assert!(message.contains("skill install stopped"), "{message}");
1583        assert!(
1584            message.contains("these destinations are written"),
1585            "{message}"
1586        );
1587        assert!(message.contains("running this again"), "{message}");
1588        // The first root is written and the second is not, which is what the
1589        // report says and what the rerun finishes.
1590        assert_ne!(
1591            std::fs::read(layout.roots[0].join("sdd-setup/SKILL.md")).unwrap(),
1592            b"previous sdd-setup\n"
1593        );
1594        assert_eq!(
1595            std::fs::read(layout.roots[1].join("sdd-write-docs/SKILL.md")).unwrap(),
1596            b"previous sdd-write-docs\n"
1597        );
1598
1599        install(&layout, true, true).unwrap();
1600        let record = SkillRecord::load(&layout.receipt);
1601        for root in &layout.roots {
1602            for path in package_files(root, "sdd-setup") {
1603                let digest = Sha256::of(&std::fs::read(&path).unwrap());
1604                assert!(record.wrote(&path, &digest), "{path}");
1605            }
1606        }
1607    }
1608
1609    #[test]
1610    fn an_uninstall_of_one_root_keeps_the_others_entries() {
1611        let dir = tempfile::tempdir().unwrap();
1612        let layout = home(&dir);
1613        install(&layout, true, false).unwrap();
1614        uninstall(&select(&layout, 1), true).unwrap();
1615        let kept = SkillRecord::load(&layout.receipt);
1616        assert!(
1617            kept.written
1618                .keys()
1619                .all(|path| path.starts_with(&layout.roots[0]))
1620        );
1621        assert!(!kept.written.is_empty());
1622        assert!(
1623            layout.roots[0]
1624                .join("sdd-setup/references/plan-gate.md")
1625                .is_file()
1626        );
1627    }
1628
1629    #[test]
1630    fn either_agent_alone_lands_a_whole_package() {
1631        for index in 0..2 {
1632            let dir = tempfile::tempdir().unwrap();
1633            let layout = home(&dir);
1634            let narrowed = select(&layout, index);
1635            install(&narrowed, true, false).unwrap();
1636            for path in package_files(&layout.roots[index], "sdd-setup") {
1637                assert!(path.is_file(), "{path} did not land");
1638            }
1639            assert!(!layout.roots[1 - index].exists());
1640        }
1641    }
1642
1643    #[test]
1644    fn the_last_uninstall_takes_the_receipt_with_it() {
1645        let dir = tempfile::tempdir().unwrap();
1646        let layout = home(&dir);
1647        install(&layout, true, false).unwrap();
1648        uninstall(&layout, true).unwrap();
1649        assert!(
1650            !layout.receipt.exists(),
1651            "the receipt outlived every file it vouched for"
1652        );
1653        for root in &layout.roots {
1654            assert!(!root.join("sdd-setup").exists());
1655        }
1656    }
1657
1658    #[test]
1659    fn an_uninstall_on_a_home_this_tool_never_wrote_into_touches_nothing() {
1660        let dir = tempfile::tempdir().unwrap();
1661        let layout = home(&dir);
1662        let before = tree(&dir);
1663        uninstall(&layout, true).unwrap();
1664        assert_eq!(tree(&dir), before);
1665        assert!(!layout.state_root.exists());
1666    }
1667}