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