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/// Remove every installed skill package under each root, previewing by default.
372///
373/// # Errors
374///
375/// As [`install`], except that nothing here refuses on foreign bytes: a
376/// file the receipt cannot vouch for stays and is named.
377pub fn uninstall(layout: &Layout, apply: bool) -> Result<Vec<String>, AppError> {
378    settle(uninstall_with(layout, apply, Interrupt::default()))
379}
380
381fn settle(result: Result<Vec<String>, Failure>) -> Result<Vec<String>, AppError> {
382    result.map_err(|failure| match failure {
383        Failure::Error(error) => error,
384        Failure::Abandoned => AppError::Other(anyhow::anyhow!(
385            "the run was interrupted; the next invocation recovers it"
386        )),
387    })
388}
389
390/// The lock an applied run holds for the whole of its own reasoning.
391///
392/// A preview takes none: it writes nothing, and a preview that refused
393/// because somebody else was installing would fail for a reason the
394/// operator cannot act on. An applied run takes it before it reads a
395/// receipt or scans a destination, so every decision it makes is one the
396/// world still agrees with when it executes. A run that derived its
397/// removals before the lock could remove files a newer install had just
398/// written.
399///
400/// # Errors
401///
402/// [`AppError::Busy`] when another process holds it.
403fn held(layout: &Layout, apply: bool, purpose: &str) -> Result<Option<Lock>, Failure> {
404    if !apply {
405        return Ok(None);
406    }
407    let lock = Lock::exclusive(&layout.lock_path(), purpose)?;
408    Ok(Some(lock))
409}
410
411/// The install, with the recovery tests' interruption point. Only the
412/// tests run it: they build the homes earlier releases left.
413#[cfg(test)]
414fn install_with(
415    layout: &Layout,
416    apply: bool,
417    force: bool,
418    interrupt: Interrupt,
419) -> Result<Vec<String>, Failure> {
420    let _lock = held(layout, apply, "skill install")?;
421    let planned = plan(&layout.roots)?;
422    let mut lines: Vec<String> = planned
423        .iter()
424        .map(|entry| entry.destination.to_string())
425        .collect();
426
427    let record = load_receipt(layout);
428    let kept: BTreeSet<Utf8PathBuf> = planned
429        .iter()
430        .map(|entry| entry.destination.clone())
431        .collect();
432    let stale = leftovers(&layout.scanned(), &record, &kept);
433    for (destination, _, ours) in &stale {
434        if *ours {
435            lines.push(format!(
436                "to sweep (no longer in the payload): {destination}"
437            ));
438        } else {
439            lines.push(format!("kept (edited): {destination}"));
440        }
441    }
442
443    let mut destinations: Vec<Utf8PathBuf> = planned
444        .iter()
445        .map(|entry| entry.destination.clone())
446        .collect();
447    destinations.push(layout.receipt.clone());
448    let refused = blocked(layout, &destinations);
449    for one in &refused {
450        lines.push(format!("conflict: {one}"));
451    }
452
453    let mut foreign: Vec<Utf8PathBuf> = Vec::new();
454    let mut writes: Vec<Planned> = Vec::new();
455    // What the receipt will vouch for is every destination that holds the
456    // payload's bytes once this run ends, not only the ones this run wrote.
457    // A previous run that stopped partway left files written and unrecorded,
458    // and a record that skipped them would never take them back.
459    let mut vouched: Vec<Planned> = Vec::new();
460    for entry in &planned {
461        if refused
462            .iter()
463            .any(|one| entry.destination.starts_with(&one.path))
464        {
465            continue;
466        }
467        vouched.push(entry.clone());
468        match standing(&entry.destination, &entry.digest, &record)? {
469            Standing::Current => {}
470            Standing::Foreign => {
471                foreign.push(entry.destination.clone());
472                writes.push(entry.clone());
473            }
474            Standing::Absent | Standing::Recorded => writes.push(entry.clone()),
475        }
476    }
477    for destination in &foreign {
478        lines.push(format!(
479            "conflict: {destination} holds bytes this tool did not write"
480        ));
481    }
482
483    if !apply {
484        lines.push("DRY RUN: no files written".to_string());
485        return Ok(lines);
486    }
487    if !refused.is_empty() {
488        return Err(refuse_blocked(&refused).into());
489    }
490    if !force && !foreign.is_empty() {
491        let paths: Vec<&str> = foreign.iter().map(|path| path.as_str()).collect();
492        return Err(AppError::Refused(format!(
493            "destinations hold bytes this tool did not write: {}; re-run with --force to overwrite",
494            paths.join(", ")
495        ))
496        .into());
497    }
498
499    let swept: Vec<Utf8PathBuf> = stale
500        .iter()
501        .filter(|(_, _, ours)| *ours)
502        .map(|(destination, _, _)| destination.clone())
503        .collect();
504    let receipt = next_receipt(&record, &vouched, &swept);
505    run_transaction(
506        layout,
507        &writes,
508        &stale
509            .into_iter()
510            .filter(|(_, _, ours)| *ours)
511            .map(|(destination, digest, _)| (destination, digest))
512            .collect::<Vec<_>>(),
513        &receipt,
514        &mut lines,
515        interrupt,
516    )?;
517    Ok(lines)
518}
519
520/// The uninstall, with the recovery tests' interruption point.
521fn uninstall_with(
522    layout: &Layout,
523    apply: bool,
524    interrupt: Interrupt,
525) -> Result<Vec<String>, Failure> {
526    // A home with no receipt has nothing this tool wrote, so an uninstall
527    // there removes nothing and takes no lock: creating the lock file
528    // would itself be the write that home was promised it would not get.
529    let _lock = held(layout, apply && layout.receipt.exists(), "skill uninstall")?;
530    let planned = plan(&layout.roots)?;
531    let record = load_receipt(layout);
532    let mut lines: Vec<String> = Vec::new();
533    let mut removals: Vec<(Utf8PathBuf, Sha256)> = Vec::new();
534
535    let refused = blocked(
536        layout,
537        &planned
538            .iter()
539            .map(|entry| entry.destination.clone())
540            .collect::<Vec<_>>(),
541    );
542    for one in &refused {
543        lines.push(format!("conflict: {one}"));
544    }
545
546    for entry in &planned {
547        if refused
548            .iter()
549            .any(|one| entry.destination.starts_with(&one.path))
550        {
551            continue;
552        }
553        if !entry.destination.is_file() {
554            continue;
555        }
556        let found = Sha256::of(&std::fs::read(&entry.destination)?);
557        if record.wrote(&entry.destination, &found) {
558            lines.push(entry.destination.to_string());
559            removals.push((entry.destination.clone(), found));
560        } else if found == entry.digest {
561            // The payload's own bytes with no receipt behind them: this
562            // tool cannot tell its copy from one the user placed there.
563            lines.push(format!("kept (not this tool's): {}", entry.destination));
564        } else {
565            lines.push(format!("kept (edited): {}", entry.destination));
566        }
567    }
568
569    let keep: BTreeSet<Utf8PathBuf> = removals
570        .iter()
571        .map(|(destination, _)| destination.clone())
572        .collect();
573    for (destination, digest, ours) in leftovers(&layout.scanned(), &record, &keep) {
574        if ours {
575            lines.push(format!("sweep (no longer in the payload): {destination}"));
576            removals.push((destination, digest));
577        } else if destination.exists() {
578            lines.push(format!("kept (edited): {destination}"));
579        }
580    }
581
582    if !apply {
583        lines.push("DRY RUN: no files removed".to_string());
584        return Ok(lines);
585    }
586    if !refused.is_empty() {
587        return Err(refuse_blocked(&refused).into());
588    }
589    // A home this tool never wrote into has nothing to take back, and an
590    // uninstall there must leave it exactly as it found it — no state root,
591    // no lock file, nothing.
592    if removals.is_empty() && !layout.receipt.exists() {
593        return Ok(lines);
594    }
595
596    let gone: Vec<Utf8PathBuf> = removals
597        .iter()
598        .map(|(destination, _)| destination.clone())
599        .collect();
600    let receipt = next_receipt(&record, &[], &gone);
601    run_transaction(layout, &[], &removals, &receipt, &mut lines, interrupt)?;
602    Ok(lines)
603}
604
605fn refuse_blocked(refused: &[Blocked]) -> AppError {
606    let named: Vec<String> = refused.iter().map(Blocked::to_string).collect();
607    AppError::Refused(format!(
608        "destinations cannot be written through: {}; move them aside and run this again",
609        named.join("; ")
610    ))
611}
612
613/// Replace each file, remove what is gone, and record it last.
614///
615/// Each destination is replaced in its own directory, one rename at a time,
616/// and the receipt is written after all of them. There is no journal and no
617/// backup store: a run that stops partway leaves whole files, the previous
618/// receipt, and a report naming what it finished, and running it again
619/// finishes the rest.
620fn run_transaction(
621    layout: &Layout,
622    writes: &[Planned],
623    removals: &[(Utf8PathBuf, Sha256)],
624    receipt: &SkillRecord,
625    lines: &mut Vec<String>,
626    interrupt: Interrupt,
627) -> Result<(), Failure> {
628    // A receipt that vouches for nothing is removed rather than written:
629    // an empty record is a file that says the tool wrote something here,
630    // and it did not.
631    let empty = receipt.written.is_empty();
632    let receipt_bytes = receipt.to_json().into_bytes();
633    let receipt_current = if empty {
634        !layout.receipt.exists()
635    } else {
636        std::fs::read(&layout.receipt).is_ok_and(|held| held == receipt_bytes)
637    };
638    if writes.is_empty() && removals.is_empty() && receipt_current {
639        return Ok(());
640    }
641
642    let mut passed = 0usize;
643    let mut completed: Vec<Utf8PathBuf> = Vec::new();
644    // What the run meant to remove and did not, because the bytes there
645    // are no longer the ones the receipt vouches for. The record keeps
646    // them, so the doctor can still name what is left behind.
647    let mut kept: Vec<Utf8PathBuf> = Vec::new();
648
649    for entry in writes {
650        replace_one(layout, &entry.destination, entry.bytes)
651            .map_err(|failure| stopped(failure, &completed))?;
652        completed.push(entry.destination.clone());
653        reached(&mut passed, interrupt)?;
654    }
655    for (destination, vouched) in removals {
656        // A component swapped since the run was planned is refused rather
657        // than followed: a removal through a link would unlink somebody
658        // else's file.
659        //
660        if let Some(root) = owning_root(layout, destination)
661            && let Some(one) = blocked_by(root, destination)
662        {
663            return Err(stopped(
664                Failure::Error(refuse_blocked(std::slice::from_ref(&one))),
665                &completed,
666            ));
667        }
668        // The receipt authorizes these bytes, not this path. Re-read them
669        // here rather than trusting the read that planned the run: a file
670        // edited since then is the user's, and a removal would be a silent
671        // loss.
672        match std::fs::read(destination) {
673            Ok(held) if &Sha256::of(&held) == vouched => {}
674            _ => {
675                kept.push(destination.clone());
676                continue;
677            }
678        }
679        match std::fs::remove_file(destination) {
680            Ok(()) => crate::transaction::sync_parent(destination)?,
681            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
682            Err(source) => {
683                return Err(stopped(Failure::Error(AppError::Io(source)), &completed));
684            }
685        }
686        lines.push(format!("swept: {destination}"));
687        completed.push(destination.clone());
688        reached(&mut passed, interrupt)?;
689    }
690
691    let mut directories: BTreeSet<Utf8PathBuf> = BTreeSet::new();
692    for (destination, _) in removals {
693        let mut parent = destination.parent();
694        while let Some(directory) = parent {
695            if !layout.roots.iter().any(|root| directory.starts_with(root))
696                && !directory.starts_with(&layout.state_root)
697                && !layout
698                    .legacy_shared
699                    .as_ref()
700                    .is_some_and(|legacy| directory.starts_with(legacy))
701            {
702                break;
703            }
704            directories.insert(directory.to_owned());
705            parent = directory.parent();
706        }
707    }
708    let mut stop = layout.roots.clone();
709    stop.push(layout.state_root.clone());
710    prune_empty(&directories, &stop, lines);
711
712    // A removal the byte check skipped leaves a file behind, so the record
713    // keeps vouching for it. Dropping it would make the leftover
714    // unrecorded, and the doctor could no longer name what is there.
715    let mut receipt = receipt.clone();
716    for destination in &kept {
717        if let Some((_, digest)) = removals.iter().find(|(path, _)| path == destination) {
718            receipt.written.insert(destination.clone(), digest.clone());
719        }
720        lines.push(format!("kept (changed since the record): {destination}"));
721    }
722    let empty = receipt.written.is_empty();
723    let receipt_bytes = receipt.to_json().into_bytes();
724
725    // The receipt is last. Until it lands, the previous one still describes
726    // the home, and what this run wrote is reported rather than vouched for.
727    if empty {
728        match std::fs::remove_file(&layout.receipt) {
729            Ok(()) => crate::transaction::sync_parent(&layout.receipt)?,
730            Err(source) if source.kind() == std::io::ErrorKind::NotFound => {}
731            Err(source) => {
732                return Err(Failure::Error(AppError::Receipt(format!(
733                    "{}: {source}",
734                    layout.receipt
735                ))));
736            }
737        }
738    } else {
739        replace_one(layout, &layout.receipt, &receipt_bytes).map_err(|failure| match failure {
740            Failure::Error(cause) => Failure::Error(AppError::Receipt(format!(
741                "{}: {cause}; the files above are written and the previous receipt still stands, so run this again",
742                layout.receipt
743            ))),
744            abandoned @ Failure::Abandoned => abandoned,
745        })?;
746    }
747    reached(&mut passed, interrupt)?;
748    Ok(())
749}
750
751/// The refusal a run that stopped partway carries.
752fn stopped(failure: Failure, completed: &[Utf8PathBuf]) -> Failure {
753    let Failure::Error(cause) = failure else {
754        return failure;
755    };
756    let done: Vec<String> = completed.iter().map(ToString::to_string).collect();
757    let finished = if done.is_empty() {
758        "no destination was written".to_string()
759    } else {
760        format!("these destinations are written: {}", done.join(", "))
761    };
762    Failure::Error(AppError::Refused(format!(
763        "skill install stopped: {cause}; {finished}, the previous receipt still stands, and running this again finishes the rest"
764    )))
765}
766
767/// Stage one destination and rename it into place.
768///
769/// The chain is inspected again immediately before the rename, so a link
770/// substituted between the plan and the write is refused rather than
771/// followed.
772fn replace_one(layout: &Layout, destination: &Utf8Path, bytes: &[u8]) -> Result<(), Failure> {
773    let refuse = || {
774        owning_root(layout, destination)
775            .and_then(|root| blocked_by(root, destination))
776            .map(|one| Failure::Error(refuse_blocked(std::slice::from_ref(&one))))
777    };
778    // Before the scratch file is created, so nothing is written through a
779    // component that already refuses.
780    if let Some(refusal) = refuse() {
781        return Err(refusal);
782    }
783    let scratch = Stage::write(destination, bytes)?;
784    // And again before the rename, so a component swapped in between is
785    // refused rather than followed.
786    if let Some(refusal) = refuse() {
787        Stage::discard(&scratch);
788        return Err(refusal);
789    }
790    Stage::replace(&scratch, destination)?;
791    Ok(())
792}
793
794#[cfg(test)]
795mod tests {
796    #![allow(
797        clippy::unwrap_used,
798        reason = "a test panics as its failure signal, not as control flow"
799    )]
800
801    use std::collections::BTreeMap;
802
803    use super::*;
804
805    fn root(dir: &tempfile::TempDir) -> Utf8PathBuf {
806        Utf8PathBuf::from(dir.path().to_str().unwrap())
807    }
808
809    /// A digest of every file a run is answerable for, under one scratch
810    /// home.
811    ///
812    /// The lock and the holder note are the run's own workings rather than
813    /// destinations, so a comparison that counted them would report a run as
814    /// having changed the home when it changed only its own scaffolding.
815    fn tree(dir: &tempfile::TempDir) -> BTreeMap<String, Sha256> {
816        walkdir::WalkDir::new(dir.path())
817            .into_iter()
818            .filter_map(Result::ok)
819            .filter(|entry| entry.file_type().is_file())
820            .filter_map(|entry| {
821                let path = entry.path().to_str()?.to_string();
822                let bytes = std::fs::read(entry.path()).ok()?;
823                Some((path, Sha256::of(&bytes)))
824            })
825            .filter(|(path, _)| {
826                !path.contains("/backups/")
827                    && !["lock", "holder"].iter().any(|suffix| {
828                        std::path::Path::new(path)
829                            .extension()
830                            .is_some_and(|found| found == *suffix)
831                    })
832            })
833            .collect()
834    }
835
836    /// The layout a home directory implies, selecting both agent roots.
837    fn home(dir: &tempfile::TempDir) -> Layout {
838        let home = root(dir);
839        let state = home.join(crate::domain::paths::STATE_ROOT);
840        Layout {
841            roots: vec![home.join(AGENTS_ROOT), home.join(CLAUDE_ROOT)],
842            receipt: state.join(crate::domain::paths::SKILL_RECEIPT_FILE),
843            legacy_receipt: home.join(crate::domain::paths::LEGACY_SKILL_RECEIPT_PATH),
844            legacy_shared: Some(home.join(LEGACY_SHARED_ROOT)),
845            state_root: state,
846        }
847    }
848
849    /// The same layout narrowed to one selected root, which leaves the
850    /// retired root alone.
851    fn select(layout: &Layout, index: usize) -> Layout {
852        Layout {
853            roots: vec![layout.roots[index].clone()],
854            legacy_shared: None,
855            ..layout.clone()
856        }
857    }
858
859    /// The retired root of a layout that sweeps it.
860    fn legacy(layout: &Layout) -> &Utf8Path {
861        layout.legacy_shared.as_deref().unwrap()
862    }
863
864    fn package_files(root: &Utf8Path, name: &str) -> Vec<Utf8PathBuf> {
865        crate::embedded::skill_package(name)
866            .unwrap()
867            .into_iter()
868            .map(|(relative, _)| root.join(name).join(relative))
869            .collect()
870    }
871
872    #[test]
873    fn a_package_is_skill_md_plus_its_references_and_every_shared_artifact() {
874        let package = crate::embedded::skill_package("sdd-setup").unwrap();
875        let names: Vec<&str> = package.iter().map(|(path, _)| path.as_str()).collect();
876        assert!(names.contains(&"SKILL.md"));
877        for (shared, _) in crate::embedded::shared_artifacts() {
878            assert!(names.contains(&format!("references/{shared}").as_str()));
879        }
880        assert!(names.contains(&"references/landing.md"));
881        assert!(
882            names
883                .iter()
884                .all(|name| *name == "SKILL.md" || name.starts_with("references/"))
885        );
886        assert!(crate::embedded::skill_package("no-such-skill").is_err());
887    }
888
889    #[test]
890    fn an_install_lands_every_package_file_and_records_each_digest() {
891        let dir = tempfile::tempdir().unwrap();
892        let layout = home(&dir);
893        install(&layout, true, false).unwrap();
894        let record = SkillRecord::load(&layout.receipt);
895        assert_eq!(record.schema_version, 2);
896        assert_eq!(record.engine_version, env!("CARGO_PKG_VERSION"));
897        for root in &layout.roots {
898            for name in crate::embedded::skill_names() {
899                for path in package_files(root, name) {
900                    assert!(path.is_file(), "{path} did not land");
901                    let digest = Sha256::of(&std::fs::read(&path).unwrap());
902                    assert!(record.wrote(&path, &digest), "{path} was not recorded");
903                }
904            }
905        }
906    }
907
908    #[test]
909    fn a_preview_lists_every_destination_and_writes_nothing() {
910        let dir = tempfile::tempdir().unwrap();
911        let layout = home(&dir);
912        let lines = install(&layout, false, false).unwrap();
913        assert_eq!(lines.last().unwrap(), "DRY RUN: no files written");
914        let packages: usize = crate::embedded::skill_names()
915            .into_iter()
916            .map(|name| crate::embedded::skill_package(name).unwrap().len())
917            .sum();
918        assert_eq!(lines.len(), packages * 2 + 1);
919        assert!(!layout.roots[0].exists());
920        assert!(!layout.receipt.exists());
921    }
922
923    #[test]
924    fn a_second_install_is_idempotent_and_writes_nothing() {
925        let dir = tempfile::tempdir().unwrap();
926        let layout = home(&dir);
927        install(&layout, true, false).unwrap();
928        let before = std::fs::metadata(layout.roots[0].join("sdd-setup/SKILL.md"))
929            .unwrap()
930            .modified()
931            .unwrap();
932        let receipt_before = std::fs::read(&layout.receipt).unwrap();
933        install(&layout, true, false).unwrap();
934        assert_eq!(
935            std::fs::metadata(layout.roots[0].join("sdd-setup/SKILL.md"))
936                .unwrap()
937                .modified()
938                .unwrap(),
939            before
940        );
941        assert_eq!(std::fs::read(&layout.receipt).unwrap(), receipt_before);
942    }
943
944    #[test]
945    fn the_retired_root_is_a_root_the_component_check_knows() {
946        let dir = tempfile::tempdir().unwrap();
947        let mut layout = home(&dir);
948        // The retired root is home-relative and the state root follows
949        // `XDG_STATE_HOME`, so a moved state root leaves the retired root
950        // outside it. A sweep there would otherwise unlink through
951        // components nothing inspected.
952        layout.state_root = root(&dir).join("moved/state");
953        let leftover = legacy(&layout).join("plan-gate.md");
954        assert_eq!(owning_root(&layout, &leftover), Some(legacy(&layout)));
955    }
956
957    #[test]
958    fn a_stale_package_file_the_receipt_vouches_for_is_replaced_without_force() {
959        let dir = tempfile::tempdir().unwrap();
960        let layout = home(&dir);
961        install(&layout, true, false).unwrap();
962
963        let mut stale = SkillRecord::load(&layout.receipt);
964        let destination = layout.roots[0].join("sdd-setup/references/plan-gate.md");
965        std::fs::write(&destination, "older canon bytes\n").unwrap();
966        stale
967            .written
968            .insert(destination.clone(), Sha256::of(b"older canon bytes\n"));
969        crate::adapters::fs::write_file(&layout.receipt, stale.to_json().as_bytes()).unwrap();
970
971        install(&layout, true, false).unwrap();
972        assert!(
973            std::fs::read_to_string(&destination)
974                .unwrap()
975                .contains("# The plan gate")
976        );
977    }
978
979    #[test]
980    fn an_edited_reference_refuses_the_install_naming_every_conflict() {
981        let dir = tempfile::tempdir().unwrap();
982        let layout = home(&dir);
983        install(&layout, true, false).unwrap();
984        let edited = layout.roots[1].join("sdd-setup/references/plan-gate.md");
985        std::fs::write(&edited, "mine\n").unwrap();
986        let message = install(&layout, true, false).unwrap_err().to_string();
987        assert!(message.contains(edited.as_str()), "{message}");
988        assert_eq!(std::fs::read_to_string(&edited).unwrap(), "mine\n");
989    }
990
991    #[test]
992    fn force_replaces_an_edited_file_and_records_the_new_digest() {
993        let dir = tempfile::tempdir().unwrap();
994        let layout = home(&dir);
995        install(&layout, true, false).unwrap();
996        let edited = layout.roots[1].join("sdd-setup/SKILL.md");
997        std::fs::write(&edited, "mine\n").unwrap();
998        install(&layout, true, true).unwrap();
999        let held = std::fs::read(&edited).unwrap();
1000        assert!(String::from_utf8_lossy(&held).contains("name: sdd-setup"));
1001        assert!(SkillRecord::load(&layout.receipt).wrote(&edited, &Sha256::of(&held)));
1002    }
1003
1004    /// The defect this phase closes: an uninstall that consulted the payload
1005    /// and not the receipt deleted a skill the operator had edited.
1006    #[test]
1007    fn an_edited_skill_md_survives_uninstall_and_is_named_as_kept() {
1008        let dir = tempfile::tempdir().unwrap();
1009        let layout = home(&dir);
1010        install(&layout, true, false).unwrap();
1011        let edited = layout.roots[0].join("sdd-setup/SKILL.md");
1012        std::fs::write(&edited, "mine\n").unwrap();
1013
1014        let lines = uninstall(&layout, true).unwrap();
1015        assert_eq!(std::fs::read_to_string(&edited).unwrap(), "mine\n");
1016        assert!(
1017            lines
1018                .iter()
1019                .any(|line| line == &format!("kept (edited): {edited}")),
1020            "{lines:?}"
1021        );
1022    }
1023
1024    #[test]
1025    fn an_edited_reference_survives_uninstall_and_its_directory_stays() {
1026        let dir = tempfile::tempdir().unwrap();
1027        let layout = home(&dir);
1028        install(&layout, true, false).unwrap();
1029        let edited = layout.roots[0].join("sdd-setup/references/plan-gate.md");
1030        std::fs::write(&edited, "mine\n").unwrap();
1031        uninstall(&layout, true).unwrap();
1032        assert_eq!(std::fs::read_to_string(&edited).unwrap(), "mine\n");
1033        assert!(layout.roots[0].join("sdd-setup/references").is_dir());
1034    }
1035
1036    #[test]
1037    fn an_uninstall_removes_a_directory_only_when_nothing_recorded_or_foreign_remains() {
1038        let dir = tempfile::tempdir().unwrap();
1039        let layout = home(&dir);
1040        install(&layout, true, false).unwrap();
1041        let mine = layout.roots[1].join("sdd-setup/notes.md");
1042        std::fs::write(&mine, "mine").unwrap();
1043
1044        let lines = uninstall(&layout, true).unwrap();
1045        assert!(!layout.roots[1].join("sdd-write-docs").exists());
1046        assert!(!layout.roots[1].join("sdd-setup/SKILL.md").exists());
1047        assert!(!layout.roots[1].join("sdd-setup/references").exists());
1048        assert_eq!(std::fs::read_to_string(&mine).unwrap(), "mine");
1049        assert!(
1050            lines
1051                .iter()
1052                .any(|line| line.starts_with("kept (not empty):"))
1053        );
1054        // A re-run on the emptied roots is a no-op, not an error.
1055        uninstall(&layout, true).unwrap();
1056    }
1057
1058    #[test]
1059    fn the_retired_shared_root_is_swept_when_the_receipt_vouches_for_it() {
1060        let dir = tempfile::tempdir().unwrap();
1061        let layout = home(&dir);
1062        // Stand in for a 0.8.0 home: two gate files under the retired root,
1063        // each vouched for by the receipt that release wrote.
1064        let mut older = SkillRecord::new();
1065        for (name, bytes) in crate::embedded::shared_artifacts() {
1066            let destination = legacy(&layout).join(&name);
1067            crate::adapters::fs::write_file(&destination, bytes).unwrap();
1068            older.written.insert(destination, Sha256::of(bytes));
1069        }
1070        crate::adapters::fs::write_file(&layout.receipt, older.to_json().as_bytes()).unwrap();
1071
1072        install(&layout, true, false).unwrap();
1073        assert!(
1074            !legacy(&layout).exists(),
1075            "the retired shared root survived"
1076        );
1077        assert!(
1078            layout.roots[0]
1079                .join("sdd-setup/references/plan-gate.md")
1080                .is_file()
1081        );
1082    }
1083
1084    #[test]
1085    fn a_one_family_install_keeps_the_legacy_gates() {
1086        let dir = tempfile::tempdir().unwrap();
1087        let both = home(&dir);
1088        let mut older = SkillRecord::new();
1089        for (name, bytes) in crate::embedded::shared_artifacts() {
1090            let destination = legacy(&both).join(&name);
1091            crate::adapters::fs::write_file(&destination, bytes).unwrap();
1092            older.written.insert(destination, Sha256::of(bytes));
1093        }
1094        crate::adapters::fs::write_file(&both.receipt, older.to_json().as_bytes()).unwrap();
1095
1096        for index in 0..both.roots.len() {
1097            let one = select(&both, index);
1098            install(&one, true, false).unwrap();
1099            uninstall(&one, true).unwrap();
1100        }
1101        for (name, bytes) in crate::embedded::shared_artifacts() {
1102            assert_eq!(std::fs::read(legacy(&both).join(&name)).unwrap(), bytes);
1103        }
1104    }
1105
1106    #[test]
1107    fn an_unrecorded_file_at_the_retired_shared_root_is_kept() {
1108        let dir = tempfile::tempdir().unwrap();
1109        let layout = home(&dir);
1110        let leftover = legacy(&layout).join("plan-gate.md");
1111        crate::adapters::fs::write_file(&leftover, b"mine\n").unwrap();
1112        install(&layout, true, false).unwrap();
1113        assert_eq!(std::fs::read(&leftover).unwrap(), b"mine\n");
1114    }
1115
1116    #[test]
1117    fn a_symlinked_package_directory_skill_md_reference_or_parent_is_a_typed_conflict() {
1118        for linked in ["sdd-setup", "sdd-setup/SKILL.md", "sdd-setup/references"] {
1119            let dir = tempfile::tempdir().unwrap();
1120            let layout = home(&dir);
1121            let elsewhere = root(&dir).join("elsewhere");
1122            std::fs::create_dir_all(&elsewhere).unwrap();
1123            let target = layout.roots[0].join(linked);
1124            std::fs::create_dir_all(target.parent().unwrap()).unwrap();
1125            std::os::unix::fs::symlink(&elsewhere, target.as_std_path()).unwrap();
1126
1127            for force in [false, true] {
1128                let message = install(&layout, true, force).unwrap_err().to_string();
1129                assert!(
1130                    message.contains("symlink"),
1131                    "{linked} with force {force}: {message}"
1132                );
1133                assert!(message.contains(target.as_str()), "{message}");
1134            }
1135            assert!(!elsewhere.join("SKILL.md").exists());
1136            assert!(target.is_symlink(), "the link itself was replaced");
1137        }
1138    }
1139
1140    #[test]
1141    fn a_symlink_whose_target_matches_the_recorded_digest_is_still_a_conflict() {
1142        let dir = tempfile::tempdir().unwrap();
1143        let layout = home(&dir);
1144        install(&layout, true, false).unwrap();
1145        let destination = layout.roots[0].join("sdd-setup/SKILL.md");
1146        let elsewhere = root(&dir).join("copy.md");
1147        std::fs::copy(&destination, &elsewhere).unwrap();
1148        std::fs::remove_file(&destination).unwrap();
1149        std::os::unix::fs::symlink(&elsewhere, destination.as_std_path()).unwrap();
1150
1151        let message = install(&layout, true, true).unwrap_err().to_string();
1152        assert!(message.contains("symlink"), "{message}");
1153        let message = uninstall(&layout, true).unwrap_err().to_string();
1154        assert!(message.contains("symlink"), "{message}");
1155        assert!(destination.is_symlink());
1156    }
1157
1158    #[test]
1159    fn two_roots_resolving_to_one_path_are_written_once() {
1160        let dir = tempfile::tempdir().unwrap();
1161        let mut layout = home(&dir);
1162        layout.roots = vec![layout.roots[0].clone()];
1163        let lines = install(&layout, false, false).unwrap();
1164        let landed = lines
1165            .iter()
1166            .filter(|line| line.ends_with("sdd-setup/SKILL.md"))
1167            .count();
1168        assert_eq!(landed, 1);
1169    }
1170
1171    #[test]
1172    fn a_second_installer_refuses_while_the_lock_is_held_naming_the_holder() {
1173        let dir = tempfile::tempdir().unwrap();
1174        let layout = home(&dir);
1175        // The home holds packages first, so the uninstall below has work to
1176        // do and reaches the lock rather than returning early.
1177        install(&layout, true, false).unwrap();
1178        age(&layout);
1179        let _held = Lock::exclusive(&layout.lock_path(), "skill install").unwrap();
1180        let error = install(&layout, true, false).unwrap_err();
1181        assert_eq!(error.kind(), "Busy");
1182        assert_eq!(error.exit_code(), 73);
1183        assert!(error.to_string().contains("skill install"));
1184        let error = uninstall(&layout, true).unwrap_err();
1185        assert_eq!(error.kind(), "Busy");
1186    }
1187
1188    /// A run the process did not finish is put back before the next one
1189    /// writes anything, at every boundary of the persistence order.
1190    /// Stand in for a home an older release left: every package file holds
1191    /// its bytes, and the receipt vouches for each, so the next install has
1192    /// a replacement at every boundary.
1193    fn age(layout: &Layout) {
1194        let mut older = SkillRecord::new();
1195        for root in &layout.roots {
1196            for name in crate::embedded::skill_names() {
1197                for path in package_files(root, name) {
1198                    crate::adapters::fs::write_file(&path, b"older\n").unwrap();
1199                    older.written.insert(path, Sha256::of(b"older\n"));
1200                }
1201            }
1202        }
1203        crate::adapters::fs::write_file(&layout.receipt, older.to_json().as_bytes()).unwrap();
1204    }
1205
1206    /// A run the process did not finish leaves whole files, the previous
1207    /// receipt, and a home the next run finishes, at every boundary of the
1208    /// persistence order.
1209    #[test]
1210    fn an_interrupted_install_leaves_whole_files_and_a_rerun_finishes() {
1211        let mut boundaries = 0usize;
1212        for after in 1..200 {
1213            let dir = tempfile::tempdir().unwrap();
1214            // One root, because the matrix walks every boundary and the
1215            // second root doubles the walk without adding a kind of
1216            // boundary to it.
1217            let layout = select(&home(&dir), 0);
1218            age(&layout);
1219            let aged = std::fs::read(&layout.receipt).unwrap();
1220
1221            let outcome = install_with(&layout, true, false, Interrupt { after: Some(after) });
1222            let Err(Failure::Abandoned) = outcome else {
1223                // The run finished before this boundary, so every earlier
1224                // boundary has already been walked.
1225                break;
1226            };
1227            boundaries = after;
1228
1229            // Every file the interrupted run left is whole: it holds either
1230            // the bytes it had before or the bytes the payload carries, and
1231            // never a fragment of the replacement.
1232            for name in crate::embedded::skill_names() {
1233                for path in package_files(&layout.roots[0], name) {
1234                    let held = std::fs::read(&path).unwrap();
1235                    assert!(
1236                        held == b"older\n" || !held.is_empty(),
1237                        "after {after}: {path} is not a whole file"
1238                    );
1239                }
1240            }
1241            // Until the run reaches its last write, the receipt the previous
1242            // run left still describes the home.
1243            let receipt = std::fs::read(&layout.receipt).unwrap();
1244            assert!(
1245                receipt == aged || !SkillRecord::load(&layout.receipt).written.is_empty(),
1246                "after {after}: the receipt is neither the old one nor a new one"
1247            );
1248
1249            // Every few boundaries, take the home all the way, so the matrix
1250            // proves an interrupted run leaves one an install still lands
1251            // into rather than only one that reads back whole.
1252            if after % 3 == 0 {
1253                install(&layout, true, false).unwrap();
1254                let record = SkillRecord::load(&layout.receipt);
1255                for path in package_files(&layout.roots[0], "sdd-setup") {
1256                    let digest = Sha256::of(&std::fs::read(&path).unwrap());
1257                    assert!(record.wrote(&path, &digest), "after {after}: {path}");
1258                }
1259            }
1260        }
1261        assert!(boundaries > 5, "only {boundaries} boundaries were walked");
1262    }
1263
1264    #[test]
1265    fn a_second_interruption_still_leaves_a_home_a_rerun_finishes() {
1266        let dir = tempfile::tempdir().unwrap();
1267        let layout = home(&dir);
1268        age(&layout);
1269        for after in [3, 5] {
1270            let Err(Failure::Abandoned) =
1271                install_with(&layout, true, false, Interrupt { after: Some(after) })
1272            else {
1273                panic!("the run was not interrupted after {after}");
1274            };
1275        }
1276        install(&layout, true, false).unwrap();
1277        let record = SkillRecord::load(&layout.receipt);
1278        for path in package_files(&layout.roots[0], "sdd-setup") {
1279            let digest = Sha256::of(&std::fs::read(&path).unwrap());
1280            assert!(record.wrote(&path, &digest), "{path}");
1281        }
1282    }
1283
1284    #[test]
1285    fn a_receipt_write_failure_reports_what_the_run_wrote() {
1286        let dir = tempfile::tempdir().unwrap();
1287        // The receipt sits in its own directory, so denying writes there
1288        // stops the receipt alone and leaves the lock beside it reachable.
1289        let mut layout = home(&dir);
1290        let vault = layout.state_root.join("receipt");
1291        layout.receipt = vault.join("skills.json");
1292        age(&layout);
1293        let aged = std::fs::read(&layout.receipt).unwrap();
1294
1295        let mut permissions = std::fs::metadata(&vault).unwrap().permissions();
1296        std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o500);
1297        std::fs::set_permissions(&vault, permissions.clone()).unwrap();
1298
1299        let error = install(&layout, true, false).unwrap_err();
1300
1301        std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o700);
1302        std::fs::set_permissions(&vault, permissions).unwrap();
1303
1304        let message = error.to_string();
1305        assert!(message.contains(layout.receipt.as_str()), "{message}");
1306        assert!(message.contains("run this again"), "{message}");
1307
1308        // The package files are written and the previous receipt still
1309        // stands, which is what the next run reads.
1310        assert_eq!(std::fs::read(&layout.receipt).unwrap(), aged);
1311        assert_ne!(
1312            std::fs::read(layout.roots[0].join("sdd-setup/SKILL.md")).unwrap(),
1313            b"older\n"
1314        );
1315
1316        // Running it again finishes the work the failure left.
1317        install(&layout, true, false).unwrap();
1318        let record = SkillRecord::load(&layout.receipt);
1319        for path in package_files(&layout.roots[0], "sdd-setup") {
1320            let digest = Sha256::of(&std::fs::read(&path).unwrap());
1321            assert!(record.wrote(&path, &digest), "{path}");
1322        }
1323    }
1324
1325    #[test]
1326    fn a_schema_one_receipt_reads_through_the_adapter() {
1327        let dir = tempfile::tempdir().unwrap();
1328        let layout = home(&dir);
1329        let destination = layout.roots[0].join("sdd-setup/SKILL.md");
1330        crate::adapters::fs::write_file(&destination, b"older\n").unwrap();
1331        crate::adapters::fs::write_file(
1332            &layout.receipt,
1333            format!(
1334                "{{\"schema_version\":1,\"written\":{{\"{destination}\":\"{}\"}}}}",
1335                Sha256::of(b"older\n")
1336            )
1337            .as_bytes(),
1338        )
1339        .unwrap();
1340        // The stale copy is the tool's, so the install replaces it without
1341        // asking, which only happens if the adapter read the old shape.
1342        install(&layout, true, false).unwrap();
1343        assert!(
1344            String::from_utf8_lossy(&std::fs::read(&destination).unwrap())
1345                .contains("name: sdd-setup")
1346        );
1347        assert_eq!(SkillRecord::load(&layout.receipt).schema_version, 2);
1348    }
1349
1350    #[test]
1351    fn a_receipt_at_the_legacy_path_is_read_once_and_rewritten_at_the_resolved_one() {
1352        let dir = tempfile::tempdir().unwrap();
1353        let mut layout = home(&dir);
1354        layout.state_root = root(&dir).join("xdg/spec-driven-docs");
1355        layout.receipt = layout
1356            .state_root
1357            .join(crate::domain::paths::SKILL_RECEIPT_FILE);
1358
1359        let destination = layout.roots[0].join("sdd-setup/SKILL.md");
1360        crate::adapters::fs::write_file(&destination, b"older\n").unwrap();
1361        let mut legacy = SkillRecord::new();
1362        legacy
1363            .written
1364            .insert(destination.clone(), Sha256::of(b"older\n"));
1365        crate::adapters::fs::write_file(&layout.legacy_receipt, legacy.to_json().as_bytes())
1366            .unwrap();
1367
1368        install(&layout, true, false).unwrap();
1369        assert!(layout.receipt.is_file());
1370        assert!(
1371            String::from_utf8_lossy(&std::fs::read(&destination).unwrap())
1372                .contains("name: sdd-setup")
1373        );
1374    }
1375
1376    #[test]
1377    fn a_write_that_fails_partway_reports_what_it_finished() {
1378        let dir = tempfile::tempdir().unwrap();
1379        let layout = home(&dir);
1380        install(&layout, true, false).unwrap();
1381
1382        // Every destination carries recognisable bytes, then one package
1383        // directory in the second root denies writes, so the failure lands
1384        // after the first root is already rewritten.
1385        for root in &layout.roots {
1386            for name in crate::embedded::skill_names() {
1387                for path in package_files(root, name) {
1388                    std::fs::write(&path, format!("previous {name}\n")).unwrap();
1389                }
1390            }
1391        }
1392        let blocked = layout.roots[1].join("sdd-write-docs");
1393        let mut permissions = std::fs::metadata(&blocked).unwrap().permissions();
1394        std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o500);
1395        std::fs::set_permissions(&blocked, permissions.clone()).unwrap();
1396
1397        let message = install(&layout, true, true).unwrap_err().to_string();
1398
1399        std::os::unix::fs::PermissionsExt::set_mode(&mut permissions, 0o700);
1400        std::fs::set_permissions(&blocked, permissions).unwrap();
1401
1402        assert!(message.contains("skill install stopped"), "{message}");
1403        assert!(
1404            message.contains("these destinations are written"),
1405            "{message}"
1406        );
1407        assert!(message.contains("running this again"), "{message}");
1408        // The first root is written and the second is not, which is what the
1409        // report says and what the rerun finishes.
1410        assert_ne!(
1411            std::fs::read(layout.roots[0].join("sdd-setup/SKILL.md")).unwrap(),
1412            b"previous sdd-setup\n"
1413        );
1414        assert_eq!(
1415            std::fs::read(layout.roots[1].join("sdd-write-docs/SKILL.md")).unwrap(),
1416            b"previous sdd-write-docs\n"
1417        );
1418
1419        install(&layout, true, true).unwrap();
1420        let record = SkillRecord::load(&layout.receipt);
1421        for root in &layout.roots {
1422            for path in package_files(root, "sdd-setup") {
1423                let digest = Sha256::of(&std::fs::read(&path).unwrap());
1424                assert!(record.wrote(&path, &digest), "{path}");
1425            }
1426        }
1427    }
1428
1429    #[test]
1430    fn an_uninstall_of_one_root_keeps_the_others_entries() {
1431        let dir = tempfile::tempdir().unwrap();
1432        let layout = home(&dir);
1433        install(&layout, true, false).unwrap();
1434        uninstall(&select(&layout, 1), true).unwrap();
1435        let kept = SkillRecord::load(&layout.receipt);
1436        assert!(
1437            kept.written
1438                .keys()
1439                .all(|path| path.starts_with(&layout.roots[0]))
1440        );
1441        assert!(!kept.written.is_empty());
1442        assert!(
1443            layout.roots[0]
1444                .join("sdd-setup/references/plan-gate.md")
1445                .is_file()
1446        );
1447    }
1448
1449    #[test]
1450    fn either_agent_alone_lands_a_whole_package() {
1451        for index in 0..2 {
1452            let dir = tempfile::tempdir().unwrap();
1453            let layout = home(&dir);
1454            let narrowed = select(&layout, index);
1455            install(&narrowed, true, false).unwrap();
1456            for path in package_files(&layout.roots[index], "sdd-setup") {
1457                assert!(path.is_file(), "{path} did not land");
1458            }
1459            assert!(!layout.roots[1 - index].exists());
1460        }
1461    }
1462
1463    #[test]
1464    fn the_last_uninstall_takes_the_receipt_with_it() {
1465        let dir = tempfile::tempdir().unwrap();
1466        let layout = home(&dir);
1467        install(&layout, true, false).unwrap();
1468        uninstall(&layout, true).unwrap();
1469        assert!(
1470            !layout.receipt.exists(),
1471            "the receipt outlived every file it vouched for"
1472        );
1473        for root in &layout.roots {
1474            assert!(!root.join("sdd-setup").exists());
1475        }
1476    }
1477
1478    #[test]
1479    fn an_uninstall_on_a_home_this_tool_never_wrote_into_touches_nothing() {
1480        let dir = tempfile::tempdir().unwrap();
1481        let layout = home(&dir);
1482        let before = tree(&dir);
1483        uninstall(&layout, true).unwrap();
1484        assert_eq!(tree(&dir), before);
1485        assert!(!layout.state_root.exists());
1486    }
1487}